MGET user:1 user:2
(error) CROSSSLOT Keys in request don't hash to the same slot
MGET {user:1}:profile {user:1}:settings
1) "..."
2) "..."
MGET user:1 user:2 fails because the two keys can live in different slots, and Redis Cluster runs a multi-key command only when all keys are in one slot.
In Cluster, each key maps to one of 16,384 slots. Each node holds only some of the slots. These must touch keys in a single slot:
- multi-key commands such as
MGETandSUNION - transactions
- Lua scripts
If the keys are in different slots, Redis returns a CROSSSLOT error.
A hash tag forces keys into the same slot. If a key contains {...}, Redis hashes only the text inside the first pair of braces. So {user:1}:profile and {user:1}:settings share a slot. You can use them together in one command, transaction or script.
Put the tag around a natural group, such as a user ID or tenant ID. Do not put one constant tag on every key. All those keys would land on one node, and you lose the point of sharding. For unrelated keys, let the client split the request into one request per slot instead.
- Multi-key operations need all their keys in one slot.
- If the keys are in different slots, Redis returns a CROSSSLOT error.
- Redis hashes only the text inside the first
{}of a key. - Group keys by a natural ID, like a user ID or tenant ID.
- Avoid one shared tag for everything, because it creates a hot node.