Skip to content

fix(client): recreate cluster node client after a terminal connect failure - #3403

Merged
nkaradzhov merged 1 commit into
redis:masterfrom
nkaradzhov:fix/cluster-dead-node-client-leak
Aug 15, 2026
Merged

nkaradzhov merged 1 commit into
redis:masterfrom
nkaradzhov:fix/cluster-dead-node-client-leak

Conversation

@nkaradzhov

@nkaradzhov nkaradzhov commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #3396.

Background

In cluster mode RedisClusterSlots#createNodeClient assigns node.client before the connect promise settles. When reconnectStrategy gives up (returns false/Error), the connect rejects but the dead client stayed in node.client. Since nodeClient() only creates a new client when node.client is falsy, it then kept returning the same non-functional client forever — a node could never recover until a topology refresh happened to drop its address.

Clearing node.client naively would leak: the abandoned client stays in the global ClientRegistry with its error/ready/end/__MOVED listeners attached (holding a strong ref back to the cluster), and RedisClient.destroy() throws ClientClosedError on an already-closed socket, so the dead client could not be disposed.

Change

  • RedisSocket.destroy() is now idempotent — it no longer throws when the socket is already closed, so a terminally-failed client can be disposed and its metrics registration and credentials subscription are released instead of leaking. RedisSocket is internal (users call client.destroy()), and this only relaxes behavior — destroy() was previously the sole path that threw ClientClosedError on a closed client — so it is not a breaking change.
  • #createNodeClient now catches a connect rejection, clears node.client (guarded on identity so an in-flight #discover swap is never clobbered), destroys the dead client, and rethrows so callers still see the real error. The next nodeClient() call retries with a fresh client.

Notes

  • Config-conditional. This only triggers when the connect can terminally reject: a reconnectStrategy returning false/Error, or a configured socketTimeout (whose idle timeout the default strategy declines to retry). The default reconnectStrategy retries with exponential backoff forever and never reaches this path, so default-configured clients are unaffected.
  • Scope. This fixes the cluster node-client caching/disposal path. A standalone client also leaves its ClientRegistry entry registered after a terminal connect failure (nothing calls destroy() on that path); that is a separate latent issue and is intentionally not addressed here.
  • Regression test (cluster-slots.spec.ts, no server required) drives a node at a dead address with reconnectStrategy: false and asserts the second nodeClient() retries rather than returning the cached dead client, and that the failure surfaces the real connect error rather than a ClientClosedError from a non-idempotent destroy(). It fails if either half of the fix is reverted.

🤖 Generated with Claude Code


Note

Medium Risk
Touches cluster connection lifecycle, socket destroy semantics, and RESP3 pooled client-side cache on teardown—important paths but narrowly scoped with regression tests.

Overview
Fixes #3396: cluster shard clients that fail to connect terminally were left cached on node.client, so later nodeClient() calls kept returning a dead connection until topology refresh.

Cluster: On connect rejection, #createNodeClient now clears node.client (only if it still refers to that client), destroy()s the failed client, and rethrows the real error so the next nodeClient() builds a fresh client.

Socket / client teardown: RedisSocket.destroy() is idempotent (no ClientClosedError when already closed), so cleanup after a failed connect can finish. close() / destroy() only invoke clientSideCache.onClose() when socketEpoch > 0, so disposing a never-connected node does not flush a shared pooled client-side cache used by healthy connections.

Regression tests cover cluster retry behavior and pooled-cache preservation on destroy() without connect.

Reviewed by Cursor Bugbot for commit eb12966. Bugbot is set up for automated code reviews on this repo. Configure here.

@nkaradzhov
nkaradzhov requested a review from PavelPashov August 14, 2026 14:44

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d2673edd1a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/client/lib/client/socket.ts Outdated
Comment on lines 469 to 473
// Idempotent: safe to call on an already-closed socket. A terminal connect
// failure (reconnectStrategy gave up) leaves #isOpen === false, and callers
// still need to dispose the client — throwing here would abort that cleanup.
this.#isOpen = false;
this.destroySocket();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid emitting close events for redundant destroys

When destroy() is called after the socket is already closed—now possible for public client.destroy() calls and for the new cluster cleanup after a terminal connect failure—this still calls destroySocket(), which always publishes a connection-closed event and emits end. In those cases there may be no live socket to close, so users can observe spurious or duplicate end/node-disconnect events and misleading application_close telemetry; please make the already-closed/no-socket path a no-op while still allowing the owning client to unregister its metrics.

Useful? React with 👍 / 👎.

Comment on lines 468 to 473
destroy() {
if (!this.#isOpen) {
throw new ClientClosedError();
}

// Idempotent: safe to call on an already-closed socket. A terminal connect
// failure (reconnectStrategy gave up) leaves #isOpen === false, and callers
// still need to dispose the client — throwing here would abort that cleanup.
this.#isOpen = false;
this.destroySocket();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve pending close when destroy wins the race

With this guard removed, client.destroy() can now run while a prior client.close() is already waiting for pending replies after setting #isOpen to false. In that case destroy() flushes the queue and destroys the socket, but RedisClient.close() only resolves from its data-driven maybeClose callback when the queue becomes empty, so the flush never wakes the existing close promise and await client.close() can hang forever; if destroy is allowed during an in-flight graceful close, it also needs to settle that close path.

Useful? React with 👍 / 👎.

@@ -466,10 +466,9 @@ const retryIn = strategy(retries, cause);
}

destroy() {

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.

Could we ensure destroySocket() emits CONNECTION_CLOSED and end only once per connection lifecycle, resetting that guard on connect()? Repeated destroy() calls currently trigger duplicate cleanup handlers and telemetry despite being described as idempotent.

…ilure

In cluster mode #createNodeClient assigns node.client before the connect
promise settles. When reconnectStrategy gives up (returns false/Error) the
connect rejects but the dead client stayed in node.client, so nodeClient()
kept returning the same non-functional client forever — a node could never
recover without a full topology refresh dropping its address.

Clearing node.client naively would leak: the abandoned client stays in the
global ClientRegistry with its error/ready/end/__MOVED listeners attached
(holding a strong ref to the cluster), and RedisClient.destroy() threw
ClientClosedError on an already-closed socket, so it could not be disposed.

Fix:
- #createNodeClient catches a connect rejection, clears node.client (guarded
  on identity so an in-flight #discover swap is never clobbered), destroys the
  dead client, and rethrows so callers still see the error. The next
  nodeClient() then retries with a fresh client.
- RedisSocket.destroy() returns early when already closed instead of throwing,
  so the owning client can finish disposing itself (unregister metrics, dispose
  credentials). Returning also makes destroy() idempotent: a repeated call no
  longer re-runs destroySocket(), which would republish CONNECTION_CLOSED and
  re-emit 'end' (spurious node-disconnect events / misleading telemetry).
- RedisClient.close()/destroy() only flush the client-side cache when the
  client actually connected (socketEpoch > 0). A pooled/cluster cache is shared
  across node clients; a client that never connected cached nothing and missed
  no invalidations, so flushing it would needlessly cold-start the healthy
  connections that share it.

Fixes redis#3396. Regression tests: a terminal connect failure recreates the node
client (and surfaces the real error, not a ClientClosedError from a throwing
destroy); a never-connected client's destroy is idempotent and leaves a shared
pooled cache intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nkaradzhov
nkaradzhov force-pushed the fix/cluster-dead-node-client-leak branch from d2673ed to eb12966 Compare August 14, 2026 18:50
@nkaradzhov

Copy link
Copy Markdown
Collaborator Author

all good points, fixed:

  • shared cache wipe — close()/destroy() now only flush the client-side cache when the client actually connected (socketEpoch > 0). A node that never connected cached nothing, so it no longer nukes the pooled cache the healthy nodes share.
  • duplicate end/telemetry — went with @PavelPashov's suggestion: destroy() early-returns when the socket's already closed, so a repeat call can't re-run destroySocket(). Once per lifecycle, no extra flag needed.
  • one note on the destroy()-during-close() hang: that one's pre-existing (close() waits on a data listener that a concurrent flush never wakes) and reproduces without this change, so I left it out of here — happy to file it separately.

added regression tests for the cache-not-flushed and recreate-on-failure paths.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eb129662dd

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2230 to +2231
if (this._self.#socket.socketEpoch > 0) {
this._self.#clientSideCache?.onClose();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Prevent failed connects from clearing the shared cache

In the terminal-connect-failure scenario this guard runs too late to preserve a pooled cache: RedisSocket.#shouldReconnect() emits error before client.connect() rejects, and the client error listener calls clientSideCache.onError(), whose BasicPooledClientSideCache implementation clears the entire shared cache. Consequently, one unreachable cluster node still evicts entries used by healthy nodes despite this new socketEpoch check; the regression test misses this because it destroys a never-connected client without attempting connect(). The never-ready distinction also needs to be applied to that error path.

Useful? React with 👍 / 👎.

Comment on lines +2194 to +2195
if (this._self.#socket.socketEpoch > 0) {
this._self.#clientSideCache?.onClose();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Invalidate cache entries after an in-progress close

When close() is called during the initial connection with a cacheable command already in the offline queue, socketEpoch is still zero here, so onClose() is skipped. The handshake can subsequently finish, increment the epoch, and drain that command as part of the graceful close; its cache promise then resolves and installs a value after the client has closed. If the client reconnects—or the provider is shared with another client—that value can be returned after invalidations were missed while this connection was closed. Defer the cache-close decision until the drain completes or invalidate pending entries regardless of the current epoch.

Useful? React with 👍 / 👎.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit eb12966. Configure here.

// connections would needlessly cold-start them.
if (this._self.#socket.socketEpoch > 0) {
this._self.#clientSideCache?.onClose();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Repeated destroy flushes shared cache

Medium Severity

Making RedisSocket.destroy() return when already closed lets RedisClient.destroy() continue past that call. A second destroy() (or destroy() after close()) on a client with socketEpoch &gt; 0 still runs clientSideCache.onClose(), so a shared BasicPooledClientSideCache can be cleared again and cold-start healthy pool/cluster peers. Previously the second socket.destroy() threw and aborted that path.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit eb12966. Configure here.

@nkaradzhov
nkaradzhov merged commit 37a2692 into redis:master Aug 15, 2026
25 of 26 checks passed
@nkaradzhov
nkaradzhov deleted the fix/cluster-dead-node-client-leak branch August 15, 2026 12:08
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.

Cluster node client stays cached after terminal reconnectStrategy failure, and clearing it on failure leaks clients

2 participants