[GH-ISSUE #7007] [Performance]: Reduce recurring full inbound snapshots during 5-second node traffic sync #4617

Open
opened 2026-10-31 20:40:55 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @HamedSanaei on GitHub (Oct 28, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/7007

Summary

On PostgreSQL-backed multi-node deployments, the five-second node traffic synchronization path requests the full inbound list from each node, even though most inbound configuration/identity data is unchanged from the previous tick. This causes repeated large database reads, identity JOINs, JSON decoding/encoding, and network transfers while the master mostly needs fresh counters, online state and enough information to safely reconcile lifecycle/structural changes.

This issue proposes measuring and reducing snapshot read amplification at the node-sync boundary. It is not a request to reimplement the already-merged client identity batching from #6926, change the five-second traffic cadence, or weaken node reconciliation correctness.

Verified code path (current main)

  • internal/web/web.go: cadenceNodeTraffic = "@every 5s".
  • internal/web/job/node_traffic_sync_job.go: NodeTrafficSyncJob.Run calls syncOne for each enabled/online node; syncOne calls rt.FetchTrafficSnapshot(ctx) and then FilterNodeSnapshot, SnapshotHasUnadoptedInbounds and SetRemoteTraffic.
  • internal/web/runtime/remote.go: Remote.FetchTrafficSnapshot makes GET panel/api/inbounds/list and unmarshals the entire response into snap.Inbounds; the method also calls online-by-GUID, last-online and active-inbounds endpoints.
  • internal/web/controller/inbound.go: getInbounds calls InboundService.GetInbounds.
  • internal/web/service/inbound.go: GetInbounds performs a full inbound query with Preload("ClientStats"), followed by enrichClientStats and annotations. backfillClientStats is already batched since #6926, but the entire path still runs on each request.

The full response is important to some existing consumers (node adoption, structural sync, backward-compatible snapshot behavior). Do not simply remove settings/identity fields from the existing endpoint.

Reproducible production evidence

PostgreSQL 18, 2-vCPU Linux VPS, about 14,774 rows in clients, 11,372 rows in client_inbounds, 9,774 rows in client_traffics, and 8 inbounds. The combined inbounds.settings payload is about 6.00 MiB (largest 2.58 MiB).

pg_stat_statements was enabled/reset at 2026-10-28 15:16:54 UTC; measurements below were sampled around 2026-10-28 22:08:42 UTC (roughly 6 h 52 min). These are database-wide cumulative query-shape counters, not endpoint-specific tracing:

SQL query shape Calls Total execution time Mean time Returned rows
SELECT * FROM client_traffics WHERE email IN (...) 55,288 646,867 ms 11.70 ms 19,902,405
clients JOIN client_inbounds ... WHERE inbound_id IN (...) 4,819 520,733 ms 108.06 ms 54,774,368
SELECT * FROM client_traffics WHERE inbound_id IN (...) 4,819 323,927 ms 67.22 ms 35,146,581
SELECT * FROM inbounds WHERE user_id = ? ORDER BY id 4,804 252,150 ms 52.49 ms 38,432

The last three shapes each run ~4,800 times in the sample, consistent with a ~5-second recurring operation. One identity JOIN returns an average of ~11.4k rows per execution. Together with the email-IN traffic shape they account for ~60% of the recorded xui SQL execution time. However, pg_stat_statements aggregates all callers of a normalized SQL shape, so attribution to node traffic snapshots must be verified with targeted instrumentation. SQL elapsed time is not identical to CPU time.

Existing indexes include client_inbounds(inbound_id) and client_traffics(inbound_id); this is not a request to add duplicate indexes.

Proposed investigation / implementation direction

  1. Add temporary/benchmark instrumentation around FetchTrafficSnapshot, inbound list loading, stats enrichment and SetRemoteTraffic: SQL calls, rows, DB time, JSON marshal/unmarshal time, bytes transferred, Go allocations, end-to-end p50/p95 and per-node rate. Avoid logging client credentials or sensitive payloads.
  2. Determine which inbound fields are required every tick for traffic delta accounting, offline/online state, node identity, lifecycle and adoption, versus which are structural and unchanged.
  3. Implement the smallest safe change that avoids repeating full, unchanged inbound/config/client identity work on every poll. Candidates: a dedicated versioned compact traffic snapshot, structural snapshot reuse/invalidation, or a hybrid. Select based on benchmarks and correctness tests, not by assuming a new endpoint is necessary.
  4. Keep full inbound detail accessible to callers that need configuration; do not change /panel/api/inbounds/list semantics for existing API users.
  5. Preserve mixed-version master/node compatibility (feature detection and fallback to existing snapshot contract for older nodes). If an incremental protocol is adopted, use a reliable initial full snapshot and invalidation/re-sync strategy after node reconnects, updates, missed deltas and resets. Changes must never be silently lost.
  6. Avoid Redis, new database tables, faster polling, and new mandatory infrastructure.

Critical correctness invariants

  • The master still obtains the correct local node traffic counters and computes deltas exactly once, including counter decreases/resets and first sync after reconnection.
  • Global traffic overlays remain display/enforcement inputs and are never double-counted as local usage.
  • Node GUID / parent-child attribution, adopted and unadopted inbounds, tags, online-by-GUID, active inbound mapping, and last-online behavior are unchanged.
  • Propagation of disabled/expired clients, renewals and inbound config changes remains correct (including the justPushed guard against re-applying a lagging snapshot).
  • Node failures/timeouts, stale snapshots, mixed versions, restarts, and disconnections cannot corrupt counters, silently drop updates or return previously removed clients.
  • No changes to Xray config generation, subscriptions, or normal admin inbound-list responses.

Acceptance criteria

  • A before/after performance comparison on the same workload shows fewer repeated full-snapshot/identity reads and/or lower DB execution time/JSON bytes/CPU allocations.
  • Benchmarks include ~1k/10k/20k clients, multi-inbound attachments and at least one master with multiple nodes; show SQL calls, rows, bytes transferred, p50/p95 latency and allocations.
  • Normal 5-second sync cadence is preserved; no additional background polling or caching with incorrect invalidation.
  • Node integration/E2E tests cover first sync, unchanged steady state, traffic increments, counter reset, client attach/detach, expiry/disable, reconnect, offline recovery, nested nodes, and structural updates.
  • Mixed-version peers fall back safely to existing behavior; full inbound-list endpoint remains backward compatible.
  • PostgreSQL and SQLite regression tests pass, including existing node contract and traffic accounting tests.
  • A small, reviewable PR changes only the relevant snapshot path and documents its measured benefit.
  • #6926 / PR #6929 (merged): batch identity queries, already present in backfillClientStats; this issue targets the frequency and scope of the full snapshot after that optimization.
  • #6927 / PR #6930 (merged): client IP merge/write reduction; not addressed here.
  • #6928 / PR #6931 (merged): global traffic heartbeat UPSERT reduction; not addressed here.
  • #6252 (closed): broad client CRUD and multi-node scaling; this is a narrowly measurable recurring traffic-snapshot problem.

I am willing to implement this improvement and submit a PR after maintainer feedback.

Originally created by @HamedSanaei on GitHub (Oct 28, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/7007 ## Summary On PostgreSQL-backed multi-node deployments, the five-second node traffic synchronization path requests the *full* inbound list from each node, even though most inbound configuration/identity data is unchanged from the previous tick. This causes repeated large database reads, identity JOINs, JSON decoding/encoding, and network transfers while the master mostly needs fresh counters, online state and enough information to safely reconcile lifecycle/structural changes. This issue proposes measuring and reducing **snapshot read amplification at the node-sync boundary**. It is **not** a request to reimplement the already-merged client identity batching from #6926, change the five-second traffic cadence, or weaken node reconciliation correctness. ## Verified code path (current `main`) - `internal/web/web.go`: `cadenceNodeTraffic = "@every 5s"`. - `internal/web/job/node_traffic_sync_job.go`: `NodeTrafficSyncJob.Run` calls `syncOne` for each enabled/online node; `syncOne` calls `rt.FetchTrafficSnapshot(ctx)` and then `FilterNodeSnapshot`, `SnapshotHasUnadoptedInbounds` and `SetRemoteTraffic`. - `internal/web/runtime/remote.go`: `Remote.FetchTrafficSnapshot` makes `GET panel/api/inbounds/list` and unmarshals the entire response into `snap.Inbounds`; the method also calls online-by-GUID, last-online and active-inbounds endpoints. - `internal/web/controller/inbound.go`: `getInbounds` calls `InboundService.GetInbounds`. - `internal/web/service/inbound.go`: `GetInbounds` performs a full inbound query with `Preload("ClientStats")`, followed by `enrichClientStats` and annotations. `backfillClientStats` is already batched since #6926, but the entire path still runs on each request. The full response is important to **some** existing consumers (node adoption, structural sync, backward-compatible snapshot behavior). Do not simply remove settings/identity fields from the existing endpoint. ## Reproducible production evidence PostgreSQL 18, 2-vCPU Linux VPS, about 14,774 rows in `clients`, 11,372 rows in `client_inbounds`, 9,774 rows in `client_traffics`, and 8 inbounds. The combined `inbounds.settings` payload is about 6.00 MiB (largest 2.58 MiB). `pg_stat_statements` was enabled/reset at **2026-10-28 15:16:54 UTC**; measurements below were sampled around **2026-10-28 22:08:42 UTC** (roughly 6 h 52 min). These are **database-wide cumulative query-shape counters**, not endpoint-specific tracing: | SQL query shape | Calls | Total execution time | Mean time | Returned rows | | --- | ---: | ---: | ---: | ---: | | `SELECT * FROM client_traffics WHERE email IN (...)` | 55,288 | 646,867 ms | 11.70 ms | 19,902,405 | | `clients JOIN client_inbounds ... WHERE inbound_id IN (...)` | 4,819 | 520,733 ms | 108.06 ms | 54,774,368 | | `SELECT * FROM client_traffics WHERE inbound_id IN (...)` | 4,819 | 323,927 ms | 67.22 ms | 35,146,581 | | `SELECT * FROM inbounds WHERE user_id = ? ORDER BY id` | 4,804 | 252,150 ms | 52.49 ms | 38,432 | The last three shapes each run ~4,800 times in the sample, consistent with a ~5-second recurring operation. One identity JOIN returns an average of ~11.4k rows per execution. Together with the email-IN traffic shape they account for ~60% of the recorded `xui` SQL execution time. However, **`pg_stat_statements` aggregates all callers of a normalized SQL shape**, so attribution to node traffic snapshots must be verified with targeted instrumentation. SQL elapsed time is not identical to CPU time. Existing indexes include `client_inbounds(inbound_id)` and `client_traffics(inbound_id)`; this is not a request to add duplicate indexes. ## Proposed investigation / implementation direction 1. Add temporary/benchmark instrumentation around `FetchTrafficSnapshot`, inbound list loading, stats enrichment and `SetRemoteTraffic`: SQL calls, rows, DB time, JSON marshal/unmarshal time, bytes transferred, Go allocations, end-to-end p50/p95 and per-node rate. Avoid logging client credentials or sensitive payloads. 2. Determine which inbound fields are **required every tick** for traffic delta accounting, offline/online state, node identity, lifecycle and adoption, versus which are structural and unchanged. 3. Implement the smallest safe change that avoids repeating full, unchanged inbound/config/client identity work on every poll. Candidates: a dedicated versioned compact traffic snapshot, structural snapshot reuse/invalidation, or a hybrid. Select based on benchmarks and correctness tests, not by assuming a new endpoint is necessary. 4. Keep full inbound detail accessible to callers that need configuration; do not change `/panel/api/inbounds/list` semantics for existing API users. 5. Preserve mixed-version master/node compatibility (feature detection and fallback to existing snapshot contract for older nodes). If an incremental protocol is adopted, use a reliable initial full snapshot and invalidation/re-sync strategy after node reconnects, updates, missed deltas and resets. Changes must never be silently lost. 6. Avoid Redis, new database tables, faster polling, and new mandatory infrastructure. ## Critical correctness invariants - The master still obtains the correct **local** node traffic counters and computes deltas exactly once, including counter decreases/resets and first sync after reconnection. - Global traffic overlays remain display/enforcement inputs and are never double-counted as local usage. - Node GUID / parent-child attribution, adopted and unadopted inbounds, tags, online-by-GUID, active inbound mapping, and last-online behavior are unchanged. - Propagation of disabled/expired clients, renewals and inbound config changes remains correct (including the `justPushed` guard against re-applying a lagging snapshot). - Node failures/timeouts, stale snapshots, mixed versions, restarts, and disconnections cannot corrupt counters, silently drop updates or return previously removed clients. - No changes to Xray config generation, subscriptions, or normal admin inbound-list responses. ## Acceptance criteria - [ ] A before/after performance comparison on the **same workload** shows fewer repeated full-snapshot/identity reads and/or lower DB execution time/JSON bytes/CPU allocations. - [ ] Benchmarks include ~1k/10k/20k clients, multi-inbound attachments and at least one master with multiple nodes; show SQL calls, rows, bytes transferred, p50/p95 latency and allocations. - [ ] Normal 5-second sync cadence is preserved; no additional background polling or caching with incorrect invalidation. - [ ] Node integration/E2E tests cover first sync, unchanged steady state, traffic increments, counter reset, client attach/detach, expiry/disable, reconnect, offline recovery, nested nodes, and structural updates. - [ ] Mixed-version peers fall back safely to existing behavior; full inbound-list endpoint remains backward compatible. - [ ] PostgreSQL and SQLite regression tests pass, including existing node contract and traffic accounting tests. - [ ] A small, reviewable PR changes only the relevant snapshot path and documents its measured benefit. ## Related work / non-duplication - #6926 / PR #6929 (merged): **batch** identity queries, already present in `backfillClientStats`; this issue targets the *frequency and scope of the full snapshot* after that optimization. - #6927 / PR #6930 (merged): client IP merge/write reduction; not addressed here. - #6928 / PR #6931 (merged): global traffic heartbeat UPSERT reduction; not addressed here. - #6252 (closed): broad client CRUD and multi-node scaling; this is a narrowly measurable recurring traffic-snapshot problem. **I am willing to implement this improvement and submit a PR after maintainer feedback.**
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4617
No description provided.