[PR #6548] [MERGED] perf(nodes): reuse one pooled client per node instead of rebuilding it #6346

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

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6548
Author: @BlindMaster24
Created: 9/15/2026
Status: ✅ Merged
Merged: 9/15/2026
Merged by: @BlindMaster24

Base: main ← Head: fix/node-sync-scale


📝 Commits (3)

  • e37af92 perf(nodes): reuse one pooled client per node instead of rebuilding it
  • 31bc136 perf(nodes): keep one client per node in the pooled cache
  • 7bc0588 style(nodes): keep the eviction comment inside the two-line cap

📊 Changes

2 files changed (+219 additions, -26 deletions)

View changed files

📝 internal/web/runtime/tls_client.go (+92 -26)
📝 internal/web/runtime/tls_client_test.go (+127 -0)

📄 Description

What this fixes

A 100-node panel polls each enabled node continuously: heartbeat and traffic sync are @every 5s compile-time constants (web.go:303-304), so one node sees ~6 requests per 5 s tick type, ~153 HTTPS requests/second across 100 nodes. Two things made that far more expensive than it needs to be.

A client per tick. probe() (service/node.go:1274) called runtime.HTTPClientForNode directly. For skip, pin and mtls modes that function built a new http.Client with a new http.Transport on every call — empty pool, so every heartbeat paid a full TCP + TLS handshake, and the CPU in a TLS handshake is server-certificate signature verification, which is exactly what shows up in monitoring.

A pool too small for the fleet. MaxIdleConns: 64 with one node per host: 100 hosts cannot fit in 64 global idle slots, so Go closed the excess and those connections re-handshook even where the client was already cached.

What was already fine, so this does not overclaim: the sync path went through Manager.RemoteFor, which caches Remote per node, so Remote.httpClient()'s sync.Once already pooled there; and verify mode plus plain http got the shared defaultNodeHTTPClient. The cost was the heartbeat probe (all non-verify nodes), the ad-hoc runtime.NewRemote(n, nil) calls in service/node.go:728, and the global idle cap on every path.

The change

  • HTTPClientForNode now caches the client per node identity — id, mode, scheme, address, port, pinned cert — with the proxy URL as a variant of it, because the heartbeat reaches a node directly while the sync path reaches it through its egress. A hit returns the pooled client.
  • When a node's identity changes, its previous client is closed (CloseIdleConnections) and dropped: no request can be served by a client built for a trust decision that no longer applies. InvalidateMasterClientConnections still works unchanged — the credential-rotating transport observes the epoch on its next RoundTrip, which is what its doc comment already promised.
  • Idle caps raised to 512 global / 8 per host, in one newNodeTransport helper that replaces the same struct literal in three places. Arithmetic: one idle connection per node host, plus the sync and push requests, so 512 covers a 200-node fleet with room for concurrency; the memory is a few KB per idle connection.
  • Client construction is delegated to a private buildNodeHTTPClient; the now-unreachable verify fallthrough at the end of the old function is gone, since the wrapper owns that decision.

Rejected: caching keyed by node id alone, which would serve a skip client to a node the operator has since switched to pin, and would hand a direct client to a proxied request.

Red first, with the exact output

TestHTTPClientForNodeReusesOneConnectionAcrossCalls runs two calls against an httptest TLS server counting http.StateNew connections. Probe — build a client per call (the pre-change behaviour):

--- FAIL: TestHTTPClientForNodeReusesOneConnectionAcrossCalls (0.02s)
    tls_client_test.go:130: TLS handshakes = 2, want 1: a rebuilt client re-handshakes on every tick

Green after the change, and TestHTTPClientForNodeRebuildsWhenNodeIdentityChanges pins the cache key the security argument rests on: a node switched to pin (or given a proxy) must never be served the client built to skip verification.

The pre-existing tests in the same file still pass unchanged — HTTPClientForNodeVerifyShared, HTTPClientForNodeMTLSRebuildsTLSConfigAfterCredentialInvalidation, HTTPClientForNodeProxyMTLSRebuildKeepsProxyAndNewCredential, HTTPClientForNodePinInvalid, HTTPClientForNode_ProxyPinPreservesPinEnforcement, HTTPClientForNode_ProxyVerifyNoPin. That is the check that the cache did not weaken credential rotation or pin enforcement.

Gate

  • go test ./internal/web/runtime — green (local run through a -overlay that supplies a pure-Go SQLite driver; the tree's go.mod/go.sum are unchanged).
  • gofmt -l and go vet on the package — clean.
  • CI on this head: go-test, golangci, race.

What I did not do, and why

  • Proxy paths keep http.DefaultTransport's caps (100 global / 2 per host), since netproxy owns that transport and only egress-tagged nodes use it. Sequential per-node ticks need one connection, so the per-host cap is not the constraint there; raising it would change every other netproxy caller.
  • GetAllInboundClientIps() is still called inside the per-node loop (node_traffic_sync_job.go:450) — one full table read per node per tick. Same family, different mechanism (DB reads and pushed bytes rather than handshakes) and a separate diff; it belongs in its own PR.
  • The largest traffic win is a protocol change and needs your call: every tick pulls the node's whole panel/api/inbounds/list with settings, streamSettings, sniffing and client stats, although it rarely changes. A conditional request on the existing route (node answers 304 when the body would be identical, master keeps the previous snapshot) would cut the bulk of the 1.8 KB average response. I have not written it — it changes master↔node wire behaviour and version compatibility.

🔄 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/6548 **Author:** [@BlindMaster24](https://github.com/BlindMaster24) **Created:** 9/15/2026 **Status:** ✅ Merged **Merged:** 9/15/2026 **Merged by:** [@BlindMaster24](https://github.com/BlindMaster24) **Base:** `main` ← **Head:** `fix/node-sync-scale` --- ### 📝 Commits (3) - [`e37af92`](https://github.com/MHSanaei/3x-ui/commit/e37af92eb63f1be5ddd8e7d731d8e903351ac2e2) perf(nodes): reuse one pooled client per node instead of rebuilding it - [`31bc136`](https://github.com/MHSanaei/3x-ui/commit/31bc136210a2dc6b3a0e11ab331138f6108cf819) perf(nodes): keep one client per node in the pooled cache - [`7bc0588`](https://github.com/MHSanaei/3x-ui/commit/7bc0588b9dc4a636f90c1af6935d8907f6db6602) style(nodes): keep the eviction comment inside the two-line cap ### 📊 Changes **2 files changed** (+219 additions, -26 deletions) <details> <summary>View changed files</summary> 📝 `internal/web/runtime/tls_client.go` (+92 -26) 📝 `internal/web/runtime/tls_client_test.go` (+127 -0) </details> ### 📄 Description ## What this fixes A 100-node panel polls each enabled node continuously: heartbeat and traffic sync are `@every 5s` compile-time constants (`web.go:303-304`), so one node sees ~6 requests per 5 s tick type, ~153 HTTPS requests/second across 100 nodes. Two things made that far more expensive than it needs to be. **A client per tick.** `probe()` (`service/node.go:1274`) called `runtime.HTTPClientForNode` directly. For `skip`, `pin` and `mtls` modes that function built a **new** `http.Client` with a **new** `http.Transport` on every call — empty pool, so every heartbeat paid a full TCP + TLS handshake, and the CPU in a TLS handshake is server-certificate signature verification, which is exactly what shows up in monitoring. **A pool too small for the fleet.** `MaxIdleConns: 64` with one node per host: 100 hosts cannot fit in 64 global idle slots, so Go closed the excess and those connections re-handshook even where the client was already cached. What was *already* fine, so this does not overclaim: the sync path went through `Manager.RemoteFor`, which caches `Remote` per node, so `Remote.httpClient()`'s `sync.Once` already pooled there; and `verify` mode plus plain `http` got the shared `defaultNodeHTTPClient`. The cost was the heartbeat probe (all non-verify nodes), the ad-hoc `runtime.NewRemote(n, nil)` calls in `service/node.go:728`, and the global idle cap on every path. ## The change * `HTTPClientForNode` now caches the client per **node identity** — `id, mode, scheme, address, port, pinned cert` — with the proxy URL as a variant of it, because the heartbeat reaches a node directly while the sync path reaches it through its egress. A hit returns the pooled client. * When a node's identity changes, its previous client is closed (`CloseIdleConnections`) and dropped: no request can be served by a client built for a trust decision that no longer applies. `InvalidateMasterClientConnections` still works unchanged — the credential-rotating transport observes the epoch on its next `RoundTrip`, which is what its doc comment already promised. * Idle caps raised to `512` global / `8` per host, in one `newNodeTransport` helper that replaces the same struct literal in three places. Arithmetic: one idle connection per node host, plus the sync and push requests, so 512 covers a 200-node fleet with room for concurrency; the memory is a few KB per idle connection. * Client construction is delegated to a private `buildNodeHTTPClient`; the now-unreachable `verify` fallthrough at the end of the old function is gone, since the wrapper owns that decision. Rejected: caching keyed by node id alone, which would serve a `skip` client to a node the operator has since switched to `pin`, and would hand a direct client to a proxied request. ## Red first, with the exact output `TestHTTPClientForNodeReusesOneConnectionAcrossCalls` runs two calls against an `httptest` TLS server counting `http.StateNew` connections. Probe — build a client per call (the pre-change behaviour): ``` --- FAIL: TestHTTPClientForNodeReusesOneConnectionAcrossCalls (0.02s) tls_client_test.go:130: TLS handshakes = 2, want 1: a rebuilt client re-handshakes on every tick ``` Green after the change, and `TestHTTPClientForNodeRebuildsWhenNodeIdentityChanges` pins the cache key the security argument rests on: a node switched to `pin` (or given a proxy) must never be served the client built to skip verification. The pre-existing tests in the same file still pass unchanged — `HTTPClientForNodeVerifyShared`, `HTTPClientForNodeMTLSRebuildsTLSConfigAfterCredentialInvalidation`, `HTTPClientForNodeProxyMTLSRebuildKeepsProxyAndNewCredential`, `HTTPClientForNodePinInvalid`, `HTTPClientForNode_ProxyPinPreservesPinEnforcement`, `HTTPClientForNode_ProxyVerifyNoPin`. That is the check that the cache did not weaken credential rotation or pin enforcement. ## Gate * `go test ./internal/web/runtime` — green (local run through a `-overlay` that supplies a pure-Go SQLite driver; the tree's `go.mod`/`go.sum` are unchanged). * `gofmt -l` and `go vet` on the package — clean. * CI on this head: `go-test`, `golangci`, `race`. ## What I did not do, and why * **Proxy paths keep `http.DefaultTransport`'s caps** (100 global / 2 per host), since `netproxy` owns that transport and only egress-tagged nodes use it. Sequential per-node ticks need one connection, so the per-host cap is not the constraint there; raising it would change every other `netproxy` caller. * **`GetAllInboundClientIps()` is still called inside the per-node loop** (`node_traffic_sync_job.go:450`) — one full table read per node per tick. Same family, different mechanism (DB reads and pushed bytes rather than handshakes) and a separate diff; it belongs in its own PR. * **The largest traffic win is a protocol change and needs your call:** every tick pulls the node's whole `panel/api/inbounds/list` with settings, streamSettings, sniffing and client stats, although it rarely changes. A conditional request on the existing route (node answers `304` when the body would be identical, master keeps the previous snapshot) would cut the bulk of the 1.8 KB average response. I have not written it — it changes master↔node wire behaviour and version compatibility. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:08:07 +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#6346
No description provided.