Repository navigation
fix(client): recreate cluster node client after a terminal connect failure - #3403
Conversation
There was a problem hiding this comment.
💡 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".
| // 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(); |
There was a problem hiding this comment.
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 👍 / 👎.
| 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(); |
There was a problem hiding this comment.
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() { | |||
There was a problem hiding this comment.
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]>
d2673ed to
eb12966
Compare
|
all good points, fixed:
added regression tests for the cache-not-flushed and recreate-on-failure paths. |
There was a problem hiding this comment.
💡 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".
| if (this._self.#socket.socketEpoch > 0) { | ||
| this._self.#clientSideCache?.onClose(); |
There was a problem hiding this comment.
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 👍 / 👎.
| if (this._self.#socket.socketEpoch > 0) { | ||
| this._self.#clientSideCache?.onClose(); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
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(); | ||
| } |
There was a problem hiding this comment.
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 > 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)
Reviewed by Cursor Bugbot for commit eb12966. Configure here.


Closes #3396.
Background
In cluster mode
RedisClusterSlots#createNodeClientassignsnode.clientbefore the connect promise settles. WhenreconnectStrategygives up (returnsfalse/Error), the connect rejects but the dead client stayed innode.client. SincenodeClient()only creates a new client whennode.clientis 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.clientnaively would leak: the abandoned client stays in the globalClientRegistrywith itserror/ready/end/__MOVEDlisteners attached (holding a strong ref back to the cluster), andRedisClient.destroy()throwsClientClosedErroron 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.RedisSocketis internal (users callclient.destroy()), and this only relaxes behavior —destroy()was previously the sole path that threwClientClosedErroron a closed client — so it is not a breaking change.#createNodeClientnow catches a connect rejection, clearsnode.client(guarded on identity so an in-flight#discoverswap is never clobbered), destroys the dead client, and rethrows so callers still see the real error. The nextnodeClient()call retries with a fresh client.Notes
reconnectStrategyreturningfalse/Error, or a configuredsocketTimeout(whose idle timeout the default strategy declines to retry). The defaultreconnectStrategyretries with exponential backoff forever and never reaches this path, so default-configured clients are unaffected.ClientRegistryentry registered after a terminal connect failure (nothing callsdestroy()on that path); that is a separate latent issue and is intentionally not addressed here.cluster-slots.spec.ts, no server required) drives a node at a dead address withreconnectStrategy: falseand asserts the secondnodeClient()retries rather than returning the cached dead client, and that the failure surfaces the real connect error rather than aClientClosedErrorfrom a non-idempotentdestroy(). 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 laternodeClient()calls kept returning a dead connection until topology refresh.Cluster: On connect rejection,
#createNodeClientnow clearsnode.client(only if it still refers to that client),destroy()s the failed client, and rethrows the real error so the nextnodeClient()builds a fresh client.Socket / client teardown:
RedisSocket.destroy()is idempotent (noClientClosedErrorwhen already closed), so cleanup after a failed connect can finish.close()/destroy()only invokeclientSideCache.onClose()whensocketEpoch > 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.