Sub topic 13
Consistent hashing in practice
This chapter covers what changes when a consistent hash ring runs in a production system. It assumes you have read the earlier chapters: you know the hash ring, virtual nodes, and the replica walk. You should also be comfortable with caches, shards, and replicas, and with reading short Python programs.
Where you will meet it
Most systems that use consistent hashing do not use the textbook ring unchanged. The table lists common uses and the variation each one applies.
| System | What it distributes | Variation |
|---|---|---|
| Dynamo-style stores (Dynamo paper, Cassandra) | Data partitions across storage nodes | Each node owns many tokens (virtual nodes). Replicas are the next distinct nodes clockwise. |
| Memcached client libraries (ketama-style) | Cache keys across cache servers | The ring lives in each client. Servers know nothing about it. |
| Redis Cluster | Keys across shards | Fixed hash slots (16384) instead of a free-form ring. A table maps each slot to a node. |
| Riak | Data partitions across nodes | A ring split into a fixed number of equal partitions that nodes claim. |
| Load balancers (Envoy ring hash) | Requests across backends | The request's session ID or header is the key, so the same client keeps reaching the same backend. |
Two broad patterns appear here. Some systems keep the ring and give each node many positions on it. Others fix the number of partitions in advance and only change which node owns which partition. The second pattern is common in storage systems because it makes data movement predictable.
Fixed slots: consistent hashing without a ring
A fixed-slot design hashes a key to one of a constant number of slots, then looks the slot up in a table. The key-to-slot step never changes. Only the table changes when the cluster does.
import hashlib
from collections import Counter
SLOTS = 1024
def slot_of(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16) % SLOTS
def build_table(nodes):
return [nodes[s % len(nodes)] for s in range(SLOTS)]
def add_node(table, new_node):
counts = Counter(table)
target = SLOTS // (len(counts) + 1)
table = list(table)
taken = 0
for s in range(SLOTS):
if taken >= target:
break
owner = table[s]
if counts[owner] > target:
table[s] = new_node
counts[owner] -= 1
taken += 1
return table
keys = [f"key{i}" for i in range(10000)]
before = build_table(["a", "b", "c", "d"])
after = add_node(before, "e")
moved = [k for k in keys if before[slot_of(k)] != after[slot_of(k)]]
print(len(moved) / len(keys))
print(all(after[slot_of(k)] == "e" for k in moved))The first line prints about 0.2, and the second prints True. As on the ring, roughly one fifth of the keys move, and all of them move to the new node.
Fixed slots have three practical advantages:
- Slot ownership is explicit data. You can inspect it, store it, and send it to clients as a small table.
- Moving a slot is a well-defined unit of work. Systems can migrate one slot at a time and track progress.
- Lookup is one array access, with no binary search.
The cost is a hard ceiling. You cannot have more nodes than slots, and with few slots per node the balance gets coarse. 16384 slots is far above realistic Redis Cluster sizes.
Choosing the number of virtual nodes
More virtual nodes smooth the load but cost memory and lookup work. This script measures the effect on a 10-node cluster.
import bisect
import hashlib
from collections import Counter
def _hash(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
def build(nodes, vnodes):
points = sorted((_hash(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
return [p[0] for p in points], [p[1] for p in points]
def owner(ring, key):
hashes, owners = ring
return owners[bisect.bisect_right(hashes, _hash(key)) % len(hashes)]
nodes = [f"n{i}" for i in range(10)]
keys = [f"key{i}" for i in range(50000)]
mean = len(keys) / len(nodes)
for vnodes in (1, 10, 100, 500):
ring = build(nodes, vnodes)
load = Counter(owner(ring, k) for k in keys)
heaviest = max(load.values()) / mean
lightest = min(load.get(n, 0) for n in nodes) / mean
print(vnodes, round(heaviest, 2), round(lightest, 2))Each output row shows the vnode count, then the heaviest and lightest node's load as a multiple of the mean. With 1 vnode per node, the heaviest node typically carries well over the mean and the lightest far under it. By 100 vnodes, the spread is typically within a few tens of percent. The spread shrinks roughly with the square root of the vnode count, so each extra step of smoothness costs more than the last. Exact numbers depend on the hash function and the keys.
The costs of high vnode counts are real:
- Memory and lookup time. The ring holds
nodes × vnodesentries. Binary search grows only logarithmically, but rebuilding the sorted structure on each membership change does not. - Repair and streaming overhead. One node's data is spread across many small ranges, so a node join or failure involves many peers and many small transfers.
- Replica correlation. Each of a node's vnodes has different neighbors, so one failed node shares replica sets with many others. This can reduce how many simultaneous failures the cluster survives without losing all replicas of some range.
This is why Cassandra lowered its default token count from 256 to 16 in version 4.0, with better token allocation to compensate. Treat the vnode count as a tuning knob and measure the result.
Everyone must agree on the ring
The ring only works if every participant computes the same answer for the same key. That depends on several details that are easy to get wrong:
- Same hash function and encoding. Two clients that hash
"user:42"differently (one UTF-8, one UTF-16, or MD5 in one place and Murmur in another) will route to different nodes. Fix the algorithm and the byte encoding and treat them as part of the protocol. - Same vnode labels. The earlier examples hash
f"{node}#{i}". If a client library formats these strings differently, its ring differs. - Don't use language-default hashes. Python's built-in
hash()for strings is randomized per process. Java'shashCode()is stable but weak. Use a defined, stable function. - Same membership view. If one client thinks node
eis in the ring and another doesn't, they send the same key to different places. In a cache, this causes extra misses. In a store that accepts writes, it can cause lost or stale data.
Real systems handle membership in two ways. Some use a central source such as a configuration service or load balancer control plane, so all clients receive the same list. Others, like Dynamo-style stores, use gossip, where nodes exchange membership info and converge over a short time. Convergence is not instant, and during the gap different nodes can disagree on ownership. Systems that care about correctness add versioned ring state, quorums, or forwarding. A request that reaches the wrong node is forwarded to the right one.
Failure versus removal
A node being unreachable is not the same as the node leaving the ring. The choice has large consequences.
If you remove a node at the first failed health check, a brief network blip causes a wave of key movement. Cache clients see misses on all of that node's keys. Storage clusters start streaming data they will have to move back minutes later. If you never remove failed nodes, you keep sending traffic to a dead server. Typical systems wait a threshold period, use a failure detector with several confirmations, or leave removal to an operator.
For a cache, removal has a specific danger. When a node is removed, its keys all go to its clockwise successors, so those nodes suddenly receive extra traffic and a burst of cache misses. Those misses go to the database at once. This is a thundering herd. Mitigations include request coalescing (only one request per key goes to the backend), staggered TTLs, and keeping enough capacity headroom on every node.
Data movement on join
On the ring, adding a node moves about 1/N of the keys. The ring tells you which keys move but not how to move them. In a cache you can ignore the transfer: the new node starts empty and fills on demand, so it gets misses until it is warm. In a database you must stream the data before the node takes over reads, or reads for those keys will miss existing data.
A common safe sequence is:
- The new node announces itself and receives its ring positions as pending.
- Current owners stream the affected ranges to it while still serving traffic.
- Writes during the transfer go to both old and new owners.
- When streaming finishes, the new node is marked active and the old owners drop the ranges.
Skipping any of these steps is a common cause of data loss during scaling. Adding several nodes at the same time multiplies the streaming load, so many operators add one node at a time.
Hot keys and bounded loads
Consistent hashing balances keys, not requests. If one key receives 30% of traffic, it lands on one node (plus its replicas), whatever the vnode count. Vnodes cannot fix this. Typical remedies are caching hot keys in front of the ring, splitting a hot key into several sub-keys (key#0 through key#7) and combining results, or reading from replicas.
For load balancers, there is a variant called consistent hashing with bounded loads. It sets a cap on how many requests each backend may hold, usually a small multiple of the average. If the key's owner is over the cap, the request goes to the next node clockwise. Most requests keep their usual home, and overloaded nodes shed the excess. It trades some key stability for a hard ceiling on imbalance.
Choosing an approach
| Situation | A good fit |
|---|---|
| Client-side routing to caches, membership changes often | Ring with 100 to 200 vnodes per node |
| Stateful store with explicit data migration | Fixed slots or a token ring with moderate vnodes |
| Small, fixed group of backends, simple code | Rendezvous hashing |
| Backends numbered 0 to N-1 that only grow at the end | Jump consistent hash |
| Load balancer with strict capacity limits | Ring with bounded loads |
Checklist before shipping
- The hash function, key encoding, and vnode label format are fixed and documented.
- Every client and node receives ring updates from one source or converges through a defined protocol.
- A failure policy states when a node leaves the ring and who decides.
- You measure per-node load, and alert when the heaviest node exceeds a set multiple of the mean.
- You have tested adding and removing a node under load, including the cache-miss spike.
- Hot keys have a plan.
Exercise
A team runs 8 cache nodes on a ring with 100 vnodes each. A node's health check fails for 20 seconds because of a network blip, and an automation script immediately removes the node from the ring. Name two problems this causes and one policy change that avoids them.
Show answer
First, all keys owned by that node are remapped to their clockwise successors, so clients see cache misses for that whole range and send a burst of requests to the database. Second, the successor nodes receive extra traffic, and when the node returns and is added back, the keys move again, causing a second wave of misses. A policy change that avoids this is to keep the node in the ring until a failure detector has confirmed the outage for a set period (or an operator removes it), and meanwhile serve from replicas or fall back to the database with request coalescing.
Exercise
In the fixed-slot example, SLOTS is 1024. What goes wrong if you build a cluster of 2000 nodes with this design, and what is the simplest fix?
Show answer
There are fewer slots than nodes, so at least 976 nodes could own no slot and receive no keys. Even with 1024 or fewer nodes, one slot per node gives very coarse balance and no room to move small amounts of load. The simplest fix is to choose a much larger slot count when designing the system (Redis Cluster uses 16384), so each node owns many slots and the count never has to change.