Consistent Hashing: Adding and Removing Servers Without Moving Everything
Why hash mod N remaps almost every key when the server count changes, and how a hash ring with virtual nodes limits movement to about one N-th of the keys.
When data or requests are spread over several servers, something must decide which server is responsible for each key. The decision has to be deterministic, so that the same key always reaches the same server, and it should distribute keys evenly.
The obvious formula is the hash of the key modulo the number of servers. It works well until the number of servers changes. Consistent hashing is the technique that keeps the mapping stable when servers are added or removed.
The problem with hash mod N
With N servers, the formula server = hash(key) mod N distributes keys evenly and is trivial to compute. The difficulty is that the result depends on N. If a server is added or one fails, N changes, and the formula gives a different answer for most keys.
Going from 4 servers to 5, a key stays on the same server only if its hash gives the same remainder for both divisors, which is true for about one key in five. Roughly 80 percent of keys are remapped. For a cache cluster this means nearly every lookup suddenly misses and the full load falls on the database. For a sharded database it means moving almost all the data. A routine operation, adding one server, becomes a system-wide disruption.
hash(key) mod 4 mod 5 moved? ------------------------------------ 10 2 0 yes 11 3 1 yes 12 0 2 yes 13 1 3 yes 14 2 4 yes 15 3 0 yes 16 0 1 yes 17 1 2 yes 18 2 3 yes 19 3 4 yes 20 0 0 no 21 1 1 no Only hashes whose remainders happen to match stay in place: about 1 in 5. Around 80% of all keys move.
The hash ring
Consistent hashing removes N from the formula. Picture the output range of the hash function, for example 0 to 2^32 - 1, bent into a circle so that the largest value is followed by zero. This circle is the hash ring.
Each server is placed on the ring at the position given by hashing its identifier, such as its name or address. Each key is placed on the ring by hashing the key with the same function. The rule for ownership is: from the key's position, move clockwise until the first server is reached. That server owns the key. Each server is thus responsible for the arc of the ring between the previous server and itself.
0 / 2^32
|
k4 . | . S1 (pos 12)
\ /
S4 (pos 88) ------+------ k1 (pos 20)
/ \
k3 . | . S2 (pos 37)
|
S3 (pos 61)
Ownership (first server clockwise from the key):
k1 (20) -> S2 (37) k3 (70) -> S4 (88)
k2 (45) -> S3 (61) k4 (95) -> S1 (12, wraps around past zero)Adding and removing a server
Suppose a new server S5 is added at a position between S2 and S3. The only keys affected are those between S2 and S5: they used to travel clockwise to S3 and now stop at S5. Every other key still reaches the same server as before.
Suppose S2 is removed. The keys it owned continue clockwise to the next server, S3. No other keys are affected. In both cases, the keys that move are those of a single arc. With N servers, that is on average K/N of the K keys, compared with nearly all of them under hash mod N. This is the minimal possible disruption: only the data that must move to or from the changed server moves.
The problem of uneven distribution
With only one position per server, the arcs are not equal. Hash positions are effectively random, so one server may own a long arc and receive far more keys than another. Removal makes it worse: when a server leaves, its entire load is added to the next server clockwise, which may then be overloaded and fail, passing an even larger load to its neighbour. This chain reaction is a cascading failure.
Virtual nodes
The solution is to place each physical server on the ring many times. Each placement is a virtual node, created by hashing the server's name with a different suffix: S1#1, S1#2, up to S1#200. A server then owns many small arcs scattered around the ring instead of one large arc.
With a hundred or more virtual nodes per server, the total share of each server averages out and the distribution becomes close to even. When a server is removed, its many small arcs are inherited by many different servers, so the extra load is spread across the cluster and no single neighbour is overwhelmed. When a server is added, it takes a little from each existing server.
Virtual nodes also provide weighting. A machine with twice the capacity is given twice as many virtual nodes and so receives about twice the keys. This handles clusters with mixed hardware.
Implementation
The ring is stored as a sorted collection of virtual node positions, each mapped to its physical server. To find the owner of a key, hash the key and binary-search for the first position greater than or equal to it, wrapping to the first entry if none is found. A lookup costs O(log V) where V is the total number of virtual nodes, and the structure occupies a small amount of memory.
const crypto = require("crypto");
function hash(str) {
// first 4 bytes of MD5 as an unsigned 32-bit integer
return crypto.createHash("md5").update(str).digest().readUInt32BE(0);
}
class HashRing {
constructor(virtualNodes = 150) {
this.virtualNodes = virtualNodes;
this.ring = []; // sorted array of { pos, node }
}
addNode(node, weight = 1) {
for (let i = 0; i < this.virtualNodes * weight; i++) {
this.ring.push({ pos: hash(node + "#" + i), node });
}
this.ring.sort((a, b) => a.pos - b.pos);
}
removeNode(node) {
this.ring = this.ring.filter((entry) => entry.node !== node);
}
getNode(key) {
if (this.ring.length === 0) return null;
const h = hash(key);
let lo = 0, hi = this.ring.length; // binary search: first pos >= h
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.ring[mid].pos < h) lo = mid + 1; else hi = mid;
}
return this.ring[lo % this.ring.length].node; // wrap around the ring
}
}
const ring = new HashRing();
["cache-a", "cache-b", "cache-c"].forEach((n) => ring.addNode(n));
ring.getNode("user:42"); // always the same node until the ring changesReplication on the ring
The ring also gives a simple rule for placing replicas. To store R copies of a key, continue clockwise from the key's position and choose the next R distinct physical servers, skipping virtual nodes that belong to a server already selected. This ordered list of servers is sometimes called the preference list. If the first server is down, the request goes to the next one in the list.
Where it is used
- Distributed caches: client libraries choose the cache node for a key, so that adding or losing a node invalidates only a fraction of the cache.
- Distributed databases in the Dynamo family, such as Cassandra and DynamoDB, partition and replicate data around a ring.
- Load balancers: route a given user or session to the same backend, with minimal reassignment when backends change.
- CDNs and object stores: decide which server holds which object.
- Sharded services in general, whenever the set of shards is expected to change.
Limitations and alternatives
- Consistent hashing balances the number of keys, not the traffic. A single extremely popular key still lands on one server and must be handled separately, for example by replication or caching.
- When a node joins, the affected data still has to be copied to it, and this must be done without disrupting service.
- All clients must share the same view of the ring; membership is distributed by a coordination service or a gossip protocol.
- Fixed hash slots are a related approach: Redis Cluster divides the key space into 16,384 slots and assigns slots to nodes, moving slots when the cluster changes.
- Rendezvous hashing and jump consistent hashing achieve similar goals with different trade-offs.
Interview summary
- hash(key) mod N remaps almost all keys when N changes.
- Consistent hashing places servers and keys on a ring; a key belongs to the first server clockwise.
- Adding or removing a server moves only about K/N keys.
- Virtual nodes even out the distribution, spread load on failure and allow weighting.
- Used in distributed caches, Dynamo-style databases and load balancers.
Summary
Modulo hashing ties every key's location to the number of servers, so any change in that number moves nearly everything. Consistent hashing maps servers and keys onto a ring, which confines the effect of a change to one arc and about one N-th of the keys. Virtual nodes make the distribution even and prevent a failed server's load from falling on a single neighbour.
Puneet Tiwari
Full Stack Developer
