Who should use Redis Cluster hash tags?
Hash tags matter to anyone whose application runs against Redis Cluster and needs more than one key in a single operation. That usually means one of these groups:
- Application engineers whose code uses
MGET,MSET, multi-keyDEL, set or sorted-set store operations,RENAME,MULTI/EXEC, or Lua scripts and functions against a cluster. - Teams moving from a standalone or Sentinel deployment to Cluster. On a single instance every multi-key command works. After the move, any command whose keys hash to different slots fails with
CROSSSLOT. Hash tags are the main way to keep that code working without rewriting it as fan-out logic. - Platform and SRE engineers who own key naming conventions, capacity planning and resharding. A tag decides which data must live on one shard, so it affects hot spots and migration cost as much as it affects correctness.
- Library and framework authors who build queues, rate limiters, locks or caches on Redis and want them to work in cluster mode.
If your workload only issues single-key commands, you do not need hash tags. They add a placement constraint and give you nothing in return. Outside cluster mode the braces are ordinary characters in the key name. Adopting a tagged naming scheme before a move to Cluster is harmless and can make the later move easier.
How does Redis Cluster map keys to hash slots?
Redis Cluster does not assign keys directly to nodes. It divides the keyspace into exactly 16,384 hash slots, and every key belongs to one slot:
slot = CRC16(key) mod 16384
The hash is the CRC16 XMODEM variant computed over the key name. The modulo is equivalent to masking the low 14 bits. The result depends only on the key, never on the cluster's size or topology, so a given key always lands in the same slot. (Hash tags, covered later, change which part of the key gets hashed but not the formula.)
Each slot is owned by exactly one primary at any moment. Replicas hold copies of their primary's slots. A three-primary cluster might split the range into roughly 0–5460, 5461–10922 and 10923–16383, but any assignment is valid, including uneven ones.
The fixed slot count is what makes resharding manageable. Adding or removing a node means moving whole slots between primaries, not rehashing every key. The topology also stays compact: a node's ownership is a 16,384-bit bitmap (2 KB), small enough to exchange in cluster gossip.
Clients route by slot for the same reason. A cluster-aware client fetches the slot-to-node map once, computes the slot locally for each command and sends the command straight to the owning primary. If the map is stale, the node replies with a MOVED redirection (or ASK during a slot migration), and the client refreshes its cache.
To check where a key lands, run CLUSTER KEYSLOT <key>. It returns the slot number without touching any data.
def crc16_xmodem(data: bytes) -> int:
crc = 0x0000
for byte in data:
crc ^= byte << 8
for _ in range(8):
if crc & 0x8000:
crc = ((crc << 1) ^ 0x1021) & 0xFFFF
else:
crc = (crc << 1) & 0xFFFF
return crc
def key_slot(key: str) -> int:
# 16384 = 2**14, so the modulo is the same as keeping the low 14 bits.
# Hash tags ({...}) are ignored here; they only change which bytes get hashed.
return crc16_xmodem(key.encode()) & 0x3FFF
assert crc16_xmodem(b"123456789") == 0x31C3
for key in ["somekey", "user:1000", "user:1001"]:
print(f"{key!r} -> slot {key_slot(key)}")
A minimal Python implementation of slot = CRC16(key) mod 16384, which you can check against CLUSTER KEYSLOT on a live cluster node.
Which multi-key commands trigger a CROSSSLOT error?
Any command that names more than one key must have all of those keys in the same slot. If they hash to different slots, the node rejects the command with a CROSSSLOT Keys in request don't hash to the same slot error. This happens even when every slot involved is served by the node you are connected to. The rule is about slots, not nodes, because slots move independently during resharding or failover. An operation that worked because two slots happened to share a node would start failing, or lose atomicity, as soon as one of them migrated. Checking slots makes the result independent of the current topology.
| Operation | Keys that must share a slot |
|---|---|
MGET, MSET, MSETNX |
Every key in the call |
Multi-key DEL, UNLINK, EXISTS |
Every key in the call |
SUNIONSTORE, SINTERSTORE, SDIFFSTORE, ZUNIONSTORE, ZINTERSTORE |
All source keys and the destination key |
SMOVE, LMOVE, RPOPLPUSH |
Source and destination |
RENAME, RENAMENX |
Old name and new name |
MULTI/EXEC |
Every key touched in the transaction |
| Lua scripts and functions | Every key passed in KEYS, and every key the script actually accesses |
Clients do not all handle this the same way. Some cluster-aware clients split MGET, MSET or DEL by slot, send the pieces to the owning nodes, and merge the replies. That avoids the error, but the result is no longer atomic. Other clients send the command unchanged and pass the CROSSSLOT error back to your code. Transactions and scripts are almost never split, because splitting them would break their guarantees. Check how your client library behaves before you rely on either outcome.
redis-cli -c -p 7000 CLUSTER KEYSLOT user:1000:profile
redis-cli -c -p 7000 CLUSTER KEYSLOT user:1000:settings
redis-cli -c -p 7000 MSET user:1000:profile '{"name":"Ada"}' user:1000:settings '{"theme":"dark"}'
redis-cli -c -p 7000 CLUSTER KEYSLOT '{user:1000}:profile'
redis-cli -c -p 7000 CLUSTER KEYSLOT '{user:1000}:settings' # same number as above
redis-cli -c -p 7000 MSET '{user:1000}:profile' '{"name":"Ada"}' '{user:1000}:settings' '{"theme":"dark"}'
redis-cli -c -p 7000 MGET '{user:1000}:profile' '{user:1000}:settings'
redis-cli -c -p 7000 RENAME '{user:1000}:settings' '{user:1000}:settings:old'
redis-cli -c -p 7000 EVAL "return redis.call('EXISTS', KEYS[1], KEYS[2])" 2 \
'{user:1000}:profile' '{user:1000}:settings:old'
redis-cli -c -p 7000 DEL '{user:1000}:profile' '{user:1000}:settings:old'
Using redis-cli against a cluster, MSET on untagged keys in different slots returns CROSSSLOT, while keys sharing the hash tag {user:1000} map to one slot and work with MSET, MGET, RENAME, EVAL and DEL.
How do Redis Cluster hash tags work?
The fix for CROSSSLOT is not to force keys into one slot after the fact. The fix is to decide which keys belong together when you design them, and hash tags are how you express that decision.
The rule is narrow. If a key contains a {, and a } appears somewhere after that first {, and at least one character sits between them, Redis hashes only that substring. If any of these conditions fails, Redis hashes the whole key. Redis does not look past the first { or the first } that follows it. It never searches for a "better" pair.
You can check where any key lands with CLUSTER KEYSLOT <key>. Compare tagged keys against the key that should share their slot, not against a slot number you remember.
| Key | Hashed substring | Why |
|---|---|---|
{user:42}:cart |
user:42 |
Standard tag at the start |
user:{42}:cart |
42 |
The tag can appear anywhere in the key |
{}user |
{}user (whole key) |
The braces are empty, so the tag is ignored |
{{a}} |
{a |
Hashing starts after the first { and stops at the first } |
{a}{b} |
a |
Only the first pair counts |
x{}{b} |
x{}{b} (whole key) |
The first pair is empty, and later pairs are never considered |
The last row is the trap. A prefix that sometimes produces {} silently disables every tag after it.
A tag also defines a unit of locality. Every key that shares a tag lives on one shard, and it moves with that shard during resharding. Choose tags the way you would choose a partition key: by which data your application needs to read and write atomically together.
#!/usr/bin/env bash
set -euo pipefail
HOST="${REDIS_HOST:-127.0.0.1}"
PORT="${REDIS_PORT:-7000}"
slot() { redis-cli -h "$HOST" -p "$PORT" CLUSTER KEYSLOT "$1"; }
same() {
local key="$1" ref="$2"
local a b
a=$(slot "$key"); b=$(slot "$ref")
if [ "$a" = "$b" ]; then verdict="same slot"; else verdict="DIFFERENT"; fi
printf '%-16s slot %-5s | %-10s slot %-5s | %s\n' "$key" "$a" "$ref" "$b" "$verdict"
}
same '{user:42}:cart' 'user:42' # tag at the start
same 'user:{42}:cart' '42' # tag anywhere in the key
same '{{a}}' '{a' # hash from first '{' to first '}' after it
same '{a}{b}' 'a' # only the first pair counts
printf '%-16s slot %s (whole key hashed)\n' '{}user' "$(slot '{}user')"
printf '%-16s slot %s (whole key hashed)\n' 'x{}{b}' "$(slot 'x{}{b}')"
same '{order:9001}:items' '{order:9001}:status'
A redis-cli script that uses CLUSTER KEYSLOT to confirm which substring Redis hashes for each edge-case key. It compares each tagged key against the expected reference string instead of a slot number you would have to remember.
How does it work end to end? The path of a multi-key command
The pieces above combine into one request path. Take MSET '{user:1000}:profile' ... '{user:1000}:settings' ... sent through a cluster-aware client:
- The client extracts the tag and computes the slot. For each key it applies the brace rule, hashes
user:1000with CRC16 XMODEM, and takes the result mod 16384. Both keys produce the same slot. - The client picks the owning primary from its cached slot map and sends the command there. Clients that split multi-key commands by slot find only one group here, so they send the command as a single unit.
- The node checks the keys. It confirms that every key in the command maps to one slot, and replies
CROSSSLOTif they do not. It then confirms that it owns that slot. If it does not, it repliesMOVEDwith the correct node, and the client retries and refreshes its map. - During a slot migration, the source node may reply
ASK, sending the client to the target node for that one request. If a multi-key command arrives while its keys are split between the source and target nodes, Redis returns aTRYAGAINerror rather than running it on a partial set of keys. The client should retry after a short delay. - The primary executes the command atomically. All keys are local, so no other command interleaves with it, and that holds for
MULTI/EXECblocks and scripts as well. Replication to the primary's replicas is asynchronous, as it is for single-key writes.
The tag never changes how the node executes a command. It only guarantees that step 3 passes, because the keys were placed together when they were named.
How should you choose a hash tag boundary?
Start from the unit of atomicity: the smallest entity whose keys must change together or be read consistently. For an order, that is the order itself. {order:981}:items and {order:981}:status hash only order:981, so both keys land in the same slot. A MULTI/EXEC that updates status and items can then run without a CROSSSLOT error. Order 982 hashes to a different slot, so the keyspace still spreads across the cluster.
Compare {orders}:981. Every order key hashes the literal string orders, so one slot and one shard hold the entire order keyspace. That shard takes all the memory, all the traffic, and all the failover risk. Adding nodes does nothing for it, because a single slot cannot be split.
| Tag width | Example | Benefit | Cost |
|---|---|---|---|
| Narrow (per entity) | {order:981}:status |
Even distribution, small slots | Cross-entity operations need client-side fan-out |
| Wide (per tenant) | {tenant:42}:session:7 |
Atomic operations across a tenant's data | Large tenants create hot or oversized slots |
| Global | {orders}:981 |
Any multi-key command works | Cluster behaves like one node |
Use tags only when correctness depends on multi-key atomicity. If you just want related keys grouped together, that convenience does not justify a hot slot.
Scripts and functions need extra discipline:
- Pass every key through
KEYS. Cluster routing readsKEYSand nothing else. - Never build key names inside the script.
- Keep all declared keys on one tag.
A script that builds "order:" .. id at runtime works on a single node, where every key is local, and passes tests there. In cluster mode the same script fails as soon as a computed key belongs to another shard.
CLI="redis-cli -c -p 7000"
$CLI CLUSTER KEYSLOT '{order:981}:items'
$CLI CLUSTER KEYSLOT '{order:981}:status'
$CLI CLUSTER KEYSLOT '{order:982}:status'
$CLI CLUSTER KEYSLOT '{orders}:981'
$CLI CLUSTER KEYSLOT '{orders}:982'
$CLI EVAL "
redis.call('HSET', KEYS[1], 'state', ARGV[1])
redis.call('RPUSH', KEYS[2], ARGV[2])
return 1
" 2 '{order:981}:status' '{order:981}:items' shipped 'sku-1234'
$CLI EVAL "
local other = '{order:' .. ARGV[1] .. '}:status'
return redis.call('HGET', other, 'state')
" 1 '{order:981}:status' 982
CLUSTER KEYSLOT shows that per-entity tags keep one order's keys in a single slot while a global tag puts every order in the same slot, and the two EVAL calls contrast a cluster-safe script that declares all keys in KEYS with one that builds a key name at runtime.
When should you avoid hash tags, and what are the alternatives?
Hash tags are the wrong tool when the tagged entity is large or busy. Every key sharing a tag lands in one slot, and a slot is never split across nodes, so a popular tenant, a viral product, or a {global} tag pins its whole workload to one primary. Adding nodes does not help, because resharding moves the slot as a unit. Watch especially for keyspaces where one tag would carry most of the traffic. In that case the cluster behaves like a single node with extra network hops.
When you need to spread load, choose one of these alternatives based on how much atomicity you actually need:
| Approach | Atomic across keys | Load spread | Main cost |
|---|---|---|---|
| Per-slot batches, pipelined per node | Only within each batch | Yes | Client groups keys by slot and handles partial failure |
| Idempotent per-key writes | No | Yes | Readers must tolerate intermediate states; retries must be safe |
| Single hash or sorted set | Yes, one key | No | One large key on one node |
Client-side MGET fan-out, where a cluster-aware client splits the call by slot, is not atomic. Each node answers at a different moment, so a concurrent writer can leave you with a mix of old and new values.
Collapsing data into one hash or sorted set avoids CROSSSLOT entirely, but it creates a big key with its own costs:
- Delete: freeing all its memory takes noticeable time.
- Migrate: it moves in one piece during resharding, which can stall that slot's migration.
- Expire: a TTL applies to the whole key. Whether you can set a TTL on individual hash fields depends on the server version you run.
How do you detect hot slots and oversized tags in an existing cluster?
CLUSTER COUNTKEYSINSLOT returns the key count for one slot, but only on the node that owns it. A slot holding far more keys than its peers is the first sign of an oversized tag. Key count alone misses large values, so sample as well: run SCAN with a modest COUNT, map each key to its slot with CLUSTER KEYSLOT, and call MEMORY USAGE on suspicious keys. Pass SAMPLES to MEMORY USAGE when a collection is large, because the default estimate samples only some of its elements.
SCAN, keyspace notifications, and most admin commands operate on a single node. They do not fan out across the cluster. Tooling must list the primaries from CLUSTER NODES or CLUSTER SHARDS and run against each one, or it will report on a fraction of the keyspace. For the same reason, alert on per-node CPU, memory, and network throughput. A cluster-wide average of 30% CPU can hide one primary pinned at 100%.
Illustrative estimate
Assumed inputs: 100,000 tenants, uneven traffic, and a largest tenant that produces 8% of all requests. Sessions spread each tenant across many small tags.
| Primaries | Tag per tenant: busiest node | Tag per tenant-session: busiest node |
|---|---|---|
| 10 | ≈ 8% + 92%/10 ≈ 17% | ≈ 10% |
| 40 | ≈ 8% + 92%/40 ≈ 10% | ≈ 2.5% |
| 100 | ≈ 8% + 92%/100 ≈ 9% | ≈ 1% |
With one tag per tenant, a single node always carries at least 8% of total load, no matter how many nodes you add. With one tag per tenant-session, the load per node keeps falling as nodes are added.
What does changing hash tag design cost, and how can you migrate safely?
A hash tag is part of the key name, so changing the tag design means renaming keys. You cannot do this with RENAME, because the old and new names usually hash to different slots, and that returns the same CROSSSLOT error you were trying to avoid. You have to copy the data at the application level, using one of three approaches:
- Dual-write: write to both the old and new keys until a backfill job finishes.
- Read-new, fall back to old: read the new key first and fall back to the old key if it is missing. Old keys drain as they are touched or as their TTLs expire.
- Planned cutover: for data that cannot tolerate either of the above, cut over in a maintenance window.
All three add code paths, metrics and a cleanup step. Teams often forget the cleanup.
Adding nodes does not fix an oversized tag either. Resharding moves whole slots, so every key that shares a tag stays on one node. Moving that slot is also expensive. Keys migrate one at a time while clients follow ASK redirects, and a single large key can block the source node while it is serialized. A slot that carries a big share of your traffic is the slowest one to move and the most painful when it stalls.
Choosing the atomicity unit correctly before launch avoids most of this work. You write fewer migration jobs, you see no CROSSSLOT surprises after a refactor, and you do not need custom fan-out code to compensate for keys that should have been colocated.
Pre-launch key design checklist
- Which keys must change together atomically? The tag should cover exactly that set, and nothing more.
- What is the largest tenant, user or entity you expect, and can its tagged keys fit comfortably on one node?
- Does any single tag carry a large share of total requests?
- Have you run every multi-key command, transaction and Lua script against a real cluster, not a single instance?
- Is the tag format documented so that new key types follow it?
- If you had to change this design, would the migration path be dual-write or read-fallback?
How can hash tag design save engineering time?
Most of the time spent on hash tags goes into getting them wrong and then repairing the damage. A deliberate design avoids several specific kinds of work:
- No fan-out and partial-failure code. When the keys of one entity share a tag,
MGET,MSET, transactions and scripts run as single commands. You do not have to write, test and maintain logic that groups keys by slot, sends batches to several nodes, merges replies, and decides what to do when one batch fails and another succeeds. - No compensating logic for lost atomicity. Code that was atomic on one node stays atomic in the cluster. You avoid adding reconciliation jobs, version checks or idempotency layers just to cover writes that a client split across nodes.
- Fewer production-only failures.
CROSSSLOTerrors and scripts that compute key names often pass on a single-instance test setup and fail only in cluster mode. Two cheap habits catch these before release. Run integration tests against a small local cluster, and add a test that compares the slot of every key a multi-key operation uses. That test can callCLUSTER KEYSLOTor a local CRC16 function like the one earlier in this article. Either way, the failure shows up as a failing test, not as an incident. - Fewer key migrations. Renaming keys across slots requires dual-write or read-fallback code, a backfill, monitoring and cleanup. If the atomicity unit is chosen correctly up front, you usually skip that project entirely.
- Shorter hot-spot investigations. A documented tag format tells on-call engineers which entity a hot slot belongs to. That is quicker than reverse-engineering slot ownership from sampled keys under pressure.
- Scaling without redesign. Narrow, per-entity tags spread load as you add primaries. You can handle capacity problems by resharding, without also changing how the application names its keys.
The up-front cost is small: a design review of the key format, a slot-equality test in CI, and one documented rule for which keys share a tag. It is far cheaper than any of the remediation work listed above.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to redis cluster hash tags, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Adding or removing a column goes through one review with the inheriting services listed, instead of ad-hoc messages to each team.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Services that depend on a column get the chance to object before it disappears, avoiding emergency fixes.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.