mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[GH-ISSUE #6927] [Performance]: Reduce PostgreSQL round trips and write amplification in multi-node client IP synchronization #4584
Labels
No labels
backlog
bug
clarification needed
documentation
duplicate
enhancement
github_actions
good first issue
invalid
javascript
New Feature
PR welcomed
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
MHSanaei/3x-ui#4584
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @HamedSanaei on GitHub (Oct 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6927
Summary
At scale, collection and cross-node synchronization of client IPs generates a very large number of small PostgreSQL reads and writes. The current code correctly includes compare-and-set (CAS) protection against lost updates (see #6587), but the per-client/row SQL cost of the cluster IP synchronization path merits optimization.
This is a performance-only proposal. IP-limit correctness and security must take precedence over query-count reduction. No Redis or external cache is requested.
Affected paths
internal/web/service/inbound_client_ips.go:MergeInboundClientIpsloads current rows, iterates incoming clients, andmergeExistingClientIpsexecutes per-row reads and CAS retries (SELECT ... WHERE id/UPDATE ... WHERE id AND ips = old).internal/web/job/check_client_ip_job.go:processObservedalready batches initial lookups but processes each client's IP row with guarded updates; keep that protection.internal/web/service/inbound_node_ips.go:upsertNodeClientIpsloads existing rows per GUID and issuesINSERT ... ON CONFLICT DO UPDATEindividually for each email, even when merged content is identical.Already implemented:
updateInboundClientIpsandmergeExistingClientIpsskip unchanged merged IP strings. This issue is NOT proposing to redo that fix; it targets the remaining round trips, per-row attribution upserts and duplicate processing.Production evidence (PostgreSQL 18)
Cumulative
pg_stat_statementsand table statistics collected since 2026-10-21:SELECT * FROM inbound_client_ips WHERE id = $1 ...UPDATE inbound_client_ips SET ips = ... WHERE id = ? AND ips = ?UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ?INSERT INTO node_client_ips ... ON CONFLICT ... DO UPDATEIn a separate 20-second sample: 542 per-ID IP reads, 153 CAS IP updates, and 118
node_client_ipsupserts. The IP-read calls themselves are fast, but their volume creates avoidable overhead.These counts characterize one workload and are not expected on all installations.
Suggested direction for discussion
upsertNodeClientIps, omit truly unchanged merged rows, including theON CONFLICTwrite; evaluate batched upsert with a deterministic lock/order strategy and PostgreSQLIS DISTINCT FROMwhere appropriate (plus portable SQLite behavior).MergeInboundClientIpswithout weakening optimistic concurrency. A stale snapshot must never overwrite more recent IPs: preserve CAS, retry/re-merge and deterministic ordering.Acceptance criteria
Related but separate: #6587 (lost-update correctness), #6286 (expiry), #6285 (orphaned GUID attribution). This issue targets database write amplification without altering their invariants.
@github-actions[bot] commented on GitHub (Oct 25, 2026):
The redundancy you measured is real, and part of it is a defect rather than just tuning. The two writers of
inbound_client_ips.ipsserialize the same IP set in opposite orders. So each one's "skip if unchanged" string compare fails after the other has written, and a row both of them touch gets rewritten on every cycle even when its IP set has not changed. Separately,mergeExistingClientIpsre-SELECTs every row it already holds in memory, andupsertNodeClientIpsupserts every email without comparing it to the stored row.1. The two writers sort the blob in opposite orders, so the unchanged-skip never fires on shared rows
The scan job writes oldest-first, with the IP as a tie-breaker (
internal/web/job/check_client_ip_job.go:588-593,sortedIpsFromMap):When the limit is enforced it writes
kept+allowedIps+historicalIps, concatenated in that order (check_client_ip_job.go:550-551). The cross-node merge writes newest-first, with no tie-breaker (internal/web/service/inbound_client_ips.go:86):Both writers then skip the write only on an exact string match:
if newIps == inboundClientIps.Ips(check_client_ip_job.go:559) andif row.Ips == mergedStr(inbound_client_ips.go:201). With two or more IPs the strings never match after the other writer has run, so each side issues a CASUPDATE. Because there is no tie-breaker, IPs that share a timestamp also come out of the merge in a random order (Go map iteration +sort.Slice). So the merge alone can produce a "changed" blob from identical input.Where this happens: on a node, the master's push (
node_traffic_sync_job.go:466→server.go:550MergeInboundClientIps) competes with the node's own scan for every client it hosts. On the master, it happens for any client the master also serves locally. Comments in the code say the skip is meant to work: "sorted so unchanged scans skip the write" (check_client_ip_job.go:554-555). No test checks that the blob stays stable across both writers.2. A per-row SELECT the snapshot already covers
MergeInboundClientIpsloads every row up front (inbound_client_ips.go:98). Then for every incoming email that already has a row,mergeExistingClientIpsreads it again before its first attempt (inbound_client_ips.go:191):That is one
SELECT ... WHERE idper reported email, per node, per cycle, whether or not anything changed. This matches your 13.9M reads against 5.06M CAS updates. The CAS inCasUpdateInboundClientIps(WHERE id = ? AND ips = ?, line 178) already protects a stale snapshot. The first attempt can therefore use the preloadedcurrent.Ipsas the expected value and re-read only afterRowsAffected == 0, without weakening #6587.3.
upsertNodeClientIpswrites every email unconditionallyinternal/web/service/inbound_node_ips.go:102-110marshals the merged entries and always runsINSERT ... ON CONFLICT (node_guid, email) DO UPDATE SET ips. It never compares the result withexistingByEmail[email].Ips, which it has already loaded (line 59). It runs from two places: every local scan (check_client_ip_job.go:408,RecordLocalClientIps) and every node attribution pull (node_traffic_sync_job.go:486,MergeClientIpsByGuid). Two caveats for a fix:mergeModelClientIpEntries(line 44) has the same tie-breaker gap, so the order must be made deterministic before an equality skip can work.nowon each scan (check_client_ip_job.go:345-346). Local-scan rows therefore really change every scan. As you said, timestamps drive expiry and must not be suppressed. Skipping unchanged rows mainly saves writes on theMergeClientIpsByGuidpath.About point 4 of your proposal: within one
MergeInboundClientIpsbatch, emails are already unique, because the batch is one node'sinbound_client_ipsrows, keyed byclient_email. The duplicate work is across nodes and across writers (items 1–3), not inside a batch.About the
UPDATE inbound_client_ips SET client_email = ..., ips = ... WHERE id = ?shape (3.41M): that matches the blindtx.Save(inboundClientIps)that8f120155(fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres (#6612)) removed. That commit first shipped in v3.10.0. I found no code on the current default branch that emits that statement. Those counts most likely come from a panel or node running a version older than v3.10.0, or from before an upgrade (inference).Suggested fix: Give both writers one shared canonical serializer, with one fixed sort order and the IP as tie-breaker, so a byte-equal compare means set-equal on every path. Use it in
sortedIpsFromMap/the enforce path,mergeClientIpEntriesandmergeModelClientIpEntries. Then letmergeExistingClientIpstry its first CAS against the preloadedcurrent.Ipsand re-read only on a miss, and letupsertNodeClientIpsskip emails whose canonical blob equals the stored one. A batchedON CONFLICTis a separate, optional step on top of that.This reply was generated automatically; a maintainer may follow up.
@HamedSanaei commented on GitHub (Oct 25, 2026):
Implemented in https://github.com/MHSanaei/3x-ui/pull/6930 and pushed as
91459180f927ea31dd1ba7c418cff8101b3b01d6(perf/client-ip-sync-6927).All IP writers now use
model.ClientIpEntrywith canonical timestamp/IP ordering and compact JSON. Remote merges use their preload for the first CAS, compare against the original stored bytes, reread only after contention, and preserve the eight-attempt/seven-reread bound, exact exhaustion error and rollback. Winning insert conflicts and duplicate payload emails retain their union instead of losing observations. Identical attribution blobs skip upserts; timestamp advances remain real writes.The 30-minute retention window, maximum timestamp per address, legacy JSON-string input, GUID separation, differing empty-address rules, live local-attribution stamping, scanner first-scan behavior, allowlist/frozen-ban semantics and commit-before-ban publication are preserved. Changed attribution upserts are not redesigned; this is not a claim to fix every pre-existing changed-attribution race.
Checks passed on SQLite 3.53.4 and real PostgreSQL 18.6/16.15:
GOFLAGS=-p=1 make verifyandGOFLAGS=-p=1 make race, with every package/test and race instrumentation retained. The full gate included 214 frontend test files/2,000 tests, build/Storybook and generated/OpenAPI checks.go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v: exactly two top-level PASSes on each PG version, no skips; actionlint passed.Regression-first tests failed before the production edit for redundant reads/writes, create-conflict/duplicate-new observation loss and the extra exhaustion reread. Real SQL injections, not mocked CAS outcomes, exercise contention and rollback.
Measured on the same 1k/10k/20k fixtures before/after, four overlapping node reports, warm union seeded outside timing. Representative PostgreSQL 18 result at 20k clients; each cell is before → after:
Flat affected rows were zero in the unchanged phase and 80,000 in each changed phase, on both revisions; the exact four-IP/max-timestamp union passed in every phase.
Tradeoff: synchronized all-changed reports make preloaded snapshots stale and increase failed CAS work; this worst-case phase is slower. The measured benefit is unchanged/uncontended sync, not a uniform speedup. Changed-phase WAL has differing FPI conditions and is reported raw, not as a normalized reduction. Zero affected row mutations is not zero WAL. Scanner live attribution still writes genuinely advancing timestamps. Statistics were captured before fixture teardown with unchanged
stats_reset,dealloc=0, and no cluster-wide reset. No external cache/service or schema/API change is introduced.