Video in progress
How are keys distributed across nodes in Redis Cluster, and what limits does that put on multi-key operations?
There are 16384 hash slots, and a key's slot is CRC16(key) mod 16384. Each node owns a subset of slots. All the keys in one command or Lua script must be in the same slot. You force that with a {...} hash tag, but if you overuse it you get a hot shard.
📖 Answer
The client computes the key's slot itself and goes straight to the right node. If its topology is stale, the node returns MOVED 3999 10.0.0.5:6379 and the client updates its map.
The problem is when keys are in different slots:
MGET user:1 user:2
(error) CROSSSLOT Keys in request don't hash to the same slot
The same restriction applies to MGET/MSET, SUNION, RENAME, keys inside MULTI, and Lua scripts.
Hash tag: only the part of the key between { and } is hashed.
SET {cart:42}:items ...
SET {cart:42}:total ...
-- both are in the same slot, so MULTI and Lua work
How I decide in the design:
- Keys that must change together atomically go under one tag, for example per user or per order. The tag should be fine-grained enough.
- Never use a large group like
{global}or{tenant}as a tag: the entire load lands on one slot and the cluster loses its point. - If you need a cross-slot
MGETto read many keys, many clients (Lettuce) group it by slot and send the parts in parallel: not atomic, but fast.
Another difference: a cluster has only db 0, and SELECT doesn't work. When moving from standalone to a cluster, the places in the code that use SELECT 3 are the first to break.
Sign up to mark studied questions and save your progress.