[PR #6931] [MERGED] perf(traffic): skip unchanged global writes between heartbeats #6529

Closed
opened 2026-11-02 04:09:24 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6931
Author: @HamedSanaei
Created: 10/25/2026
Status: ✅ Merged
Merged: 10/25/2026
Merged by: @MHSanaei

Base: main ← Head: perf/global-traffic-heartbeat-6928


📝 Commits (2)

  • 5509c0d perf(traffic): skip unchanged global writes between heartbeats
  • 70f082a docs(traffic): describe persisted global heartbeat timestamps

📊 Changes

10 files changed (+699 additions, -38 deletions)

View changed files

📝 .github/workflows/ci.yml (+10 -0)
📝 docs/architecture.md (+11 -0)
📝 internal/database/model/client_global_traffic.go (+2 -10)
📝 internal/nodee2e/node_sync_test.go (+116 -0)
📝 internal/web/service/client_paging.go (+1 -1)
➕ internal/web/service/global_traffic_heartbeat_test.go (+374 -0)
➕ internal/web/service/global_traffic_postgres_test.go (+39 -0)
➕ internal/web/service/global_traffic_scale_test.go (+118 -0)
📝 internal/web/service/inbound_disable.go (+8 -10)
📝 internal/web/service/inbound_traffic_global.go (+20 -17)

📄 Description

Summary

Avoid replacing identical client_global_traffics row versions on every push. Directional counter changes—including lower values and zero resets—still persist immediately; identical totals refresh at an inclusive one-hour heartbeat.

Why

Every incoming hosted-client total previously updated up, down and updated_at even when usage was unchanged. This creates avoidable row-version/WAL churn on large installations.

The existing (master_guid,email) UPSERT now has an action WHERE predicate, not a conflict-target predicate. Explicit NULL branches repair legacy nullable counters/timestamps; any directional difference writes immediately. Rows insert immediately when missing. Known-email filtering, duplicate-email last-wins behavior, queued writing, one transaction and 200-row batches remain unchanged.

Ingestion and freshness readers use the existing GORM clock. The persisted-row freshness window remains inclusive at 24 hours; local-only counters/full-list snapshots, per-master componentwise-MAX read overlays, downstream forwarding, actual reset/delete cleanup and quota-disable subscription invalidation remain intact. Ordinary ingestion does not invalidate subscription settings caches.

Bounded liveness tradeoff: after a master stops, coarsened timestamps can make its idle totals expire up to one hour earlier relative to its final unchanged push. Active hourly refresh leaves roughly 23 hours of missed-push margin. This is an internal fixed interval, with no new setting, clock abstraction, cache, service, schema or API change.

Closes #6928.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other: Performance

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

Passed on Windows amd64, Go 1.27.3, CGO/GCC, Node 26.12.1/npm 11.20.0, SQLite 3.53.4, and disposable PostgreSQL 18.6 and 16.15:

# PostgreSQL environment variables unset.
GOFLAGS=-p=1 make verify
GOFLAGS=-p=1 make race
make node-e2e

go test ./internal/web/service \
  -run 'TestAcceptGlobalTraffic|TestGlobalTraffic|TestGlobalUsage|TestStaleGlobalTraffic|TestSnapshotListNotOverlaid|TestListPagedGlobalTrafficOverlay|TestNodeRenew_ClearsGlobalTraffic' \
  -count=1 -v

# Run with each disposable PostgreSQL 18/16 DSN; exactly one top-level PASS, no skips.
XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \
go test ./internal/web/service -run '^TestGlobalTrafficHeartbeatPostgres$' -count=1 -v

go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color -shellcheck=

The full gate passed generation/lint/format/type checks, all Go tests, 214 frontend test files/2,000 tests, full build, Storybook and the docs-vs-panel OpenAPI check. Package serialization retains all tests and race instrumentation.

Regression-first evidence: before the production change, the new boundary test observed an affected row before one hour when it required zero. Tests use real databases and synchronized affected-row counts after gorm:create, not merely unchanged timestamps. The atomic fake GORM clock is installed on the global DB after stopping/draining the writer and restored only after another stop/drain.

Shared SQLite/PostgreSQL cases cover before/exactly-at/after the heartbeat, up-only/down-only increases and decreases, zero resets, legacy NULLs, 405-client mixed batches, unknown and duplicate emails, 48 hours of active unchanged pushes versus an absent-master control, missed cycles/24-hour absence/recovery, inclusive display/quota/paging freshness, real attached-client disable plus settings/cache invalidation, reset/delete/real CreateOne recreation and downstream forwarding. Same/different-master concurrency runs both queued and inline; same-master results are complete submitted pairs and an ordered final lower reset persists. Existing subscription-cache same-output/fresh-inbound/host-on-hit tests remain in the full suite.

A newly built disposable panel also passed HTTP smoke: local counters 10/20 stayed unchanged; repeated 900/800 pushes kept the side-row timestamp; slim/detail displayed the overlay while full-list snapshots remained local; 50/60 then 0/0 overwrote the side row immediately; an identical push refreshed a deliberately aged row.

Real master/node scenarios and a genuine root→middle→leaf chain passed, with 90-second waits for unchanged 30-second global-push cadence. The chain covers combined usage, lower totals, real producer resets, deletion/recreation at each independently seeded origin and offline recovery. The fixture keeps one UUID/SubID identity across origins and does not assume that resetting a global overlay erases independently produced local usage. Existing two-panel root reset/delete scenarios remain unchanged. It does not claim live-Xray or firewall coverage; 48-hour freshness is proven with deterministic database time, not wall-clock sleeps.

Repeatable measurements

Before/after workloads used 6,708 hosted local traffic rows and 240 simulated 30-second ticks over two hours. Initial local/global seed and one warmup push were outside timing. Unchanged values stay fixed; sparse change selects (clientIndex+tick)%100 == 0; all-change increments every client's directional counters each tick; reset overwrites all counters with zero at tick 120 and stays idle. Quotas/expiry are disabled in these ingestion fixtures.

XUI_SCALE_TEST=1 XUI_DB_TYPE=sqlite go test ./internal/web/service \
  -run '^TestAcceptGlobalTrafficScale$' -count=1 -v -timeout=30m

XUI_SCALE_TEST=1 XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \
go test ./internal/web/service \
  -run '^TestAcceptGlobalTrafficScale$' -count=1 -v -timeout=30m

Both SQLite and PostgreSQL produced these affected-row counts:

Workload Row updates before Row updates after PostgreSQL INSERT calls, both revisions
Unchanged 1,609,920 13,416 8,160
Sparse 1% 1,609,920 16,096 8,160
All change 1,609,920 1,609,920 8,160
Reset halfway 1,609,920 13,416 8,160

Statements/batches are not reduced. Conflict checks may still lock rows and advance sequences; fewer affected row versions is not zero database work or zero WAL.

Supplemental PostgreSQL 18 runs controlled checkpoint conditions in isolated original/changed source snapshots with identical fixtures. Both used full_page_writes=on, max_wal_size=8GB, checkpoint_timeout=1h, one warmup and an untimed CHECKPOINT before each workload. Timed/requested checkpoint counters were unchanged during every measured interval. Temporary settings were restored to their original 1GB/5-minute values; this instrumentation/configuration is not added to committed tests or production.

Workload WAL bytes before WAL bytes after FPI before FPI after Measured wall time before → after
Unchanged 656,606,698 99,620,736 189 187 44.816s → 22.507s
Sparse 639,243,787 95,762,516 190 184 45.009s → 22.827s
All change 629,563,129 664,663,497 189 189 43.634s → 44.745s
Reset 608,240,466 99,695,128 188 187 42.127s → 22.396s

The benefit is unchanged/sparse/reset ingestion; all-change showed no benefit and had higher measured WAL. No universal speedup or statement-count reduction is claimed. Server calls, rows, execution time, WAL records/FPI/bytes and buffer counters were captured before fixture teardown across all INSERT batch shapes. Statistics reset was unchanged and dealloc=0; no cluster-wide statistics reset was used. Initial supplemental intervals containing checkpoints were rejected rather than counted as controlled evidence.

Review follow-up

Approved documentation-only commit 70f082a6931b656410028f22f1f00d08b2fff051 corrects the model's stale every-push comment: UpdatedAt tracks a persisted change or hourly unchanged heartbeat. Local-counter separation, delta accounting, MAX folding and reset propagation remain documented within the two-line comment limit. Production fix 5509c0dd7d3e38ce57db24b3bd6463adc7a6f937 remains unchanged; no published history was rewritten. Model-package golangci-lint and the six SQLite heartbeat regression cases passed again; no executable code or schema changed.

Breaking changes

None. The bounded heartbeat/freshness tradeoff is described above and in the existing architecture documentation.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior (when applicable).
  • go build ./... and the test suite pass locally.
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass. (Exercised by the full gate; backend-only PR.)
  • I updated the Wiki / README / API docs if user-facing behavior changed. (Existing architecture documentation updated.)
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6931 **Author:** [@HamedSanaei](https://github.com/HamedSanaei) **Created:** 10/25/2026 **Status:** ✅ Merged **Merged:** 10/25/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `perf/global-traffic-heartbeat-6928` --- ### 📝 Commits (2) - [`5509c0d`](https://github.com/MHSanaei/3x-ui/commit/5509c0dd7d3e38ce57db24b3bd6463adc7a6f937) perf(traffic): skip unchanged global writes between heartbeats - [`70f082a`](https://github.com/MHSanaei/3x-ui/commit/70f082a6931b656410028f22f1f00d08b2fff051) docs(traffic): describe persisted global heartbeat timestamps ### 📊 Changes **10 files changed** (+699 additions, -38 deletions) <details> <summary>View changed files</summary> 📝 `.github/workflows/ci.yml` (+10 -0) 📝 `docs/architecture.md` (+11 -0) 📝 `internal/database/model/client_global_traffic.go` (+2 -10) 📝 `internal/nodee2e/node_sync_test.go` (+116 -0) 📝 `internal/web/service/client_paging.go` (+1 -1) ➕ `internal/web/service/global_traffic_heartbeat_test.go` (+374 -0) ➕ `internal/web/service/global_traffic_postgres_test.go` (+39 -0) ➕ `internal/web/service/global_traffic_scale_test.go` (+118 -0) 📝 `internal/web/service/inbound_disable.go` (+8 -10) 📝 `internal/web/service/inbound_traffic_global.go` (+20 -17) </details> ### 📄 Description ## Summary Avoid replacing identical `client_global_traffics` row versions on every push. Directional counter changes—including lower values and zero resets—still persist immediately; identical totals refresh at an inclusive one-hour heartbeat. ## Why Every incoming hosted-client total previously updated `up`, `down` and `updated_at` even when usage was unchanged. This creates avoidable row-version/WAL churn on large installations. The existing `(master_guid,email)` UPSERT now has an action `WHERE` predicate, not a conflict-target predicate. Explicit NULL branches repair legacy nullable counters/timestamps; any directional difference writes immediately. Rows insert immediately when missing. Known-email filtering, duplicate-email last-wins behavior, queued writing, one transaction and 200-row batches remain unchanged. Ingestion and freshness readers use the existing GORM clock. The persisted-row freshness window remains inclusive at 24 hours; local-only counters/full-list snapshots, per-master componentwise-MAX read overlays, downstream forwarding, actual reset/delete cleanup and quota-disable subscription invalidation remain intact. Ordinary ingestion does not invalidate subscription settings caches. Bounded liveness tradeoff: after a master stops, coarsened timestamps can make its idle totals expire up to one hour earlier relative to its final unchanged push. Active hourly refresh leaves roughly 23 hours of missed-push margin. This is an internal fixed interval, with no new setting, clock abstraction, cache, service, schema or API change. Closes #6928. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [x] Documentation - [ ] Tests only - [x] Build / CI / tooling - [x] Other: Performance ## Areas affected - [ ] Frontend (UI / panel pages) - [x] Backend (API endpoints, login, settings) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [x] Statistics / traffic counters - [x] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [x] Multi-node (sub-nodes) - [ ] Telegram bot ## How was this tested? Passed on Windows amd64, Go 1.27.3, CGO/GCC, Node 26.12.1/npm 11.20.0, SQLite 3.53.4, and disposable PostgreSQL 18.6 and 16.15: ```bash # PostgreSQL environment variables unset. GOFLAGS=-p=1 make verify GOFLAGS=-p=1 make race make node-e2e go test ./internal/web/service \ -run 'TestAcceptGlobalTraffic|TestGlobalTraffic|TestGlobalUsage|TestStaleGlobalTraffic|TestSnapshotListNotOverlaid|TestListPagedGlobalTrafficOverlay|TestNodeRenew_ClearsGlobalTraffic' \ -count=1 -v # Run with each disposable PostgreSQL 18/16 DSN; exactly one top-level PASS, no skips. XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \ go test ./internal/web/service -run '^TestGlobalTrafficHeartbeatPostgres$' -count=1 -v go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color -shellcheck= ``` The full gate passed generation/lint/format/type checks, all Go tests, 214 frontend test files/2,000 tests, full build, Storybook and the docs-vs-panel OpenAPI check. Package serialization retains all tests and race instrumentation. Regression-first evidence: before the production change, the new boundary test observed an affected row before one hour when it required zero. Tests use real databases and synchronized affected-row counts after `gorm:create`, not merely unchanged timestamps. The atomic fake GORM clock is installed on the global DB after stopping/draining the writer and restored only after another stop/drain. Shared SQLite/PostgreSQL cases cover before/exactly-at/after the heartbeat, up-only/down-only increases and decreases, zero resets, legacy NULLs, 405-client mixed batches, unknown and duplicate emails, 48 hours of active unchanged pushes versus an absent-master control, missed cycles/24-hour absence/recovery, inclusive display/quota/paging freshness, real attached-client disable plus settings/cache invalidation, reset/delete/real `CreateOne` recreation and downstream forwarding. Same/different-master concurrency runs both queued and inline; same-master results are complete submitted pairs and an ordered final lower reset persists. Existing subscription-cache same-output/fresh-inbound/host-on-hit tests remain in the full suite. A newly built disposable panel also passed HTTP smoke: local counters 10/20 stayed unchanged; repeated 900/800 pushes kept the side-row timestamp; slim/detail displayed the overlay while full-list snapshots remained local; 50/60 then 0/0 overwrote the side row immediately; an identical push refreshed a deliberately aged row. Real master/node scenarios and a genuine root→middle→leaf chain passed, with 90-second waits for unchanged 30-second global-push cadence. The chain covers combined usage, lower totals, real producer resets, deletion/recreation at each independently seeded origin and offline recovery. The fixture keeps one UUID/SubID identity across origins and does not assume that resetting a global overlay erases independently produced local usage. Existing two-panel root reset/delete scenarios remain unchanged. It does not claim live-Xray or firewall coverage; 48-hour freshness is proven with deterministic database time, not wall-clock sleeps. ### Repeatable measurements Before/after workloads used 6,708 hosted local traffic rows and 240 simulated 30-second ticks over two hours. Initial local/global seed and one warmup push were outside timing. Unchanged values stay fixed; sparse change selects `(clientIndex+tick)%100 == 0`; all-change increments every client's directional counters each tick; reset overwrites all counters with zero at tick 120 and stays idle. Quotas/expiry are disabled in these ingestion fixtures. ```bash XUI_SCALE_TEST=1 XUI_DB_TYPE=sqlite go test ./internal/web/service \ -run '^TestAcceptGlobalTrafficScale$' -count=1 -v -timeout=30m XUI_SCALE_TEST=1 XUI_DB_TYPE=postgres XUI_DB_DSN="$TEST_PG_DSN" \ go test ./internal/web/service \ -run '^TestAcceptGlobalTrafficScale$' -count=1 -v -timeout=30m ``` Both SQLite and PostgreSQL produced these affected-row counts: | Workload | Row updates before | Row updates after | PostgreSQL INSERT calls, both revisions | |---|---:|---:|---:| | Unchanged | 1,609,920 | 13,416 | 8,160 | | Sparse 1% | 1,609,920 | 16,096 | 8,160 | | All change | 1,609,920 | 1,609,920 | 8,160 | | Reset halfway | 1,609,920 | 13,416 | 8,160 | Statements/batches are not reduced. Conflict checks may still lock rows and advance sequences; fewer affected row versions is not zero database work or zero WAL. Supplemental PostgreSQL 18 runs controlled checkpoint conditions in isolated original/changed source snapshots with identical fixtures. Both used `full_page_writes=on`, `max_wal_size=8GB`, `checkpoint_timeout=1h`, one warmup and an untimed `CHECKPOINT` before each workload. Timed/requested checkpoint counters were unchanged during every measured interval. Temporary settings were restored to their original 1GB/5-minute values; this instrumentation/configuration is not added to committed tests or production. | Workload | WAL bytes before | WAL bytes after | FPI before | FPI after | Measured wall time before → after | |---|---:|---:|---:|---:|---:| | Unchanged | 656,606,698 | 99,620,736 | 189 | 187 | 44.816s → 22.507s | | Sparse | 639,243,787 | 95,762,516 | 190 | 184 | 45.009s → 22.827s | | All change | 629,563,129 | 664,663,497 | 189 | 189 | 43.634s → 44.745s | | Reset | 608,240,466 | 99,695,128 | 188 | 187 | 42.127s → 22.396s | The benefit is unchanged/sparse/reset ingestion; **all-change showed no benefit and had higher measured WAL**. No universal speedup or statement-count reduction is claimed. Server `calls`, `rows`, execution time, WAL records/FPI/bytes and buffer counters were captured before fixture teardown across all INSERT batch shapes. Statistics reset was unchanged and `dealloc=0`; no cluster-wide statistics reset was used. Initial supplemental intervals containing checkpoints were rejected rather than counted as controlled evidence. ## Review follow-up Approved documentation-only commit `70f082a6931b656410028f22f1f00d08b2fff051` corrects the model's stale every-push comment: `UpdatedAt` tracks a persisted change or hourly unchanged heartbeat. Local-counter separation, delta accounting, MAX folding and reset propagation remain documented within the two-line comment limit. Production fix `5509c0dd7d3e38ce57db24b3bd6463adc7a6f937` remains unchanged; no published history was rewritten. Model-package `golangci-lint` and the six SQLite heartbeat regression cases passed again; no executable code or schema changed. ## Breaking changes None. The bounded heartbeat/freshness tradeoff is described above and in the existing architecture documentation. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [x] I added or updated tests for the new behavior (when applicable). - [x] `go build ./...` and the test suite pass locally. - [x] For frontend changes: `npm run lint`, `npm run typecheck`, and `npm run build` pass. (Exercised by the full gate; backend-only PR.) - [x] I updated the Wiki / README / API docs if user-facing behavior changed. (Existing architecture documentation updated.) - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:09:24 +07:00
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#6529
No description provided.