Consistent Hashing
Why hash mod N breaks when servers change, the hash ring, virtual nodes, replication on the ring, rendezvous hashing, and where consistent hashing is used.
To spread keys across N servers, the obvious approach is server = hash(key) mod N. It balances well — until N changes. Add one server to a 4-node cache and almost every key maps somewhere new: about 80% of the cache misses at once, and the database behind it gets flattened. Consistent hashing fixes this.
The problem with mod N
| key hash | mod 4 | mod 5 |
|---|---|---|
| 10 | 2 | 0 |
| 11 | 3 | 1 |
| 12 | 0 | 2 |
| 13 | 1 | 3 |
| 14 | 2 | 4 |
| 15 | 3 | 0 |
Every key moved. In general, going from N to N + 1 servers remaps about N/(N+1) of the keys.
The hash ring
- Imagine the hash space (say 0 to 2³² − 1) bent into a ring.
- Hash each server onto the ring (e.g.
hash("cache-a")). - Hash each key onto the ring; it belongs to the first server clockwise from it.
- Adding a server takes over only the keys between it and its counter-clockwise neighbour. Removing one hands its keys to its clockwise neighbour.
Only about 1/N of the keys move when a server joins or leaves.
Virtual nodes
With few servers, random positions leave uneven arcs: one server might own 50% of the ring. Virtual nodes fix this: each physical server is placed at many points (100–200, e.g. hash("cache-a#17")).
- Load evens out statistically.
- When a server leaves, its load spreads across many servers instead of dumping everything on one neighbour.
- Give bigger machines more virtual nodes for weighted capacity.
class ConsistentHash<T> {
private final TreeMap<Long, T> ring = new TreeMap<>();
private final int vnodes;
ConsistentHash(int vnodes) { this.vnodes = vnodes; }
void add(T node) {
for (int i = 0; i < vnodes; i++) ring.put(hash(node + "#" + i), node);
}
void remove(T node) {
for (int i = 0; i < vnodes; i++) ring.remove(hash(node + "#" + i));
}
T get(String key) {
if (ring.isEmpty()) return null;
Map.Entry<Long, T> e = ring.ceilingEntry(hash(key)); // first clockwise
return (e != null ? e : ring.firstEntry()).getValue(); // wrap around
}
private long hash(String s) { // use a good hash (Murmur3, xxHash)
return Integer.toUnsignedLong(Hashing.murmur3_32_fixed().hashUnencodedChars(s).asInt());
}
}import bisect, hashlib
class ConsistentHash:
def __init__(self, vnodes=150):
self.vnodes, self.keys, self.ring = vnodes, [], {}
def _hash(self, s: str) -> int:
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
def add(self, node: str):
for i in range(self.vnodes):
h = self._hash(f"{node}#{i}")
self.ring[h] = node
bisect.insort(self.keys, h)
def remove(self, node: str):
for i in range(self.vnodes):
h = self._hash(f"{node}#{i}")
del self.ring[h]
self.keys.remove(h)
def get(self, key: str) -> str:
i = bisect.bisect(self.keys, self._hash(key)) % len(self.keys) # wrap around
return self.ring[self.keys[i]]import { createHash } from "node:crypto";
const h = (s: string) => createHash("md5").update(s).digest().readUInt32BE(0);
class ConsistentHash {
private points: { hash: number; node: string }[] = [];
constructor(private vnodes = 150) {}
add(node: string) {
for (let i = 0; i < this.vnodes; i++) this.points.push({ hash: h(`${node}#${i}`), node });
this.points.sort((a, b) => a.hash - b.hash);
}
get(key: string): string {
const k = h(key);
let lo = 0, hi = this.points.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (this.points[m].hash < k) lo = m + 1; else hi = m; }
return this.points[lo % this.points.length].node; // wrap around
}
}Replication on the ring
To keep R copies, store each key on the first R distinct physical servers clockwise from it (Dynamo, Cassandra). When a node fails, its neighbours already hold copies.
Alternatives
| Technique | Idea | Notes |
|---|---|---|
| Rendezvous (HRW) hashing | For each key, compute hash(key, server) for every server; pick the highest | No ring or virtual nodes; O(N) per lookup; minimal movement |
| Jump consistent hash | A tiny arithmetic function mapping a key to one of N buckets | Fast and perfectly even, but buckets can only be added or removed at the end |
| Fixed partitions + directory | Hash into e.g. 16,384 slots; a table maps slots to nodes | Redis Cluster (16,384 slots), Kafka partitions; explicit control over moves |
Where it's used
- Distributed caches: Memcached clients, Redis client-side sharding.
- Databases: Cassandra, DynamoDB, Riak, ScyllaDB.
- Load balancers keeping affinity for caches (Maglev, Envoy's ring hash).
- CDNs choosing which server in a PoP caches an object.
- hash mod N remaps nearly all keys when N changes.
- Consistent hashing places servers and keys on a ring; a key goes to the next server clockwise.
- Only ~1/N of the keys move when a server joins or leaves.
- Virtual nodes balance load and spread a failed node's keys widely.
- Replicate to the next R distinct nodes; alternatives include rendezvous hashing and fixed slots.