mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[GH-ISSUE #6928] [Performance]: Avoid unnecessary global traffic UPSERTs while preserving multi-node freshness and quota correctness #4587
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#4587
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/6928
Summary
The cross-panel traffic synchronization path overwrites every incoming
client_global_trafficsrow on every push, updatingup,down, andupdated_ateven when the usage values have not changed. With thousands of clients and frequent master-to-node pushes this creates significant PostgreSQL UPDATE/WAL churn.We should investigate change-aware writes with a bounded freshness heartbeat, keeping PostgreSQL as the source of truth. No Redis or extra service is requested.
Code paths / why this is delicate
internal/web/service/inbound_traffic_global.go:AcceptGlobalTraffic()filters to locally-known emails, batches in chunks of 200 and callsINSERT ... ON CONFLICT (master_guid,email) DO UPDATE SET up,down,updated_atevery push.internal/web/service/inbound_disable.go:globalTrafficFreshWindow = 24 * time.Hour; freshness is used by read and enforcement paths.overlayGlobalTraffic()treats stale rows as absent, andclient_trafficsdeliberately holds local-only counters so the master's delta accounting is not corrupted.Critical invariants: a traffic reset must propagate lower counts (not a max-only update); a master that stops reporting must age out; a live but idle master must not age out solely because its
up/downvalues remained unchanged.Production evidence (PostgreSQL 18)
A several-day statistics window beginning 2026-10-21 showed:
client_global_traffics: ~6,708 currently live rows and ~173 million cumulative row updates (pg_stat_user_tables.n_tup_upd).INSERT ... ON CONFLICT DO UPDATEquery shape: ~155,449 statements, ~4.69 GB reported WAL, ~639,000 ms cumulative execution time inpg_stat_statements.The values reflect one busy cluster and a particular measurement window, not a universal rate. Some statements contain many client rows; statement count and row-update count must not be conflated.
Proposed direction (for maintainer review)
master_guid/email, plus the frequency of freshness-only writes.ON CONFLICT DO UPDATE ... WHERE ...soup/downchanges (including resets to lower numbers) always write immediately, but identical values refreshupdated_atonly when a safe, configurable or internal heartbeat threshold has elapsed.Acceptance criteria
pg_stat_statementsdeltas.globalTrafficFreshWindow(#6113).client_traffics, no cross-master double counting and no behavior change to intermediate forwarding nodes.Related but distinct from #6035 (general PostgreSQL/multi-node CRUD slowness). This focuses on write amplification in the global traffic ingestion path.
@github-actions[bot] commented on GitHub (Oct 25, 2026):
The source confirms what you describe. Every global-traffic push rewrites every row it covers, including rows whose
up/downhaven't changed. This is a performance change you are asking for, not a correctness bug, so I've labelled itenhancement. The fix you propose (a conditional upsert plus a heartbeat shorter than the freshness window) fits the existing design.What the code does today
internal/web/job/node_traffic_sync_job.go:26setsnodeGlobalPushInterval = 30 * time.Second.maybePushGlobals(node_traffic_sync_job.go:304-357) then sends each online node the full list fromGetNodeClientTraffics(n.Id): every client that node hosts, changed or not (internal/web/service/inbound_traffic_global.go:169-188).AcceptGlobalTrafficstamps the samenowon every row (inbound_traffic_global.go:60,UpdatedAt: nowat :72). It then upserts in batches of 200 with nothing that skips unchanged rows: (inbound_traffic_global.go:80). Every row in the payload gets a newupdated_aton every push, so on PostgreSQL every row becomes a new tuple version, with the WAL and index churn that brings.Why
updated_atcan't just be skippedupdated_atis the only liveness signal. Three paths depend on it:globalTrafficFreshWindow = 24 * time.Hour(internal/web/service/inbound_disable.go:35).depletedClientsCondonly counts rows withg.updated_at >= ?(inbound_disable.go:46-53).overlayGlobalTrafficignores rows older than the window (inbound_traffic_global.go:105-135, #6113).So your three constraints are real, and the code enforces each of them:
inbound_traffic_global.go:22and the model comment atinternal/database/model/client_global_traffic.go:10-12both say so, andTestAcceptGlobalTraffic_OverwriteAndMultiMaster(internal/web/service/global_traffic_test.go:46) tests it.global_traffic_test.go:98tests this withstaleAt := time.Now().Add(-globalTrafficFreshWindow - time.Hour).Where a change would go
The only place that needs to change is the
OnConflictclause inAcceptGlobalTraffic. A conditionalDO UPDATE ... WHEREwould write when the incoming values differ from the stored ones (IS DISTINCT FROM), which covers decreases from a reset. For identical values it would only write when the storedupdated_atis older than an internal heartbeat set well inside 24 h. PostgreSQL and SQLite (3.24+) both supportON CONFLICT ... DO UPDATE ... WHERE. That keeps PostgreSQL the single source of truth, with no extra cache or service.Things to check (my inferences, not verified):
WHEREevaluates false, so the cost doesn't drop to zero. It should still remove the new tuple version and most of the WAL.nowper push, all rows from a master hit the heartbeat in the same push. That gives one full rewrite per heartbeat interval instead of one every 30 s.INSERTpath, andclearGlobalTrafficdeletes rows outright (inbound_traffic_global.go:209-219).GetNodeClientTrafficsand never depends on the write count.The master could also skip unchanged rows before sending, which would save network traffic too. But it would need its own heartbeat bookkeeping per node, and it could drift from what the node actually has stored. Doing it on the node, in SQL, avoids that, as you suggested.
Related: #6035 (general PostgreSQL/multi-node slowness) and #6113 (why the freshness window exists). Neither is a duplicate.
Verdict: Feature request
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/6931 (
perf/global-traffic-heartbeat-6928). Production fix:5509c0dd7d3e38ce57db24b3bd6463adc7a6f937; current head:70f082a6931b656410028f22f1f00d08b2fff051, an approved docs-only correction of the model's stale every-push comment. No published history was rewritten.The UPSERT now writes any directional counter difference immediately—including lower values and zero resets—or refreshes an identical row at the inclusive one-hour heartbeat. Explicit NULL branches repair legacy nullable values. New rows still insert immediately; known-local-email filtering, duplicate last-wins behavior, queued writing, one transaction and 200-row batches remain unchanged.
The existing GORM clock drives ingestion and persisted freshness checks. Local counters/full-list snapshots stay separate; slim/detail/quota reads retain the inclusive 24-hour rule and existing per-master overlays; downstream forwarding and actual reset/delete cleanup remain intact. Ordinary heartbeat ingestion does not invalidate subscription settings caches. No cache/service, settings/API/schema change or sequence/precedence protocol is introduced.
Liveness tradeoff: an idle master can expire up to one hour earlier relative to its final unchanged push because freshness writes are coarsened. Active hourly refresh leaves roughly 23 hours of missed-push margin; counter changes are not delayed.
Verification passed:
GOFLAGS=-p=1 make verifyandGOFLAGS=-p=1 make race, retaining all packages/tests and race instrumentation; the full gate included 214 frontend test files/2,000 tests, build/Storybook and generated/OpenAPI checks.TestGlobalTrafficHeartbeatPostgresruns on real PostgreSQL 18.6 and 16.15: one top-level PASS each, no skips; actionlint passed.CreateOnerecreation and forwarding. The premature-update assertion failed before the production edit.make node-e2epassed existing two-panel scenarios and a genuine three-panel forwarding chain with combined usage, lower/reset totals, origin-owned deletion/recreation and offline recovery. Cadence stayed unchanged; waits were 90 seconds. No live-Xray/firewall claim; 48-hour proof uses deterministic DB time.The documentation-only follow-up also passed model-package
golangci-lintand the six SQLite heartbeat regression cases. It changes no executable code or schema.The same workload ran before/after on both dialects: 6,708 clients, 240 simulated 30-second pushes over two hours, seed/one warmup excluded, unchanged/sparse 1%/all-change/reset-at-tick-120 phases.
Supplemental PostgreSQL 18 comparisons used the identical fixtures in isolated original/changed snapshots,
full_page_writes=on, 8GB maximum WAL, one-hour checkpoint timeout and an untimed checkpoint before each workload. Timed/requested checkpoint counters did not change inside any measured interval; original 1GB/5-minute settings were restored afterward. No checkpoint requirement/configuration was added to committed tests or production.This reduces row versions/WAL for unchanged, sparse and reset workloads—not statement count. Conflict locking and sequence advancement can remain. All-change showed no benefit and had higher measured WAL; no universal speedup is claimed. Server execution/WAL/buffer statistics were captured before fixture teardown, with unchanged
stats_reset,dealloc=0and no cluster-wide reset. Intervals with intervening checkpoints were rejected rather than presented as controlled evidence.