Skip to content

perf: stop counting every client to check for a connected one - #6287

Merged
metcoder95 merged 1 commit into
nodejs:mainfrom
Nabeel-akk:perf-pool-connected-check
Dec 1, 2026
Merged

metcoder95 merged 1 commit into
nodejs:mainfrom
Nabeel-akk:perf-pool-connected-check

Conversation

@Nabeel-akk

Copy link
Copy Markdown
Contributor

This relates to...

#6279

Rationale

Agent checks whether a pool still has a connected client every time one of that pool's connections closes, so it can drop the pool when it is idle. PoolBase[kConnected] answers that question by adding up kConnected over every client, and each client reads socket.destroyed. A pool holds one client per open response, so with long-lived responses (SSE, long polling, streaming RPC) each closing connection walks the whole pool. Socks5ProxyAgent has the same check.

The check only needs a yes/no answer, so it does not have to visit clients after the first connected one.

Changes

  • New internal kHasConnectedClient symbol.
  • DispatcherBase answers it generically with kConnected > 0, so any dispatcher keeps working.
  • PoolBase overrides it and returns on the first connected client.
  • Agent and Socks5ProxyAgent use it instead of kConnected > 0.
  • New test in test/agent-connection-management.js: a pool with 100 clients, only the first connected, answers true after reading exactly one client's kConnected. It fails without the PoolBase override.

kConnected itself is unchanged — stats and kFree still need the count.

Status

Tests

node --test test/agent-connection-management.js test/pool.js \
  test/pool-retired-clients.js test/pool-connection-error-memory-leak.js \
  test/client-reconnect.js test/client.js test/dispatcher.js \
  test/socks5-proxy-agent.js
# tests 150, pass 148, skipped 2, fail 0

npm run lint passes on the changed files.

I did not benchmark it: on this Windows host the reproduction from the issue runs into ephemeral-port pressure before the numbers get interesting, and the results were not stable enough to be worth quoting. The added test pins the behaviour that matters (one client read instead of all of them).

AI assistance

Prepared with AI assistance (OpenCode, DeepSeek V4.1 Flash Free) under my direction; the regression test and the reasoning above were checked against the code.

Agent and Socks5ProxyAgent ask whether a pool has at least one connected
client before closing it as unused. Pool answered by adding up kConnected
over all its clients, so with one long-lived client per open response every
closing connection visited the whole pool.

Answer the yes/no question directly: DispatcherBase keeps the generic
kConnected > 0, and PoolBase stops at the first connected client.

Assisted-by: OpenCode (DeepSeek V4.1 Flash Free)
Signed-off-by: Nabeel-akk <Account@lushvista.cc>

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new connectivity check can prematurely close and unregister mock or custom dispatchers, losing configured interceptors or disrupting connections that remain open.

2 open issues
What changed in this PR

Optimizes Undici’s idle-pool checks by checking for any connected client instead of counting every connected client.

Changes:

  • Adds an internal connectivity getter with a default implementation and an early-exit pool override.
  • Updates Agent and Socks5ProxyAgent cleanup checks to use it.
  • Adds a regression test for early exit while leaving connection counts unchanged.
File Description
test/​agent-connection-management.js Verifies the pool check stops at the first connected client.
lib/​dispatcher/​socks5-proxy-agent.js Uses the new getter during pool cleanup.
lib/​dispatcher/​pool-base.js Adds the early-exit connectivity getter.
lib/​dispatcher/​dispatcher-base.js Provides a default getter based on the connection count.
lib/​dispatcher/​agent.js Uses the new getter during idle-dispatcher cleanup.
lib/​core/​symbols.js Defines the internal connectivity symbol.

Review effort: Max

Comment thread lib/dispatcher/agent.js
// Closing it here lets the replacement Client finish those requests
// and then destroys that new connection with ClientDestroyedError.
if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
if (dispatcher[kHasConnectedClient] || dispatcher[kBusy]) {
// connected client instead of counting all of them.
get [kHasConnectedClient] () {
for (let i = 0; i < this[kClients].length; i++) {
if (this[kClients][i][kConnected]) {
@codecov-commenter

codecov-commenter commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.78%. Comparing base (2bcc4b8) to head (9395082).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6287      +/-   ##
==========================================
- Coverage   91.78%   91.78%   -0.01%     
==========================================
  Files         113      113              
  Lines       44920    44941      +21     
==========================================
+ Hits        41232    41251      +19     
- Misses       3688     3690       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@metcoder95
metcoder95 merged commit 6254048 into nodejs:main Dec 1, 2026
34 of 37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants