Redis Cluster
The 16,384 Hash Slot Model
slot = CRC16(key) mod 16384
With 3 masters:
Node A: slots 0 – 5460
Node B: slots 5461 – 10922
Node C: slots 10923 – 16383Why 16,384? The cluster bus gossips each node's slot ownership as a bitmap in every heartbeat. 16,384 bits = 2 KB — small enough to send constantly. 1M slots would be 128 KB per heartbeat. Cluster was never designed for thousands of nodes, so 16,384 gives plenty of granularity.
CLUSTER SLOTS ← show live slot→node mapping
CLUSTER SHARDS ← newer alternative
CLUSTER KEYSLOT user1000 ← which slot does this key hash to?Gossip Protocol: Topology and Failure Detection
Cluster nodes form a full mesh on the cluster bus (data port + 10,000). They continuously PING/PONG, carrying node ID, IP/port, slots owned, and observed health of other nodes. No central coordinator — topology propagates epidemically.
Each config change carries a monotonically increasing configEpoch. When two nodes disagree about slot ownership, higher epoch wins — this is how a freshly-promoted replica's claim supersedes the dead master's. The rest of this part is how that promotion actually gets decided: who notices a primary is gone, how they agree on it, and how the replacement wins an epoch.
Why Cluster doesn't need a separate watcher fleet
Sentinel and Cluster are solving different problems. Sentinel buys availability for a dataset that already fits on one machine: one primary holds 100% of the keys, and every replica is a full copy of that same 100% — failover just relabels which full copy is "primary." Cluster buys capacity: the keyspace itself is cut into pieces so no single machine has to hold or serve all of it. HA falls out of that split as a side effect, not the goal.
Concretely, with 30M keys:
Sentinel — 1 shard: Cluster — 3 shards:
primary — 30M keys (100%) Shard A: primary A + replica — keys 1-10M (slots 0-5460)
replica-1 — 30M keys (100%) Shard B: primary B + replica — keys 10M-20M (slots 5461-10922)
replica-2 — 30M keys (100%) Shard C: primary C + replica — keys 20M-30M (slots 10923-16383)Each shard is already its own miniature primary+replica HA unit — structurally identical to a whole Sentinel deployment in miniature. What differs is who watches the primaries. Sentinel has exactly one primary: it cannot watch itself or vote on its own health, so an entirely separate fleet of processes has to do it from the outside. Cluster needs ≥3 independent primaries anyway, for capacity, for reasons that have nothing to do with failover — and once they exist, they can double as each other's watchers for free. Primary B and primary C aren't a monitoring layer bolted on top; they're just the other shards, doing their own unrelated jobs, who also happen to vote on whether A is alive.
One consequence worth holding onto through everything below: a Cluster failure is always scoped to a single shard. Only one primary (A) dies, only one replica of A gets promoted — shards B and C are never at risk, never touched, and keep serving their own slice of the keyspace the entire time. They're bystanders acting as jurors, not participants.
How gossip actually detects and agrees on failure
The payload — what's actually inside a PING
The cluster bus (port+10000) isn't RESP — it's a binary header plus a gossip section. Every PING and PONG carries the sender's own state (node ID, currentEpoch, configEpoch, slot bitmap) plus a random sample of other nodes it knows about, each stamped with the flags the sender currently believes about them — including whether the sender thinks that node is PFAIL. That's the whole mechanism in one sentence: suspicion doesn't only spread when you fail to reach someone, it rides secondhand inside everyone else's routine heartbeats to everyone else.
Step 1 — PFAIL is one node's private opinion
Each node tracks ping_sent / pong_received timestamps per peer. Every cron tick it checks: has this peer been silent longer than cluster-node-timeout (default 15s)? If so, it flips a flag in its own table only — nobody else has been told yet. This is exactly Sentinel's s_down under a different name: one node's subjective read, not cluster truth.
Step 2 — gossip turns that opinion into a failure report on everyone else
On this node's next outgoing PING/PONG, the suspected node's gossip entry carries the PFAIL flag. Every primary that receives it doesn't overwrite its own opinion — it appends "sender X reports this node down, at time T" to a list attached to its own record of that node (clusterNodeAddFailureReport()). So each primary accumulates who else is complaining, not just what it personally sees. Reports older than cluster-node-timeout × 2 are pruned, so an old blip can't ambush a count much later.
Step 3 — the majority check, and a hard broadcast (not more gossip)
Every cron tick, each node tallies, for any node it holds reports on: own opinion + unexpired reports from other primaries — does that exceed floor(N_primaries/2) + 1? The first node anywhere in the cluster whose tally crosses that line does two things at once: flips its local flag PFAIL→FAIL, and fires an explicit FAIL message — a distinct message type, not a gossip payload — broadcast directly to its connections. Every node that receives a FAIL message marks it immediately: no timeout, no waiting for its own tally to catch up.
That's the asymmetry worth remembering: reaching FAIL is decentralized — any primary can be the one to notice majority first, there's no leader — but propagating it is push, not epidemic. That's why Cluster reacts faster than Sentinel's SDOWN→ODOWN round-trip. What exactly N_primaries counts, and why the threshold sits where it does, is worth unpacking on its own — it's the difference between a cluster that survives a dead primary and one that doesn't.
What N actually counts — and why ">N/2" specifically
N_primaries is deliberately narrower than "cluster node," or even "master node": it's the count of primaries that currently own at least one hash slot — full stop. That's the same number Redis tracks internally (server.cluster->size), recomputed from the same slot bitmaps every node already gossips — not from a membership list.
$ redis-cli -p 30001 cluster nodes
07c37dfe... 127.0.0.1:30001 master - 0 1426238316232 0 connected 0-5460
4a2c1c... 127.0.0.1:30002 master - 0 1426238317232 0 connected 5461-10922
29b77... 127.0.0.1:30003 master - 0 1426238318232 0 connected 10923-16383
912fe... 127.0.0.1:30004 slave 07c37dfe... 0 1426238318000 0 connectedTwo things fall out of that definition that are easy to miss:
- Replicas can't count — there's nothing to count. A replica carries no slot bitmap of its own; it just holds a pointer to the primary it follows and serves whatever slots that primary owns. It has no independent ownership entry in anyone's gossip. Only if it wins a promotion does a bitmap get copied onto it — only then does it become countable.
- A master with zero slots doesn't count either — a real, reachable state, not a hypothetical. Add a fourth node D to a running 3-primary cluster via
CLUSTER MEETbefore resharding any slots onto it: D shows up asmasterinCLUSTER NODES, everyone gossips with it, butN_primariesstays 3. The same thing happens in reverse when a primary is fully decommissioned — the instant its bitmap goes all-zero, it drops out of the count.
| N (slot-owning primaries) | quorum = floor(N/2)+1 | What that means |
|---|---|---|
| 2 | 2 | Need both to agree. If one dies, the other has 1 opinion forever — quorum is mathematically unreachable. No automatic failover, ever. |
| 3 | 2 | Any 2 of the 3 agreeing is enough — survives exactly 1 primary failure. |
| 5 | 3 | Survives 2 simultaneous primary failures with the remaining 3 still able to agree. |
The threshold is strictly more than half, rather than some other fraction, because of what that specific ratio buys: with quorum > N/2, any two quorum-sized groups drawn from the same N must overlap by at least one node — you cannot split N nodes into two disjoint groups that are both bigger than half of N. That overlap is what makes two contradictory majority decisions impossible: it's why two replicas can't both win a promotion vote, and why a network partition can't let both halves declare victory independently.
That last case is worth tracing through, since it's exactly the scenario the split-brain callout later in this part describes. Take N=3 (A, B, C) and partition A away from B and C, with A still alive but unreachable to either. From B and C's side: A is unreachable, they gossip-confirm it to each other, 2 opinions ≥ quorum(2) → they declare A FAIL and promote its replica. From A's side: B and C both look unreachable too — A marks them PFAIL locally, but it only has its own opinion, 1 < quorum(2), so A can never declare anyone else FAIL. The majority side gets to act unilaterally; the minority side is mathematically stuck. The gap that remains — the reason the split-brain risk exists at all — is that A has no idea any of this happened: if clients can still reach it, it keeps accepting writes on its own slots until the partition heals and it discovers B/C's replica now holds a higher configEpoch for those slots.
Step 4 — the replica queues by data freshness before asking for votes
Seeing its own primary go FAIL doesn't make a replica fire a vote request instantly. It waits:
delay = 500ms + random(0-500ms) + (rank × 1000ms)rank is this replica's position among the dead primary's other replicas, sorted by replication offset — the most caught-up replica gets rank 0 (shortest delay). In the normal case only that replica's timer expires before it notices anyone else starting an election, so there's no real contention. Before starting the clock it also runs a sanity check: if it's been cut off from the dead primary for longer than (cluster-node-timeout × cluster-replica-validity-factor) + repl-ping-replica-period (default factor 10 → ~150s), it refuses to stand at all — its data is judged too stale to become the new source of truth.
Step 5 — the vote: FAILOVER_AUTH_REQUEST / ACK
When its timer fires uncontested, the replica bumps the cluster's currentEpoch — a logical clock every node ratchets up to the highest value it has ever seen — and broadcasts FAILOVER_AUTH_REQUEST to every primary. Each primary votes at most once per epoch: it confirms the requester really is a replica of a node it also believes is FAIL, checks it hasn't already voted this epoch, then replies FAILOVER_AUTH_ACK. That one-vote-per-epoch rule is the entire split-brain guard — two replicas can never win the same epoch, and epochs only move forward.
The requesting replica counts ACKs; a majority (same N/2+1 quorum as FAIL detection) wins — no further negotiation. A concrete run:
replica-of-A: rank=0 (highest offset among A's replicas)
→ waits 500ms + random(0-500ms) + 0×1000ms ≈ 750ms, sees no competing election
t+750ms: currentEpoch 7 → 8, broadcasts FAILOVER_AUTH_REQUEST(epoch=8) to B, C
B: hasn't voted in epoch 8, agrees A is FAIL → ACK
C: hasn't voted in epoch 8, agrees A is FAIL → ACK
replica-of-A: 2/3 ACKs (quorum) → wins epoch 8Step 6 — takeover, and making sure everyone finds out fast
The winner does the equivalent of REPLICAOF NO ONE, copies the dead primary's slot bitmap onto itself, bumps its own configEpoch to the winning epoch — highest configEpoch always wins a slot claim, which is what stops a partitioned old primary from reclaiming its slots if it later reconnects — and immediately broadcasts an unsolicited PONG cluster-wide announcing the new ownership, instead of waiting for its next lazy gossip turn. Every other node updates its slot→node table on receipt.
| Message | Carries | Trigger |
|---|---|---|
| PING / PONG | Sender's own state + gossip section (sampled peers, as the sender currently sees them) | ~1/s per sampled peer; forced if a peer hasn't been pinged in > node-timeout/2 |
| FAIL | "Node X is FAIL" — a push, not a gossip entry | Fired once, by whichever node's local tally first crosses quorum |
| FAILOVER_AUTH_REQUEST | Replica's node ID + new epoch | After the rank-based election delay elapses uncontested |
| FAILOVER_AUTH_ACK | One primary's vote | Requester's primary is FAIL, and this primary hasn't voted this epoch yet |
| UPDATE | "Your config epoch for this slot is stale" | A node sees a slot claimed at a lower epoch than it already knows |
Clients get MOVED or CLUSTERDOWN during the window and must retry. The election is faster than Sentinel's because escalation to FAIL is a direct broadcast, not a Sentinel-style round of asking peers "can you reach it?" after the fact.
MOVED and ASK Redirects
GET foo (sent to a node that doesn't own foo's slot)
-MOVED 3999 10.0.0.2:6379
"Slot 3999 is at 10.0.0.2:6379 — go there permanently."| Redirect | Meaning | Client behavior |
|---|---|---|
MOVED | Permanent ownership change | Update the cached slot→node map. Rare in practice — only after topology changes. |
ASK | Transient, during slot migration: "this specific key already moved to the target node" | Ask there this one time; do not update the cache. |
Hash Tags: Forcing Co-location
A multi-key operation only works if all keys are in the same slot. If a key contains {...}, only the substring inside the first {} is hashed:
CLUSTER KEYSLOT {user1000}.followers → same slot as
CLUSTER KEYSLOT {user1000}.profile → this oneBoth hash only user1000, so they co-locate. Now MGET {user1000}.followers {user1000}.profile works, and you can run MULTI/EXEC or Lua scripts across them.
Why MGET across slots fails
A multi-key command executes on a single node against its local keyspace. If keys live on different nodes, no single node holds all the data:
CROSSSLOT Keys in request don't hash to the same slotYou must either (a) hash-tag related keys to co-locate them, or (b) have the client fan out per-slot and merge — losing cross-key atomicity.
The Consistency Guarantee Cluster Does NOT Provide
Redis Cluster is not a CP system. An acknowledged
OKcan be lost during failover.
Client → master: SET k v
master applies in memory → replies OK ──────► client thinks: durable ✓
master THEN streams write to replica ──────► (asynchronous, lagging)| Partial mitigation | What it does | Limitation |
|---|---|---|
WAIT numreplicas timeout | Block until ≥N replicas ack | Not a true sync commit — a timeout doesn't roll back |
min-replicas-to-write / min-replicas-max-lag | Refuse writes if not enough caught-up replicas | Trades availability for safety |
WAITAOF 7.2+ | Like WAIT but for AOF fsync — disk-level durability ack | Still not a distributed transaction |