A slow reconnect can mark a dead Redis connection as healthy

Your Redis connection drops. The client reconnects. A second later it drops again, and the client reconnects again. Everything looks fine in the logs.
Then every command starts failing, and the client never tries to reconnect, because as far as it knows it is already connected.
This is a real bug that was reported against ioredis in issue #2099. The fix is one number. I want to show you the race first, because once you see it you will start noticing the same shape in your own code.
Connecting is not instant
When we say “the client connected”, we are flattening several steps that each take time:
- Look up the host name.
- Open the TCP socket.
- Say hello to Redis:
AUTH,SELECT,HELLO, whatever your options need. - Mark the client as ready.
Step 3 is a round trip to a server over a network. It can take 2 milliseconds or 2 seconds. While it is happening, your process is free to do other things. Including starting another connection.
The race
Picture two reconnect attempts:
- Attempt A starts. Its handshake is slow.
- The connection drops again while A is still talking.
- Attempt B starts. Its handshake is fast, and it finishes.
- The client is now using B’s socket. Good.
- Attempt A finally finishes. It runs its “I am done, mark us ready” code.
Attempt A is holding socket A, which is dead. Nobody told A that B took over, because nothing ever did. So A overwrites the client’s state with its own dead socket and sets the status to ready.
Now the client believes it is connected. Reconnect logic only runs when a connection drops, and from the client’s point of view nothing dropped. It just sits there, healthy and useless.
Thirty lines that reproduce it
Save this as race.mjs and run it with node race.mjs. No Redis needed, no packages.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
class Client {
constructor(useEpoch) {
this.useEpoch = useEpoch;
this.epoch = 0;
this.socket = null;
}
async connect(name, handshakeMs) {
this.epoch += 1;
const myEpoch = this.epoch; // snapshot, taken at the start
const mySocket = { name };
await sleep(handshakeMs); // the handshake is in flight
if (this.useEpoch && myEpoch !== this.epoch) return; // stale, drop it
this.socket = mySocket;
}
}
async function run(useEpoch) {
const c = new Client(useEpoch);
const slow = c.connect("socket-A (dead)", 60); // starts first, ends last
await sleep(10);
const fast = c.connect("socket-B (live)", 10);
await Promise.all([slow, fast]);
return c.socket.name;
}
console.log("without epoch check:", await run(false));
console.log("with epoch check: ", await run(true));Output on Node 22:
without epoch check: socket-A (dead)
with epoch check: socket-B (live)The only difference between the two runs is three lines. Let’s look at them.
The counter
this.epoch starts at zero and goes up by one every time a new connection attempt begins. That is the whole idea.
Each attempt copies the number into a local variable at the moment it starts:
this.epoch += 1;
const myEpoch = this.epoch;myEpoch belongs to that one attempt. It never changes again. this.epoch lives on the shared client and keeps climbing.
When the slow attempt wakes up from its await, it compares the two:
if (myEpoch !== this.epoch) return;If they still match, nothing newer started, and this attempt is still the one in charge. If they differ, somebody else took over while it was away, so it returns and touches nothing.
That is a stale check, and it costs one integer comparison.
The same thing in ioredis
Here is the real code, from lib/redis/event_handler.ts. The snapshot:
const { connectionEpoch } = self;
const isActiveConnect = () =>
connectionEpoch === self.connectionEpoch && self.status === "connect";
const finishHandshake = () => {
if (!isActiveConnect()) {
return false;
}
self.condition.handshake = false;
return true;
};connectionEpoch is pulled off self into a const, which freezes it for this attempt. isActiveConnect() compares the frozen copy against the live one, exactly like the demo.
And the check at the end of the handshake, with the project’s own comment explaining what it prevents:
try {
await sendHandshake(getHandshakeCommands(self), self.condition.protocol);
} catch (err) {
// The connection may have been closed (and possibly already
// reconnected) while the client setup commands above were still
// in flight. In that case this callback is stale and the
// connection is no longer the one we are setting up, so calling
// readyHandler() would mark a dead connection as "ready" and
// permanently stop reconnection.
// See https://github.com/redis/ioredis/issues/2099
if (!isActiveConnect()) {
return;
}
// ...
}Read the last part of that comment again: permanently stop reconnection. Not “drop a command”, not “log a warning”. The client gives up forever, and it does it quietly.
In lib/Redis.ts the counter is as plain as it looks:
private connectionEpoch = 0;It goes up in connect(), and again when the client swaps in a different transport. Every path that produces a new connection bumps it, which is what makes the stale check trustworthy.
Why nobody catches this in review
I find this bug interesting because every single function involved is correct.
The handshake function marks the connection ready. That is its job. Read it on its own and there is nothing to flag. The reconnect function starts a new attempt. Also its job, also fine.
The bug only exists in the gap between two runs of the same function, where the second one starts after the first and finishes before it. Those two runs never appear next to each other in the file. A reviewer reading top to bottom has no reason to line them up.
So “read the code more carefully” would not have caught it. A different question would have:
Can this function be running twice at the same time, for two different reasons, and finish out of order?
For anything that reconnects, retries, or refetches, the answer is usually yes.
Where else this shows up
The shape is: start slow thing A, start newer thing B that replaces A, A finishes anyway and writes over B’s work.
You have probably met it already:
- A search box where you type
red, thenredis. The response forredarrives last and replaces the right results with stale ones. - A tab switcher that loads data per tab. Click fast enough and tab one’s data lands inside tab two.
- Any “refresh the token / reload the config / re-subscribe” loop that can be triggered again before the previous one settles.
A counter fixes all of them the same way. Bump it when you start, snapshot it locally, compare before you write anything back.
Counter or AbortController?
Node and browsers both ship AbortController, so it is fair to ask why ioredis does not use one here.
They solve different problems:
AbortControlleractually stops the work. The socket read is torn down, the fetch is cancelled, the resources go back early.- A counter lets the work finish and then throws the result away.
If the in-flight work is expensive or holds something scarce, cancel it. If it is a handshake that is about to end on its own anyway, a counter is lighter: no listeners to add, no listeners to remove, nothing to leak if you forget the cleanup.
ioredis wants the second one. The stale handshake can finish in peace. It just is not allowed to speak.
The takeaway
If you maintain anything that reconnects, go find the function that runs when a connection becomes ready, and ask whether two attempts can overlap. If they can, a counter and three lines closes the hole:
this.epoch += 1;
const myEpoch = this.epoch;
// ... await the slow part ...
if (myEpoch !== this.epoch) return;The version of this bug that bites you will not look like a bug. It will look like a service that was fine for months and then stopped talking to Redis one afternoon, with no error in the logs, because the client was sure it had a connection the whole time.