[GH-ISSUE #7008] [Performance]: Reduce repeated PostgreSQL work in global-aware client depletion checks #4616

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/7008

Summary

Even after the previous fix for #5392, an active multi-node PostgreSQL deployment spends substantial time repeatedly evaluating the client expiry/quota predicate against thousands of traffic rows. Almost all executions find zero clients to disable, but the global-usage-aware OR EXISTS path remains relatively expensive.

This is a follow-up, performance-only optimization, not a request to relax quota enforcement, change the polling schedule, or reimplement the already-fixed empty-global-table shortcut.

Confirmed implementation

  • internal/web/web.go: XrayTrafficJob runs at cadenceXrayTraffic = "@every 5s".
  • internal/web/job/xray_traffic_job.go: Run calls InboundService.AddTraffic.
  • internal/web/service/inbound_traffic.go: addTrafficLocked commits incoming traffic, then performs lifecycle maintenance in a separate transaction: autoRenewClients, disableInvalidClients, and disableInvalidInbounds.
  • internal/web/service/inbound_disable.go: depletedCond first checks whether any client_global_traffics row is fresh within 24 hours. If yes, it selects depletedClientsCond, combining local quota exhaustion, expiry, and a correlated EXISTS against global usage. On empty/stale global data it uses the cheaper local-only predicate (the #5392 improvement).

Relevant SQL shape, simplified for readability:

SELECT *
FROM client_traffics ct
WHERE ct.enable = TRUE
  AND (
       (ct.total > 0 AND ct.up + ct.down >= ct.total)
    OR (ct.expiry_time > 0 AND ct.expiry_time <= :now_ms)
    OR (
      ct.total > 0 AND EXISTS (
        SELECT 1 FROM client_global_traffics g
        WHERE g.email = ct.email
          AND g.updated_at >= :fresh_since
          AND g.up + g.down >= ct.total
      )
    )
  );

The global path is essential: a node can exceed the global quota even when its local counters are below the limit. Do not replace this with local-only accounting.

Production measurements

PostgreSQL 18, 2 vCPUs, ~9,774 client_traffics rows and ~6,857 client_global_traffics rows; source: pg_stat_statements, from 2026-10-28 15:16:54 UTC through approximately 22:08:42 UTC.

Metric Observed
Global-aware depletion SELECT calls 4,951
Cumulative SQL execution time 273,662 ms (~4.56 minutes)
Mean execution time 55.27 ms
Max execution time 530.0 ms
Rows returned over all those calls 4
Shared-buffer hits 35,750,337

The recurrent SELECT count(*) FROM client_global_traffics WHERE updated_at >= ? LIMIT ? shape also registered 7,242 calls and ~31,685 ms cumulative execution time. Identify all its callers before attributing the entire count to depletion checking.

The main predicate commonly returns no rows but still costs ~55 ms per call. This is a repeatable SQL hot path, not proof that each run wastes CPU: determining that no one is depleted is required. Query-level execution time is also not the same as OS CPU time.

Existing indexes (do not duplicate blindly)

  • client_traffics: unique (email), (inbound_id), (expiry_time,reset).
  • client_global_traffics: (email), unique (master_guid,email).

Proposed approach

  1. First capture actual query plans for representative local-only and fresh-global datasets using EXPLAIN (ANALYZE, BUFFERS) on safe read-only queries; compare enabled/disabled populations, expiration distributions, and number of fresh masters.
  2. Evaluate SQL-shape improvements and filtering by enabled rows, expiry and quotas. Benchmark splitting the conditions or narrowing candidates before the correlated lookup, and assess whether PostgreSQL can take advantage of existing indexes.
  3. Consider an additional index only if measured. If justified, integrate it portably in the project's migration strategy and test its write/WAL overhead on the high-frequency traffic path; avoid one-off manual production indexes.
  4. Evaluate whether the preliminary fresh-global probe can be made cheaper or shared safely within a traffic cycle, without incorrectly treating active, inactive, new, or stale global data as interchangeable.
  5. Keep the existing client disable operations atomic. Preserve the current transaction boundaries, and make sure every actual exhaustion event is detected promptly with the current cadence.
  6. Do not add a Redis/cache service, change the global quota definition, or implement speculative asynchronous disable queues.

Correctness requirements

  • Global aggregated usage remains authoritative where applicable; never silently substitute local traffic.
  • Existing inclusive 24-hour freshness rules are preserved. A master that stops pushing eventually stops contributing, while an idle but actively heartbeating master stays valid.
  • Newly pushed global totals become effective promptly; lower totals and zero resets must propagate correctly.
  • Multiple masters, nested nodes, live and previously disabled clients, manually disabled users, unlimited quotas, expiry/renewal, shared emails, and simultaneous traffic/expiry depletion retain their behavior.
  • No disabled client is incorrectly re-enabled. No legitimately depleted client stays enabled beyond existing lifecycle latency.
  • Preserve PostgreSQL and SQLite behavior and avoid regressions in Xray user removal, node synchronization and traffic counter accounting.

Acceptance criteria

  • Before/after EXPLAIN (ANALYZE, BUFFERS) on matched PostgreSQL fixtures, showing row/plan differences and query time.
  • On a recurring ~5-second workload, materially reduce cumulative query time/buffer visits and/or redundant probe calls without increasing costly writes.
  • Test at least 1k/10k/20k traffic rows; compare empty-global, all-stale-global, fresh-global, multiple-master and mostly-nondepleted cases.
  • Retain correct local and global quota cut-off semantics with current detection cadence.
  • Regression tests cover exact expiry boundary, global quota crossing, stale/heartbeat freshness boundary, concurrent changes, resets/renewals, and repeated empty-result cycles.
  • No unnecessary schema migrations or new mandatory services; pass relevant Go tests on PostgreSQL and SQLite.
  • Include measured before/after pg_stat_statements deltas (matched observation windows) if available.

Prior art / boundaries

  • #5392 (closed): established the original hotspot and optimized away global EXISTS when no fresh global usage exists. This issue specifically covers the still-expensive active-global case observed after that change.
  • #6928 / PR #6931 (merged): suppresses unchanged global UPSERT writes while maintaining freshness heartbeats; this proposal concerns the read-side depletion predicate, not global ingestion writes.
  • #6883: recording depletion reason/time is a separate feature; no new depletion metadata is requested here.

I can implement and benchmark a small focused PR once the direction is agreed.

Originally created by @HamedSanaei on GitHub (Oct 28, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/7008 ## Summary Even after the previous fix for #5392, an active multi-node PostgreSQL deployment spends substantial time repeatedly evaluating the client expiry/quota predicate against thousands of traffic rows. Almost all executions find **zero** clients to disable, but the global-usage-aware `OR EXISTS` path remains relatively expensive. This is a **follow-up, performance-only optimization**, not a request to relax quota enforcement, change the polling schedule, or reimplement the already-fixed empty-global-table shortcut. ## Confirmed implementation - `internal/web/web.go`: `XrayTrafficJob` runs at `cadenceXrayTraffic = "@every 5s"`. - `internal/web/job/xray_traffic_job.go`: `Run` calls `InboundService.AddTraffic`. - `internal/web/service/inbound_traffic.go`: `addTrafficLocked` commits incoming traffic, then performs lifecycle maintenance in a separate transaction: `autoRenewClients`, `disableInvalidClients`, and `disableInvalidInbounds`. - `internal/web/service/inbound_disable.go`: `depletedCond` first checks whether any `client_global_traffics` row is fresh within 24 hours. If yes, it selects `depletedClientsCond`, combining local quota exhaustion, expiry, and a correlated EXISTS against global usage. On empty/stale global data it uses the cheaper local-only predicate (the #5392 improvement). Relevant SQL shape, simplified for readability: ```sql SELECT * FROM client_traffics ct WHERE ct.enable = TRUE AND ( (ct.total > 0 AND ct.up + ct.down >= ct.total) OR (ct.expiry_time > 0 AND ct.expiry_time <= :now_ms) OR ( ct.total > 0 AND EXISTS ( SELECT 1 FROM client_global_traffics g WHERE g.email = ct.email AND g.updated_at >= :fresh_since AND g.up + g.down >= ct.total ) ) ); ``` The global path is essential: a node can exceed the **global** quota even when its local counters are below the limit. Do not replace this with local-only accounting. ## Production measurements PostgreSQL 18, 2 vCPUs, ~9,774 `client_traffics` rows and ~6,857 `client_global_traffics` rows; source: `pg_stat_statements`, from **2026-10-28 15:16:54 UTC** through approximately **22:08:42 UTC**. | Metric | Observed | | --- | ---: | | Global-aware depletion SELECT calls | 4,951 | | Cumulative SQL execution time | **273,662 ms** (~4.56 minutes) | | Mean execution time | **55.27 ms** | | Max execution time | **530.0 ms** | | Rows returned over all those calls | **4** | | Shared-buffer hits | **35,750,337** | The recurrent `SELECT count(*) FROM client_global_traffics WHERE updated_at >= ? LIMIT ?` shape also registered **7,242 calls** and ~31,685 ms cumulative execution time. Identify all its callers before attributing the entire count to depletion checking. The main predicate commonly returns no rows but still costs ~55 ms per call. This is a repeatable SQL hot path, not proof that each run wastes CPU: determining that *no one* is depleted is required. Query-level execution time is also not the same as OS CPU time. ### Existing indexes (do not duplicate blindly) - `client_traffics`: unique `(email)`, `(inbound_id)`, `(expiry_time,reset)`. - `client_global_traffics`: `(email)`, unique `(master_guid,email)`. ## Proposed approach 1. First capture actual query plans for representative **local-only and fresh-global** datasets using `EXPLAIN (ANALYZE, BUFFERS)` on safe read-only queries; compare enabled/disabled populations, expiration distributions, and number of fresh masters. 2. Evaluate SQL-shape improvements and filtering by enabled rows, expiry and quotas. Benchmark splitting the conditions or narrowing candidates before the correlated lookup, and assess whether PostgreSQL can take advantage of existing indexes. 3. Consider an additional index **only if measured**. If justified, integrate it portably in the project's migration strategy and test its write/WAL overhead on the high-frequency traffic path; avoid one-off manual production indexes. 4. Evaluate whether the preliminary fresh-global probe can be made cheaper or shared **safely** within a traffic cycle, without incorrectly treating active, inactive, new, or stale global data as interchangeable. 5. Keep the existing client disable operations atomic. Preserve the current transaction boundaries, and make sure every actual exhaustion event is detected promptly with the current cadence. 6. Do not add a Redis/cache service, change the global quota definition, or implement speculative asynchronous disable queues. ## Correctness requirements - Global aggregated usage remains authoritative where applicable; never silently substitute local traffic. - Existing inclusive 24-hour freshness rules are preserved. A master that stops pushing eventually stops contributing, while an idle but actively heartbeating master stays valid. - Newly pushed global totals become effective promptly; lower totals and zero resets must propagate correctly. - Multiple masters, nested nodes, live and previously disabled clients, manually disabled users, unlimited quotas, expiry/renewal, shared emails, and simultaneous traffic/expiry depletion retain their behavior. - No disabled client is incorrectly re-enabled. No legitimately depleted client stays enabled beyond existing lifecycle latency. - Preserve PostgreSQL and SQLite behavior and avoid regressions in Xray user removal, node synchronization and traffic counter accounting. ## Acceptance criteria - [ ] Before/after `EXPLAIN (ANALYZE, BUFFERS)` on matched PostgreSQL fixtures, showing row/plan differences and query time. - [ ] On a recurring ~5-second workload, materially reduce cumulative query time/buffer visits and/or redundant probe calls without increasing costly writes. - [ ] Test at least 1k/10k/20k traffic rows; compare empty-global, all-stale-global, fresh-global, multiple-master and mostly-nondepleted cases. - [ ] Retain correct local **and global** quota cut-off semantics with current detection cadence. - [ ] Regression tests cover exact expiry boundary, global quota crossing, stale/heartbeat freshness boundary, concurrent changes, resets/renewals, and repeated empty-result cycles. - [ ] No unnecessary schema migrations or new mandatory services; pass relevant Go tests on PostgreSQL and SQLite. - [ ] Include measured before/after `pg_stat_statements` deltas (matched observation windows) if available. ## Prior art / boundaries - #5392 (closed): established the original hotspot and optimized away global EXISTS when no fresh global usage exists. This issue specifically covers the **still-expensive active-global case** observed after that change. - #6928 / PR #6931 (merged): suppresses unchanged global UPSERT writes while maintaining freshness heartbeats; this proposal concerns the **read-side depletion predicate**, not global ingestion writes. - #6883: recording depletion reason/time is a separate feature; no new depletion metadata is requested here. **I can implement and benchmark a small focused PR once the direction is agreed.**
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#4616
No description provided.