Skip to content

fix(cluster): don't fall back to a replica when no primary is left - #2275

Merged
PavelPashov merged 1 commit into
redis:mainfrom
EeeasyCode:fix/cluster-retry-readonly-replies
Nov 6, 2026
Merged

PavelPashov merged 1 commit into
redis:mainfrom
EeeasyCode:fix/cluster-retry-readonly-replies

Conversation

@EeeasyCode

@EeeasyCode EeeasyCode commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2274

This pull request stops Cluster from falling back to a replica when no primary is left in the pool. The command is handled like a closed connection instead, so the existing slot refresh and retry find the primary. This is the approach agreed in #2274, and it replaces the READONLY retry from the first version of this PR.

On a cluster with one shard, once the connection to the primary is lost, commands went to a replica on a READONLY connection. The replica runs a Lua script instead of answering MOVED, so the script failed with READONLY, the slots were never refreshed and every later script failed too. #2274 has the reproduction and the steps.

With retryDelayOnFailover: 0 or maxRedirections: 0 nothing retries, so the command fails right away and the slots are refreshed for the next one. The README already says the default scaleReads never sends queries to slaves, so the docs didn't need a change.

Two changes on top of the snippet in #2274:

  • It only rejects when the cluster is ready. CLUSTER commands reach this code earlier, and handleError() doesn't retry before ready, so cluster.cluster("INFO") right after new Cluster() failed with Connection is closed. instead of waiting in the offline queue.
  • A pipeline keeps the role of its first command. With scaleReads: "slave", a pipeline starting with a write had the write rejected while the read after it went to a replica. A rejected command is never written, so the pipeline never flushed and exec() never resolved.

Behavior changes to flag:

  • While no primary is left in the pool, commands that a replica used to answer fail once the retries run out, about 1.6 s with the default options (maxRedirections × retryDelayOnFailover), with Too many Cluster redirections. Last error: Error: Connection is closed. PING is where this shows: with the primary dead for 10 s and no failover on Valkey 8.1.11, it failed 0 of 114 times on main and 5 of 69 times on this branch. It needs a single shard or every primary down at once, and it stops once a replica is promoted. GET and SET fail in that window on both, 5 or 6 times each.
  • Read-only commands that scaleReads allows on a replica don't change.

Not covered: a script with no keys that writes, after a normal failover. The old primary stays in the pool, so the command never reaches this code and keeps getting READONLY, same as main. As discussed in #2274, scripts should declare their keys.

Tests

test/functional/cluster/missing_primary.ts uses mock servers like tryagain.ts and clusterdown.ts, and replaces readonly.ts from the first version. 5 of its 8 tests fail on main. The other 3 cover what shouldn't change: reads with scaleReads, a pipeline that starts with a write, and a CLUSTER command sent while connecting. The last two fail with the snippet as written.

With npm run docker:setup on Node.js 24.15.0:

  • npm run lint: 0 errors, 23 warnings, same as main
  • npm run build: passes
  • npm run test:js: 3155 passing, 1 pending, 6 failing. The 6 are georadiusbymember and georadiusbymember_ro, which also fail on main (3147 passing).
  • npm run test:cluster: 72 passing
  • npm run test:tsd: passes
  • npx prettier --check passes on the changed files. npm run format-check already fails on main.

One of three test:js runs also failed should close sentinel subscriptions after quit - RESP 3, with 3 sockets on the mock sentinels instead of 2. That test doesn't use Cluster, and sentinel.ts passed 8 of 8 runs on its own, on this branch and on main. It didn't happen in three full runs on main. On a just-started cluster, two #nodes() tests in test:cluster fail on both as well, because replicas stay out of CLUSTER SLOTS until they have a replication offset, so I wrote a few keys first.

Against real servers, with one primary and one replica, I ran scripts every 200 ms for 4 s after CLIENT KILL on the primary:

Server Failed on main Failed on this branch
Redis 6.2.24 20 of 20 0 of 20
Redis 7.2.5 20 of 20 0 of 20
Redis 8.6.1 20 of 20 0 of 20
Valkey 8.1.11 20 of 20 0 of 20
Valkey 9.1.3 20 of 20 0 of 20

EVAL, a defineCommand script (EVALSHA) and a script with no keys gave the same numbers. SET didn't fail on either. Neither did a script with a #!lua shebang, except on Redis 6.2, which can't compile that syntax on either build.

On Valkey 8.1.11 with this branch, scripts with keys had no errors when the connection was lost and the cluster then failed over and back. On main every script fails after that failback. Losing the connection before a failover with two replicas, and DEBUG SEGFAULT with CLUSTER FAILOVER TAKEOVER, also had no errors. With three shards, scripts with keys, pipelines and MULTI had no READONLY errors through graceful, takeover, killed and hung primaries.

Not run: ElastiCache. CLIENT KILL stands in for the lost connection here.


Note

Medium Risk
Changes core cluster command routing and failover fallbacks when slot metadata still lists a master but the pool has no master connection; mis-routing could affect writes and pipelines during partial outages.

Overview
When the cluster is ready but no master connection is available (e.g. only a replica left in the pool after the primary drops), write/master-targeted commands no longer fall through to a random node via getSampleInstance("all"). That fallback could send Lua scripts or other writes to a replica (which fails with READONLY instead of MOVED and never refreshes slots).

The client now tries getSampleInstance(to) first, then—if to is master and there is still no connection—treats it like a lost primary: optionally refreshes the slot cache when retryDelayOnFailover or maxRedirections is 0, and rejects with Connection is closed. so existing failover retry logic (connectionClosed / handleError) can refresh slots and retry instead of hitting the replica.

Pipelines pin the read/write role on the pipeline node: the first command sets node.to, and later commands reuse it so a batch stays on one node and a pipeline that starts with a write keeps routing as master even when scaleReads: "slave".

Adds test/functional/cluster/missing_primary.ts for scripts, pipelines, scaleReads, redirection limits, slot refresh with disabled retries, and CLUSTER during connect.

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

@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T09:10:26.420795Z a940a57 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

Copy link
Copy Markdown

💡 Codex Review

const READONLY_ERROR = /^READONLY |-READONLY You can't write/;

P2 Badge Avoid retrying scripts on a matching error string

When an EVAL or defineCommand script returns redis.error_reply("READONLY ...") after performing a write, this regex treats the application-generated reply as a stale-replica error, so handleError() re-executes the script up to maxRedirections even on a healthy primary. Redis does not roll back earlier Lua writes after an error, so a write such as INCR can be applied repeatedly. The error text alone cannot establish that the command reached a replica.

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

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@PavelPashov

Copy link
Copy Markdown
Contributor

@EeeasyCode Thanks for the PR and the thorough testing notes. Before going further with review, could we settle the approach on #2274 first, as described in the contribution guide? I've left a question there about handling the missing primary in sendCommand routing instead of retrying on READONLY.

When the connection to a slot's primary is lost, the node leaves the
pool and the slots stay as they are until a MOVED arrives. On a cluster
with one shard the only node left to send a command to is a replica,
and connections to replicas run in READONLY mode. The replica then runs
a Lua script instead of answering MOVED, because a script without a
shebang isn't flagged as a write. The write inside it fails with
READONLY, the slots are never refreshed and every later script fails
the same way.

Handle a missing primary like a closed connection instead of falling
back to a replica, so the existing failover handling refreshes the slots
and retries the command. Commands that aren't allowed on a replica now
fail once the retries run out, including PING.

This only applies once the cluster is ready, because handleError()
doesn't retry before that and CLUSTER commands sent earlier must stay in
the offline queue. A pipeline now keeps the role of its first command: a
rejected command is never written, so a write rejected ahead of a read
that went to a replica would leave the pipeline waiting forever.
@EeeasyCode
EeeasyCode force-pushed the fix/cluster-retry-readonly-replies branch from 6169ec2 to a940a57 Compare November 5, 2026 09:04
@EeeasyCode EeeasyCode changed the title fix(cluster): refresh slots and retry on READONLY errors fix(cluster): don't fall back to a replica when no primary is left Nov 5, 2026

@PavelPashov PavelPashov 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.

LGTM

@PavelPashov
PavelPashov merged commit c353e34 into redis:main Nov 6, 2026
22 checks passed
github-actions Bot pushed a commit that referenced this pull request Nov 23, 2026
# [6.1.0](v6.0.0...v6.1.0) (2026-11-23)

### Bug Fixes

* accept field arrays in hmget/hmgetBuffer types ([#2167](#2167)) ([c0cd66c](c0cd66c))
* align auto-pipeline callbacks for dynamic commands ([#2180](#2180)) ([7479cab](7479cab))
* apply the legacy reply shape to uppercase command names ([#2252](#2252)) ([8ecb423](8ecb423))
* clean up Sentinel failover subscriptions after quit ([#2198](#2198)) ([727edfa](727edfa))
* close the monitor connection when monitor() rejects ([#2247](#2247)) ([3cfe93f](3cfe93f))
* cluster stuck in close ([#2217](#2217)) ([a5fad1d](a5fad1d))
* **cluster:** bucket autopipelined MSET objects by their first key ([#2207](#2207)) ([b4e3237](b4e3237))
* **cluster:** do not reject pipeline commands for connecting nodes when offline queue is disabled ([#2277](#2277)) ([71516ca](71516ca)), closes [#2096](#2096) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [#2276](#2276)
* **cluster:** do not throw when auto-pipelining meets an uncached slot ([#2233](#2233)) ([e04bb49](e04bb49))
* **cluster:** don't fall back to a replica when no primary is left ([#2275](#2275)) ([c353e34](c353e34))
* **cluster:** emit sharded subscriber connect errors silently ([#2241](#2241)) ([00c9a22](00c9a22))
* **cluster:** end when quit() or disconnect() is called while reconnecting ([#2240](#2240)) ([8526785](8526785))
* **cluster:** hash autopipelined Buffer keys by their bytes ([#2208](#2208)) ([a8378bd](a8378bd)), closes [Command#getSlot](https://github.com/Command/issues/getSlot)
* **cluster:** hash lone surrogates as the UTF-8 Node sends ([#2242](#2242)) ([cfa464d](cfa464d))
* **cluster:** keep forwarding sharded messages after reconnecting from end ([#2251](#2251)) ([326e987](326e987))
* **cluster:** map every slot when stringNumbers is enabled ([#2255](#2255)) ([8ce4115](8ce4115))
* **cluster:** match Buffer shard channels when unsubscribing ([#2203](#2203)) ([d997d01](d997d01))
* **cluster:** pass the retry delay to the reconnecting event ([#2291](#2291)) ([ed50383](ed50383))
* **cluster:** resend only the redirected command in a pipeline ([#2214](#2214)) ([46b3191](46b3191)), closes [#2075](#2075) [Pipeline#exec](https://github.com/Pipeline/issues/exec) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [Pipeline#exec](https://github.com/Pipeline/issues/exec) [Cluster#sendCommand](https://github.com/Cluster/issues/sendCommand) [Pipeline#exec](https://github.com/Pipeline/issues/exec)
* **cluster:** stay ended when nodes removed by disconnect() end late ([#2237](#2237)) ([61896e5](61896e5)), closes [#2217](#2217)
* **cluster:** stop refreshing slots when disconnect() is called during a refresh ([#2249](#2249)) ([80501ed](80501ed))
* **cluster:** support zero-argument sunsubscribe with sharded subscribers ([#2137](#2137)) ([13ff050](13ff050)), closes [#2133](#2133)
* **cluster:** vendor cluster-key-slot to fix empty hash tag slot bug ([#2172](#2172)) ([b479b76](b479b76))
* correct Sentinel retry ordering after node connection failures ([#2246](#2246)) ([a10e0fa](a10e0fa))
* decode integer replies up to MAX_SAFE_INTEGER exactly ([#2164](#2164)) ([28940b5](28940b5))
* decode RESP3 attribute replies instead of failing the connection ([#2213](#2213)) ([6a8cb3e](6a8cb3e)), closes [#decodeNestedType](https://github.com/redis/ioredis/issues/decodeNestedType) [#decodeMapAsObject](https://github.com/redis/ioredis/issues/decodeMapAsObject) [#decodeMapKey](https://github.com/redis/ioredis/issues/decodeMapKey)
* decode RESP3 doubles with Number ([#2150](#2150)) ([6fb5a10](6fb5a10))
* end when quit() or disconnect() is called while reconnecting ([#2245](#2245)) ([81bc16a](81bc16a))
* handle rejection from the db-restoring select on reconnectOnError ([#2229](#2229)) ([1b744ca](1b744ca))
* handle rejections from auto-resubscribe and select on reconnect ([#2187](#2187)) ([de2fbdf](de2fbdf))
* inherit connectTimeout for cluster subscribers ([#2220](#2220)) ([db57c2d](db57c2d))
* keep String.prototype in fast mode after defining VerbatimString ([#2206](#2206)) ([90e1261](90e1261))
* keep subscriber mode while other channel kinds remain subscribed ([#2196](#2196)) ([eb97beb](eb97beb))
* keep the exec error out of its own previousErrors ([#2218](#2218)) ([2c602cf](2c602cf))
* keep the selected db for commands queued while reconnecting ([#2235](#2235)) ([9f90154](9f90154))
* preserve empty keys and match patterns in scan streams ([#2199](#2199)) ([b169c3a](b169c3a))
* redact credentials from the command attached to errors ([#2231](#2231)) ([a26f8de](a26f8de)), closes [#1713](#1713)
* reject unfulfilled commands dropped on reconnect ([#2194](#2194)) ([d95d05a](d95d05a)), closes [#2193](#2193)
* reset retry attempts when connect() is called after giving up ([#2204](#2204)) ([b597303](b597303)), closes [#1463](#1463)
* reset the manual close state when connect() is called after end ([#2250](#2250)) ([7713c4b](7713c4b))
* resolve argument-less (p)unsubscribe once its own kind is empty ([#2238](#2238)) ([280812b](280812b))
* restore the db selected by a non-lowercase SELECT after reconnecting ([#2248](#2248)) ([400b774](400b774))
* **sentinel:** handle errors on failover detector connections ([#2257](#2257)) ([09bcda5](09bcda5))
* **sentinel:** retry unreachable sentinels in a loop instead of recursing ([#2270](#2270)) ([6bee8d2](6bee8d2))
* **types:** accept documented TLS profile options ([#2195](#2195)) ([56a7fb8](56a7fb8)), closes [#1626](#1626)
* **types:** add event overloads to Cluster interface ([#2201](#2201)) ([3996eaf](3996eaf)), closes [#2191](#2191)
* **types:** add smessage and smessageBuffer event overloads ([#2191](#2191)) ([ee48f4c](ee48f4c)), closes [#2190](#2190)
* **types:** allow number for zrange stop argument ([#2163](#2163)) ([932f4c2](932f4c2))

### Features

* add BITRANGEINTARRAY command ([#2279](#2279)) ([b141399](b141399))
* add set member expiration commands ([#2261](#2261)) ([5efba6b](5efba6b)), closes [redis/redis#15938](redis/redis#15938)
* bless commands ([#2209](#2209)) ([9181ee0](9181ee0))
* **cluster:** allow configuring node role for Pub/Sub subscriber ([#2176](#2176)) ([6b9130c](6b9130c))
* sharded subscriber health check ([#2268](#2268)) ([1b25ffb](1b25ffb))
* smart client handoffs ([#2165](#2165)) ([d8ae3cb](d8ae3cb))
* sorted set move commands ([#2288](#2288)) ([2f4f09d](2f4f09d))
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 6.1.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cluster: Lua scripts keep failing with READONLY after losing the connection to the primary

2 participants