Skip to content

fix(cluster): replace a node client that gave up after it connected - #3656

Open
teddyteh wants to merge 2 commits into
redis:masterfrom
teddyteh:fix/cluster-replace-terminated-node-client
Open

teddyteh wants to merge 2 commits into
redis:masterfrom
teddyteh:fix/cluster-replace-terminated-node-client

Conversation

@teddyteh

@teddyteh teddyteh commented Nov 21, 2026 •

Copy link
Copy Markdown

Description

Follow-up to #3403, which fixed the first-connect half of #3396. This covers the other half: a cluster node client that connected successfully and later gave up.

When a connected node client's reconnectStrategy stops (returns false/Error), for example on a socket timeout, which the default strategy declines to retry, the client is closed for good and emits terminated. nodeClient() only creates a new client when node.client is falsy, so it keeps returning the closed one, and every command for that node's slots fails with ClientClosedError: The client is closed. The #3403 fix doesn't reach this path, because the original connect() resolved long ago. The only ways out are a topology change that drops the node's address, or recreating the whole cluster client. Users have reported this since #2141 ("ClientClosedError forever until the application is restarted", closed as stale), and again in a comment on #2948.

We hit it in production with socketTimeout set: a shard stalls for about a minute, the idle node connection times out, and that shard's slots then fail for minutes after the shard has recovered, until the application rebuilds the cluster client.

Change

The node client is dropped and destroyed when it emits terminated, as suggested in #3674. That event fires only when reconnectStrategy gives up, never on close() or QUIT, so a client still draining is left alone without extra checks. The next nodeClient() call then connects a fresh client through the existing path. In #createClient:

.on('terminated', () => {
  if (node.client !== client) return;
  node.client = undefined;
  this.#reconnectionTracker.removeClient(client._clientId);
  client.destroy();
})

The identity check keeps a newer client that #discover may have swapped in. The client is destroyed in a microtask, after the socket error has rejected its pending commands with the real cause. The handler covers node data clients only; the pub/sub clients #createClient also builds are left as they are (see #3652).

Two supporting changes, from review:

  • #handleSmigrated keeps the source client in a local for the whole migration, so a source that terminates mid-migration doesn't break the cleanup.
  • nodeClient() doesn't open a connection after close()/destroy() (a flag those set and connect() clears), for a caller still holding a node whose client was dropped.

Notes

  • Config-conditional, like fix(client): recreate cluster node client after a terminal connect failure #3403. It needs a reconnectStrategy that can give up, which includes the default strategy whenever socketTimeout is set. Default-configured clients never reach this path.
  • No backoff here. If the node is still unreachable, the next command's connect fails and the one after retries again. Concurrent callers share one connectPromise, and each attempt is bounded by connectTimeout/socketTimeout, which matches what fix(client): recreate cluster node client after a terminal connect failure #3403 does for first-connect failures. Happy to add a per-node backoff if you'd prefer one.
  • Tests (cluster-slots.spec.ts, no Redis server; a fake RESP2 node like the existing discovery tests):
    • replaces a node client whose reconnectStrategy gave up after it connected: connects a real cluster to the fake node, drops the connection with reconnectStrategy: false, then asserts nodeClient() returns a new, open client. It fails without the fix (the closed client must be replaced).
    • keeps a node client that is still draining after close(): a PING is held by the server, the client is closed, and nodeClient() must still return it and the PING must resolve.
    • does not reconnect a closed node client after the cluster is destroyed: destroy() doesn't emit terminated, so no new connection is opened.
    • rejects pending commands with the socket failure when the node gives up: a held PING rejects with SocketClosedUnexpectedlyError, not DisconnectsClientError.
    • does not open a node connection after the cluster is destroyed, once the node gave up.
    • finishes a slot migration whose source client terminates mid-migration.
    • drops a node client that gives up during its first connect, once, and retries on the next call: the path that runs both the listener and the catch in #createNodeClient. It asserts the real connect error surfaces (not ClientClosedError), terminated fires once, node.client is cleared, and the next call creates a fresh client.

Checklist

  • Does npm test pass with this change (including linting)? cluster-slots.spec.ts passes (24), and eslint and tsc are clean on the changed files. I haven't run the full Docker-backed suite.
  • Is the new or changed code fully tested?
  • Is a documentation update included? No API change.

Note

Medium Risk
Changes core cluster connection lifecycle and SMIGRATED handling; behavior is heavily tested but affects all shard routing after terminal disconnects.

Overview
Fixes cluster shards getting stuck on ClientClosedError after a node connection dies for good (e.g. socketTimeout with default reconnectStrategy). nodeClient() used to keep returning the same closed client until topology refresh or a full cluster rebuild.

A terminated listener on each node data client now clears node.client, removes the client from the reconnection tracker, and **destroy()**s it on the next microtask so in-flight commands see the real socket error, not DisconnectsClientError. Clients still draining after close()``** are untouched because **terminated` does not fire there.

#shutDown is set on destroy() / graceful teardown and cleared on connect(), so late nodeClient() calls reject with ClientClosedError instead of opening untracked connections.

Slot migration (#handleSmigrated) pins sourceClient for the whole handler so a mid-migration terminate does not leave **TypeError**s or stale nodes in masters / nodeByAddress.

New unit tests cover replacement after give-up, draining clients, shutdown guards, first-connect termination, error surfacing, and migration when the source terminates mid-flight.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T07:29:40.045294Z e4c68c7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 959adc9464

ℹ️ 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".

@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Nice — this is the connected-then-gave-up half of #3396. Heads-up on an overlap: my #3652 rewrites nodeClient() and drops the #waitForNodeClient path, so we're editing the same spot, and whichever lands first the other will need to rebase.

More usefully: my current rewrite would actually regress your case. It returns node.client as soon as it's set and only creates a fresh one when it's falsy, so a client that connected and later gave up (still assigned, but isOpen === false) would be handed back closed — exactly what your guard prevents. So #3652 needs to fold your drop-and-recreate in, whichever routing direction it lands on.

Happy to coordinate however you'd prefer — rebase mine onto yours once it lands, or pull your guard into #3652. Either way your fix should stand.

@teddyteh

Copy link
Copy Markdown
Author

Thanks, good catch on the overlap. Happy with whichever order the maintainers prefer. If #3652 lands first I'll rebase #3656 onto it; in your synchronous nodeClient() the guard goes just before the if (!node.client) create branch. If #3656 lands first, the replaces a node client whose reconnectStrategy gave up after it connected spec should keep the guard from being lost in your rebase.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Perfect — I'll fold the guard in right there when I rework #3652, and if yours lands first the rebase plus your spec will keep me honest. Thanks, teddy.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Thanks for the isReady fix — that is the right line to draw. A client draining after close()/QUIT is isOpen === false but stays ready until its queue empties, while one whose reconnectStrategy gave up never got there, so keying the guard on readiness separates exactly those two. The PING-hold test pins it well.

An update on the overlap, since it resolved in your favour: nkaradzhov picked the bounded-wait option on #3592, so #3652 no longer rewrites nodeClient(). It is back to master's shape — connectPromise still awaited, with the wait raced against the cluster's command timeout — and the queue routing and ClientClosedError retry are gone. The regression I flagged against your case went with them: #3652 no longer returns a synchronously created client, so it cannot hand back the dead-after-connect one.

I checked the branches and they merge cleanly in either order — your guard sits at the top of nodeClient(), mine is inside #waitForNodeClient, so they do not touch the same lines. And #3652 on its own still does not fix what you are fixing: master's if (node.client) return Promise.resolve(node.client) still returns a closed client, so this stands on its own merits regardless of which lands first. No ordering constraint from my side.

@nkaradzhov

Copy link
Copy Markdown
Collaborator

Closing this, as it does not follow our contributing guidelines (https://github.com/redis/node-redis/blob/master/CONTRIBUTING.md#before-starting-work). We doubt this comes up in a real application: the default reconnect strategy gives up only on a socket timeout, and in practice socketTimeout is set far higher than a one-minute stall. If you hit this in a real application, please open an issue that describes it, including your client configuration, and we can take it from there.

@teddyteh

Copy link
Copy Markdown
Author

Thanks for taking a look. I've opened #3674 with our production configuration and the impact, as you asked. In short, our socketTimeout is 12 s and our shards stall for about a minute, so we hit this several times a day. I'll wait for your view there before reopening anything here.

@nkaradzhov nkaradzhov reopened this Nov 24, 2026
@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Glad this is reopened — the production numbers in #3674 make the case well.

Since #3652 touches this file, here is where the two stand now, so neither of you has to work it out from the diff.

nodeClient() itself is byte-identical to master on my branch, so nothing lands there from my side in either merge order.

The node client's handler chain in #createClient() is a different matter, and it is worth knowing before you write the terminated handler. #3652 removes the wasReady latch entirely — both the if (!wasReady) return; early exit in .on('reconnecting') and the wasReady = true in .on('ready'), along with the declaration. That is #3592's third point: a node that is down from the start has to count for the reconnection-attempt topology refresh, or its slots can never move after a failover.

Two consequences:

  • A .on('terminated') added to that chain sits directly next to those lines, so whoever lands second may get a small conflict there. Trivial to resolve, just not a clean auto-merge.
  • If any version of this fix was going to lean on wasReady to tell "gave up after connecting" apart from "never connected", that latch no longer exists on my branch. Keying on terminated avoids that entirely, which is another point in favour of the change Nikolay asked for.

No ordering constraint from my side either way.

A node client that connected and later gave up reconnecting (e.g. after a
socket timeout) stayed in node.client, so nodeClient() kept returning it
and every command for the node's slots failed with ClientClosedError
until the cluster client was rebuilt.

Drop and destroy the client on its 'terminated' event, which fires only
when reconnectStrategy gives up, never on close() or QUIT, so a draining
client is left alone. The next nodeClient() call connects a fresh one.

Fixes redis#3674
@teddyteh
teddyteh force-pushed the fix/cluster-replace-terminated-node-client branch from db41dd5 to 8605413 Compare November 25, 2026 07:10
@teddyteh

Copy link
Copy Markdown
Author

Thanks for reopening it. I've reworked it as you suggested:

  • The node client is now dropped on terminated, in #createClient, with an identity check so a client #discover swapped in is left alone. The nodeClient() change is gone, so nodeClient() matches master.
  • I kept the specs, including the draining-client one, which now passes because close() never emits terminated.
  • I added drops a node client that gives up during its first connect, once, and retries on the next call. It covers the path where both the listener and the catch in #createNodeClient run. It checks that the real connect error surfaces (not ClientClosedError), terminated fires once, node.client is cleared, and the next call creates a fresh client.

I rebased onto master and squashed it into one commit. cluster-slots.spec.ts passes (21), and eslint and tsc are clean. Without the listener, the "replaces a node client…" spec fails.

@Cdineshreddy12 thanks for the heads-up about #3652. The listener sits next to the wasReady lines, so whichever of us lands second may need to resolve a small conflict there. It doesn't depend on wasReady.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Read through 8605413. The listener does the four things I would have worried about: it guards on identity so a client #discover swapped in is left alone, unregisters from the reconnection tracker, actually destroys rather than just dropping the reference, and leaves a draining client alone because close() never emits terminated. Keeping nodeClient() identical to master is a nice outcome too — it means the recovery is entirely in the event path.

The first-connect spec is the one I would have asked for, since that is the case where both the listener and the catch in #createNodeClient can run. Checking that terminated fires once and that the real connect error surfaces rather than ClientClosedError covers the ordering trap well.

One thing worth a comment rather than a change, because it reads as covered when it is not. #createClient() builds three kinds of client: the node's data client, the dedicated pub/sub client in #initiatePubSubClient(), and the sharded one in #initiateShardedPubSubClient(). For the latter two, node.client is the node's data client and never the pub/sub client, so node.client !== client is always true and the listener returns immediately. A pub/sub client whose reconnectStrategy gives up therefore stays on pubSubNode, and since connectPromise is cleared once it first connects, getPubSubClient() hands back the closed client and every later subscribe fails with ClientClosedError with nothing to clear it — the same shape as what you are fixing here, one path over.

I am not suggesting you take that on in this PR. Nikolay and I have an open thread on #3652 about the pub/sub node pinning to a node it cannot reach, and this is the terminal variant of it, so it probably belongs with that decision. A line in the comment noting the listener is node-client-only would stop the next reader assuming pub/sub is handled.

Agreed on the conflict: your listener sits right next to the wasReady lines #3652 removes, so whoever lands second resolves a couple of lines. Nothing deeper than that, and no ordering constraint from my side.

@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: 860541366d

ℹ️ 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".

@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 8605413. Configure here.

…n a node gives up

- Destroy the terminated client in a microtask, after the socket error has
  rejected its pending commands with the real cause, not
  DisconnectsClientError.
- #handleSmigrated keeps the source client for the whole migration, so a
  source that terminates while in-flight replies are awaited no longer
  throws and leaves the emptied source in masters/nodeByAddress.
- nodeClient() no longer opens a connection after close()/destroy(), for a
  caller still holding a node whose client was dropped.
- Note that the 'terminated' handler covers node data clients only.
@teddyteh

Copy link
Copy Markdown
Author

@Cdineshreddy12 thanks for reading it closely. Good point about the pub/sub clients: the handler returns straight away for them, because node.client is the data client. I added a line to the comment saying it handles node data clients only, and left the pub/sub terminal case for the #3652 discussion, as you suggest.

e4c68c7 also addresses Codex's three findings on 8605413, each with a spec that fails on 8605413:

  • pending commands keep the real socket failure (destroy moved to a microtask),
  • a slot migration whose source terminates mid-migration completes, and
  • nodeClient() doesn't open connections after close()/destroy().

cluster-slots.spec.ts passes (24), and eslint and tsc are clean.

@Cdineshreddy12

Copy link
Copy Markdown
Contributor

Thanks for adding the node-client-only line — that was the only thing I wanted from it.

I actually merged the two branches locally to check the conflict we both predicted, and we were both wrong about where it is. git merge-tree of e4c68c7 against my f6a6f34:

  • cluster-slots.ts merges cleanly. Your terminated listener and the wasReady lines fix(cluster): don't hang connect() or commands on an unreachable node (#3592) #3652 removes sit next to each other, but git resolves them without help. No conflict in the production file in either order.
  • The one conflict is a single import line in cluster-slots.spec.ts. Master has import { ClientClosedError } from '../errors';, I add TimeoutError, you add SocketClosedUnexpectedlyError. Whoever lands second resolves it to import { ClientClosedError, SocketClosedUnexpectedlyError, TimeoutError } from '../errors';. Our new describe blocks land at different offsets and merge fine.

Both branches also merge cleanly against current master on their own, so there is still no ordering constraint — just that one line to join up afterwards.

One note on the rework, since I had cited it: nodeClient() is no longer identical to master on your side, because of the #shutDown guard. That does not affect the merge, since #3652 does not touch that function. Worth knowing that the guard returns ClientClosedError and #3652 retries on ClientClosedError inside #waitForNodeClient — but that retry is gated on this.#isOpen, and destroy()/close() clear #isOpen in the same breath as setting #shutDown, so the two cannot disagree and there is no retry loop. I checked rather than assumed.

The queueMicrotask ordering for the real socket error is a neat catch.

@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: e4c68c7bfb

ℹ️ 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".

// Only a node's data client is handled here: for the pub/sub clients this
// method also builds, node.client is the data client, so this returns.
if (node.client !== client) return;
node.client = undefined;

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 Process migrations after the source data client terminates

If the data client terminates before an SMIGRATED notification arrives on another live node or Pub/Sub connection, this assignment makes #handleSmigrated() skip the entire source entry through its sourceNode.client === undefined guard. The handler has already recorded the sequence ID, so later copies are ignored too: moved slots remain routed to the source, which also remains selectable for keyless and fan-out commands. A two-node comparison processes the same notification on the parent but leaves the source unchanged here. Run the topology updates and source cleanup without a data client, skipping only the queue-transfer work.

Useful? React with 👍 / 👎.

this.#reconnectionTracker.removeClient(sourceNode.client?._clientId);
sourceNode.client.destroy();
this.#reconnectionTracker.removeClient(sourceClient._clientId);
sourceClient.destroy();

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 Dispose replacement clients when removing a migration source

If the source terminates while a full-slot migration is awaiting in-flight replies, a concurrent nodeClient(sourceNode) lookup can install a replacement before cleanup resumes. Cleanup removes the node from masters and nodeByAddress, but this line destroys only the captured original sourceClient, leaving the replacement in sourceNode.client open and untracked. In a two-node runtime check, that connection remains open even after slots.destroy(). Retain the stable reference for queue operations, but also prevent or dispose replacement clients when removing the source.

Useful? React with 👍 / 👎.

@nkaradzhov nkaradzhov left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks. The terminated approach looks right. Two small changes, please:

  1. Leaked client after a full-slot migration. If the source terminates while #handleSmigrated waits for in-flight replies, a concurrent nodeClient(sourceNode) can install a new client. Cleanup then destroys only sourceClient, so the new one stays open and untracked, even after destroy(). At cleanup, please also remove and destroy sourceNode.client when it is set and is not sourceClient.
  2. Migration spec. finishes a slot migration whose source client terminates mid-migration clears sourceNode.client by hand. Please make the source client emit a real terminated instead, so the spec exercises the listener.

We're fine with Codex's other finding on e4c68c7 (SMIGRATED skipped when the source has no client): the next command to that node gets MOVED, which refreshes the topology. The hang on a node that stays down is #3592, which #3652 covers.

This branch has not been deployed

No deployments
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.

3 participants