How to Implement Consistent Hashing
Distribute keys across nodes with consistent hashing: build a ring, add virtual nodes, and move only a fraction of keys when a node changes.
On this page
Introduction
Distributing keys across a set of nodes is easy until a node changes: the naive modulo maps each key to hash % N, and changing N remaps almost every key. For a cache, that means every entry is invalidated at once, and the origin is flooded. Consistent hashing solves it by mapping the keys and the nodes onto a ring, so a key belongs to the next node around it, and a change moves only the keys near the changed node.
This tutorial implements consistent hashing: build the ring, add virtual nodes for balance, move only a fraction of the keys on a change, and test the balance and the movement. The examples use a hash ring, and the technique applies wherever a key must be assigned to one of several nodes.
Map the keys and the nodes onto a ring
Hash each key and each node to a position on a ring, conceptually a circle from zero to the maximum hash. A key belongs to the first node clockwise from its position. Because the positions wrap around, the ring has no start or end, and every key has a node. Adding or removing a node changes only the mapping of the keys between it and its neighbour.
The hash function should distribute the keys and the nodes uniformly, so neither clusters. A cryptographic or a good non-cryptographic hash works; a poor one clusters and unbalances the ring. The ring is a sorted list of the node positions, and a lookup is a binary search for the key’s position and the next node, which is fast even with many nodes.
function hashKey(key) {
return createHash('sha1').update(key).digest().readUInt32BE(0); // uniform 32-bit
}
function owner(ring, key) {
const h = hashKey(key);
// the first node at or after h, wrapping to the first if none
for (const node of ring) if (node.pos >= h) return node.name;
return ring[0].name;
}
Add virtual nodes for an even distribution
A single position per node is random, so the arcs between the nodes vary in length and the keys bunch onto the nodes with the large arcs. Placing each node at several positions, the virtual nodes, breaks the large arcs into smaller ones and smooths the distribution, so each node gets a roughly equal share of the keys.
The number of virtual nodes trades the balance against the memory and the lookup cost: more virtual nodes mean a more even distribution and a larger ring. A few hundred per node is common, which brings the imbalance under a few percent. Name each virtual node with the node’s name plus an index, so the virtual positions map back to the physical node.
function buildRing(nodes, vnodes = 200) {
const ring = [];
for (const name of nodes) {
for (let i = 0; i < vnodes; i++) {
ring.push({ pos: hashKey(name + '#' + i), name }); // virtual positions
}
}
ring.sort((a, b) => a.pos - b.pos); // sorted for lookup
return ring;
}
Move only a fraction on a change
When a node joins, it takes the keys between its position and its clockwise neighbour from that neighbour, so only that arc’s keys move. When a node leaves, its keys move to its clockwise neighbour. In both cases, the keys on the other arcs do not move, so the reshuffle is a fraction of the total, roughly the share of one node.
This minimal movement is the property that protects a cache: adding a node invalidates only its share of the keys, not all of them, so the origin sees a small extra load rather than a flood. For a load balancer or a sharded store, the same property means a change is a partial migration, not a full redistribution.
# adding a node moves roughly 1/N of the keys, not all of them
# assert the fraction of keys that changed owner is close to 1/(N+1)
Replicate for availability
A single owner per key means a node’s failure loses its keys. To tolerate a failure, replicate each key to the next R nodes on the ring, so if the owner fails, a replica takes over. The replica set for a key is the owner and the next R minus one nodes, which the ring gives by walking clockwise.
The replication is the ring’s other use: the key’s preferred node is the owner for the writes and the reads, and the next nodes are the replicas for the availability. When a node fails, the replicas serve its keys, and when it recovers, the ring includes it again and the keys return. This is how a consistent-hashed system tolerates a node failure without remapping everything.
Test the balance and the minimal movement
Test that the keys are roughly even across the nodes, by hashing many keys and measuring each node’s share, and asserting the deviation is small. Test that adding a node moves only its share, by building the ring with and without a node and asserting the fraction of keys that changed owner is close to one over the count. Test that a key always maps to the same node for a stable ring, so the mapping is deterministic.
node -e '
const { buildRing, owner } = require("./ring");
const keys = Array.from({ length: 100000 }, (_, i) => "key" + i);
const before = buildRing(["a","b","c","d"]);
const after = buildRing(["a","b","c","d","e"]);
const moved = keys.filter((k) => owner(before, k) !== owner(after, k)).length;
console.log("moved fraction:", (moved / keys.length).toFixed(3)); // ~0.2 for 4 -> 5
'
Common pitfalls
Using modulo so a node change remaps every key, a single position per node so the distribution is uneven, a poor hash that clusters, too few virtual nodes so the balance is poor, and no replication so a node failure loses its keys are the recurring mistakes. A ring with virtual nodes, a uniform hash, enough virtual nodes, and a replication to the next R nodes address them.
Conclusion
Consistent hashing assigns a key to one of several nodes with minimal movement when a node changes. Map the keys and the nodes onto a ring, add virtual nodes for balance, move only the keys near the changed node, and replicate to the next R nodes for availability. Self-check by asserting the keys are roughly even and that adding a node moves only its share. Then a node change invalidates a fraction, not the whole set.
Sources: Consistent hashing (Wikipedia), Amazon Dynamo paper, Redis: Cluster and hash slots.
FAQ
- Why not modulo the number of nodes?
- Modulo maps a key to node hash % N, so changing N from four to five remaps almost every key, which invalidates every cache entry at once. Consistent hashing moves only the keys near the changed node, so the reshuffle is a fraction, not the whole set.
- What are virtual nodes for?
- A single position per node leaves the keys unevenly distributed, because the node positions are random. Placing each node at many positions, the virtual nodes, smooths the distribution so each node gets a roughly equal share. More virtual nodes mean a more even distribution.
Report a problem with this articleOpens a pre-filled issue on GitHub.