Redis Cluster and hash slots

Redis · Expert · 14 min

When one server's memory or CPU isn't enough, Redis Cluster scales out, but it changes how you design keys.

Redis Cluster splits the keyspace into 16384 hash slots. A key's slot is CRC16(key) mod 16384, and each primary node owns a subset of slots, with replicas for failover. There is no proxy: clients are cluster-aware, cache the slot map, and send each command straight to the right node.

If a client asks the wrong node, it gets -MOVED slot host:port (update your map) or, during slot migration, -ASK (retry once on the other node). Good client libraries handle both.

Multi-key commands (MGET, SINTER, transactions, Lua scripts) only work when all keys hash to the same slot; otherwise you get CROSSSLOT. Hash tags solve this: only the part inside the first {...} is hashed, so {user:42}:profile and {user:42}:cart share a slot. Use tags around the entity that operations group by, not a constant, or one slot becomes a hot spot.

Other differences from a single instance:

  • only database 0 exists,
  • failover is built in: replicas of a failed primary are promoted by majority vote of primaries,
  • resharding moves slots between nodes online (redis-cli --cluster reshard),
  • cluster-require-full-coverage decides whether the cluster stops when some slots have no live node.

Like Sentinel setups, cluster replication is asynchronous, so the same write-loss window applies.

Example

redis-cli --cluster create 10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379 \
  10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379 --cluster-replicas 1

redis-cli -c -h 10.0.0.1 CLUSTER KEYSLOT user:42          # (integer) 6929 (example)
redis-cli -c -h 10.0.0.1 CLUSTER KEYSLOT '{user:42}:cart'  # same slot as {user:42}:profile
redis-cli -c -h 10.0.0.1 MSET a 1 b 2
# (error) CROSSSLOT Keys in request don't hash to the same slot
redis-cli -c -h 10.0.0.1 MSET '{user:42}:a' 1 '{user:42}:b' 2   # OK
redis-cli -h 10.0.0.1 GET some-key-on-another-node
# (error) MOVED 12182 10.0.0.3:6379   (-c makes redis-cli follow it)
redis-cli -h 10.0.0.1 CLUSTER SHARDS        # slot ranges, primaries and replicas

Remember

  • 16384 slots; slot = CRC16(key) mod 16384; nodes own slot ranges
  • Clients follow MOVED/ASK redirections and cache the slot map
  • Multi-key operations need one slot: use {hash tags}
  • Only database 0; replication remains asynchronous

Watch out for

  • Using one constant hash tag like {app} for every key: all data lands in one slot on one node.

Check yourself

  1. Which pair of keys can be used together in one MGET on a Redis Cluster?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: redis.io/docs/latest/operate/oss_and_stack/management/scaling/

Builds on

Unlocks

Nothing builds on this yet.