TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท redis ยท valkey ยท sharding ยท distributed systems

Redis Cluster

Redis Cluster (and Valkey cluster) splits the keyspace into 16,384 hash slots spread across several primaries, each with replicas, and smart clients route every command straight to the node that owns its key's slot.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ“• Sharding๐ŸŽฝ Redis and Valkey

๐Ÿ–จ๏ธ Cheat sheet

16,384 numbered pigeonholes

A big school keeps everything in one wall of pigeonholes, numbered from 0 to 16,383. That's far too many for one person to look after, so the office splits them up. Jo looks after pigeonholes 0 to 5,460, Sam the middle stretch and Priya the rest.

Every item has a name on its label, like "Ana's homework". To find its pigeonhole, the office does the same fixed sum on the letters of the name, which always lands on a number from 0 to 16,383. Same name, same number, every time. Those numbered pigeonholes are called hash slots.

So a teacher dropping something off never has to search: do the sum, see whose stretch the number is in, and walk to that person.

Hash slots and primaries

Redis Cluster shards one keyspace across several Redis servers with no proxy in between. The unit of sharding is the hash slot: there are exactly 16,384 of them, and every key maps to one:

1HASH_SLOT = CRC16(key) mod 16384

The CRC16 is the XMODEM variant. Each primary owns a set of slot ranges, for example 0โ€“5460, 5461โ€“10922 and 10923โ€“16383 with three primaries. Single-key commands are served by the primary that owns the key's slot, so throughput and memory grow roughly with the number of primaries. Valkey, the Linux Foundation fork of Redis 7.2, uses the same design and protocol.

TermMeaning
Hash slotOne of 16,384 buckets a key hashes into
PrimaryA node that owns slot ranges and accepts writes for them
ReplicaA copy of one primary, ready to take over
Cluster busThe node-to-node channel for gossip, failure detection and failover
Slot mapThe client's cached table of which node owns which slots

The docs recommend at least three primaries, and in production three primaries with three replicas. This is sharding with a fixed, hash-based layout: a single-key lookup touches one node, and anything spanning many slots is up to the client.

Keys, slots and primaries4 steps
Jo: 0 to 5,4600123Sam: 5,461 to 10,9220123Priya: 10,923 to 16,3830123๐Ÿง‘โ€๐ŸซTeacher
Press play and watch it happen!

"That range is Priya's"

Teachers keep a little crib sheet in their pocket listing who looks after which stretch of pigeonholes, so they can walk straight to the right person. That crib sheet is the slot map.

A new teacher only knows where Jo sits. She asks Jo for pigeonhole 14,585. Jo doesn't fetch it for her. She says "that range is Priya's" and points. The teacher copies out the office's whole up-to-date list, then goes to Priya, and next time she goes straight there.

The slot map and MOVED

Cluster clients are "smart": at startup they connect to any seed node and fetch the topology with CLUSTER SHARDS (or the older CLUSTER SLOTS, deprecated in Redis 7.0 but still supported in Valkey), then cache it as a slot map. Each command is sent directly to the primary that owns the key's slot, in a single round trip, with no proxy.

A client that skips this, or whose map goes stale, finds out through redirects: nodes don't forward requests. If a node receives a command for a slot it doesn't own, it replies with a redirection:

1-MOVED 14585 10.0.0.3:6379

MOVED means the slot now lives permanently on that node. The client retries there and should refresh its slot map, usually by fetching the whole map again, since one change (a failover, a reshard) often moves many slots at once. A client that doesn't follow redirects isn't a cluster client: connected to one node, it gets MOVED errors for most keys.

The slot map and MOVED5 steps
๐Ÿง‘โ€๐ŸซNew teacher๐Ÿ™‹โ€โ™€๏ธJo๐Ÿง”Sam๐Ÿ‘ฉโ€๐ŸฆฑPriya
Press play and watch it happen!

A deputy for every desk

Every staff member has a deputy who copies whatever lands in their pigeonholes. The staff also keep chatting on walkie-talkies, checking that everyone is still there.

If Sam goes home ill and doesn't answer, the others notice. Once most of the staff agree Sam is really gone, Sam's deputy asks them for the go-ahead, gets it, and takes over Sam's stretch. That handover is called a failover.

There's a catch: the deputy copies a moment after Sam files something. If Sam drops out in that moment, the last item may never reach the deputy.

Replicas and automatic failover

Each primary can have one or more replicas, which replicate it asynchronously. Nodes talk over the cluster bus, a separate TCP port (by default the data port plus 10000, set with cluster-port), sending pings and gossip about the nodes they know.

If a node gets no reply from a primary for cluster-node-timeout milliseconds, it flags it PFAIL (possible failure). When a majority of primaries report it within a time window, it is marked FAIL. A replica of the failed primary then asks the other primaries for votes, wins with a majority, takes a new configEpoch and claims its primary's slots. Clients get MOVED (or refresh their map) and continue on the new primary.

Trade-offs to know:

  • Acknowledged writes can be lost. Replication is asynchronous, so a write the primary confirmed may not have reached a replica before the failover. WAIT narrows the window but doesn't make the cluster strongly consistent.
  • The minority side stops. A primary cut off from the majority for longer than the node timeout stops accepting writes.
  • A failed primary with no replica leaves a hole. By default (cluster-require-full-coverage yes) the cluster refuses queries while any slot has no working owner.

This is replication inside each shard; failover is decided by a majority of primaries, not by a separate coordinator. How each node also keeps data on disk is covered in persistence and replication, and the server itself in Redis and Valkey.

Replicas and automatic failover5 steps
๐Ÿ—ƒ๏ธ Jo's desk๐Ÿ—ƒ๏ธ Sam's desk๐Ÿ—ƒ๏ธ Priya's desk๐Ÿง‘โ€๐ŸซTeacher๐Ÿ™‹โ€โ™€๏ธJo๐Ÿง”Sam๐Ÿ‘ฉโ€๐ŸฆฑPriya๐Ÿง‘โ€๐ŸŽ“Jo's deputy๐Ÿ‘ฉโ€๐ŸŽ“Sam's deputy๐Ÿง‘โ€๐ŸŽ“Priya's deputy
Press play and watch it happen!

Moving pigeonholes to a new person

The school hires Max to share the work. Jo hands some of her pigeonholes over to Max, one item at a time, while teachers keep coming in. That's called resharding.

While one pigeonhole is half moved, Jo checks first. If the item is still with her, she hands it over. If it has already gone, she says "ask Max, just this once". The teacher goes to Max but doesn't change her crib sheet yet, because the move isn't finished. When it is, Jo says "that range is Max's now", and the crib sheet changes for good.

The pigeonholes themselves are never renumbered. Only the person looking after them changes.

Live resharding and ASK

Adding or removing a node means moving hash slots between primaries while the cluster serves traffic. In the classic, client-visible procedure (what redis-cli --cluster reshard and valkey-cli --cluster reshard drive):

  1. The target is marked CLUSTER SETSLOT <slot> IMPORTING <source>, the source MIGRATING <target>.
  2. Keys are copied over in batches with MIGRATE, which moves them atomically, one batch at a time.
  3. While the slot is migrating, the source serves keys it still has and answers -ASK <slot> <target> for keys it doesn't.
  4. Finally CLUSTER SETSLOT <slot> NODE <target> assigns the slot; from then on the source answers MOVED.

ASK is a one-off redirect: the client sends ASKING and then the command to the target, but does not update its slot map, because the next key in that slot may still be on the source. The target only serves an importing slot after ASKING. Valkey 9.0 (CLUSTER MIGRATESLOTS) and Redis 8.4 (CLUSTER MIGRATION IMPORT) added atomic slot migration, which moves whole slots server-side with less client impact. The two commands differ, so check your server's docs.

๐Ÿ”ง Going deeper

Not consistent hashing. Consistent hashing puts nodes on a ring, and a key belongs to the next node clockwise, so adding a node automatically takes keys from one neighbour. Redis Cluster instead fixes the key-to-slot function forever and keeps an explicit slot-to-node table. Nothing moves until an operator (or tool) reassigns slots, and any slots can go to any node, so you choose exactly what moves and when. The 16,384 slots act like a fixed number of pre-made virtual nodes. It also caps a cluster at 16,384 primaries; the docs suggest staying around 1,000 nodes at most.

Live resharding and ASK5 steps
Jo's pigeonhole 2,2260123๐Ÿง‘โ€๐ŸซTeacher
Press play and watch it happen!

Keeping things together

Some jobs need two items at once: "swap Ana's name card and Ana's lunch card together". Each staff member can only handle a job if every item is in the same pigeonhole. "Ana's name" and "Ana's lunch" add up to different numbers, maybe on different people's stretches, so the office refuses the job.

The fix is to put the shared part of the label in brackets: (Ana) name, (Ana) lunch. When there are brackets, the sum uses only what's inside them, so both items land in Ana's pigeonhole. That trick is called hash tags. Just don't put everyone's things under one bracket, or one person ends up with all the work.

Multi-key operations and hash tags

A command touching several keys (MSET, MGET, SUNION, RENAME, a MULTI/EXEC transaction, a Lua script or function) only runs if all its keys hash to the same slot. Otherwise the node answers CROSSSLOT. Nothing coordinates across nodes: there's no two-phase commit. Atomicity across primaries would need distributed locking and extra round trips, which the design leaves out so every command stays one fast trip to one node.

Hash tags let you choose the slot. If a key contains {, then } later, with at least one character between, only the text inside the first such pair is hashed. So {user:1}:name and {user:1}:cart both hash user:1, share a slot, and can be used together in MSET or MULTI/EXEC:

1MSET {user:1}:name Ana {user:1}:cart 3

Tag by the entity your operations group around (a user, an order, a tenant). One tag for everything puts all those keys in one slot on one node, a hotspot that also can't be split later. During a reshard, a multi-key command on a slot whose keys are split between source and target gets TRYAGAIN.

Multi-key commands and hash tags4 steps
Jo: 0 to 5,4600123Sam: 5,461 to 10,9220123Priya: 10,923 to 16,3830123๐Ÿง‘โ€๐ŸซTeacher
Press play and watch it happen!

A runner with the crib sheet

In a Java program you don't do the sums or carry the crib sheet yourself. You give your app a runner and the names of a couple of staff members. The runner fetches the full list, does the sum for every item, walks to the right person, and quietly follows "that range is Priya's" or "ask Max, just this once" for you. Every so often it also checks the list again, so it hears about changes before walking to the wrong desk.

Redis Cluster from Java

Lettuce (Spring Boot's default Redis driver) has a cluster client that computes slots, caches the topology and follows MOVED and ASK itself:

1RedisClusterClient client = RedisClusterClient.create(List.of(2        RedisURI.create("redis://10.0.0.1:6379"),3        RedisURI.create("redis://10.0.0.2:6379")));4try (StatefulRedisClusterConnection<String, String> conn = client.connect()) {5    RedisAdvancedClusterCommands<String, String> redis = conn.sync();6    redis.set("user:1:name", "Ana");          // routed to the slot owner7    redis.mset(Map.of("{user:1}:name", "Ana",8                      "{user:1}:cart", "3")); // one slot: one atomic MSET9}10client.shutdown();

With Spring Boot, listing seed nodes switches Spring Data Redis to cluster mode:

1spring:2  data:3    redis:4      cluster:5        nodes: 10.0.0.1:6379,10.0.0.2:6379,10.0.0.3:63796        max-redirects: 37      lettuce:8        cluster:9          refresh:10            period: 30s11            adaptive: true

refresh.adaptive: true makes a MOVED, ASK or reconnect trigger an immediate topology reload (it's off by default; this property is from Spring Boot 3.x, where newer versions may differ).

RedisTemplate and @Cacheable then work unchanged for single keys. Seed nodes only bootstrap discovery; the client learns the rest from the cluster. max-redirects bounds how many redirects one command may follow, and a periodic topology refresh means a failover is noticed even for slots the app hasn't touched recently. Lettuce's advanced cluster API splits a cross-slot MGET, MSET or DEL into one call per slot, which works but is no longer atomic, so keys that must change together still need a hash tag.

Lettuce in a Spring app4 steps
โ˜• Your Java app๐Ÿง‘โ€๐ŸซTeacher๐ŸƒRunner๐Ÿ™‹โ€โ™€๏ธJo๐Ÿง”Sam๐Ÿ‘ฉโ€๐ŸฆฑPriya
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Redis Cluster, told the same way as the story.
  1. A teacher asks Jo for an item in a pigeonhole that's on Priya's stretch. What does Jo do?
  2. Jo is halfway through handing pigeonhole 2,226 to Max and says "ask Max, just this once". What should the teacher do with her crib sheet?
  3. Why does the office refuse to swap Ana's name card and lunch card together when their names sum to different pigeonholes?
  4. Sam files an item, tells the teacher "done", then goes home ill before the deputy copies it. The deputy takes over. What happened to the item?
  5. The school hires a new staff member. What changes?
Answer every question to check.Passing marks Redis Cluster as done.
Got the hang of Redis Cluster? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 4 of 8

โ† Previous on the path๐Ÿงพ Redis persistence and replicationNext on the path โ†’๐Ÿ”‘ Distributed locks with Redis

๐Ÿ‘‰ Read next

  • ๐ŸชAmazon ElastiCacheHiring an agency to run your shop's express counter, staff and standby clerk included, while you choose what it stocks.