Consistent hashing
With hash(key) % N, every key’s server depends on N, the number of servers. Change N from 10 to 11 and almost every key gets a new server: about 91% of them. For a cache, that means 91% misses at once; for a database, moving 91% of the data.
Consistent hashingConsistent hashingA way to assign keys to servers so that adding or removing a server moves only about 1/N of the keys.Open in glossary → fixes this with a circle, the hash ring:
- Hash every server to a point on the ring.
- Hash every key to a point on the ring.
- A key belongs to the first server clockwise from its point.
Add a new server, and it only takes the keys between itself and the previous server: about 1/N of the keys. Everything else stays where it was. Remove a server, and only its keys move, to the next server clockwise.
With few servers, their points can land unevenly, so one server gets a huge arc. The fix is virtual nodes: each server gets many points on the ring (say 100), which spreads load evenly. When a server fails, its keys are spread over many servers instead of all landing on one neighbor.
With modulo placement, going from N to N+1 servers keeps only the keys whose hash mod N equals their hash mod (N+1), about 1/(N+1) of them, so ~N/(N+1) move. Consistent hashing maps servers and keys onto the same hash space (a ring); ownership is the successor of the key’s position; membership changes move ~K/N keys. Virtual nodes (tens to hundreds per server) bound load imbalance and let heterogeneous servers take proportional numbers of points; lookups are O(log V) with a sorted structure. Replication stores a key on the next R distinct physical servers clockwise (Dynamo, Cassandra), which pairs naturally with quorums. Alternatives: rendezvous (HRW) hashing (each key picks the server with the highest hash(key, server): no ring, minimal movement, O(N) per lookup), jump consistent hash (tiny and perfectly balanced, but only for numbered buckets that grow or shrink at the end), and slot-based schemes like Redis Cluster’s 16,384 hash slots assigned to nodes, which make rebalancing explicit. None of them fix hot keys: a single very popular key still lands on one server and needs replication of that key, request coalescing or local caching.
class HashRing(nodes: Collection<String>, private val virtualNodes: Int = 100) {
private val ring = TreeMap<Long, String>() // position on the ring → server
init { nodes.forEach(::add) }
fun add(node: String) = repeat(virtualNodes) { i -> ring[hash("$node#$i")] = node }
fun remove(node: String) = repeat(virtualNodes) { i -> ring.remove(hash("$node#$i")) }
fun nodeFor(key: String): String {
val entry = ring.ceilingEntry(hash(key)) ?: ring.firstEntry() // past the end: wrap around
return entry.value
}
private fun hash(s: String): Long =
ByteBuffer.wrap(MessageDigest.getInstance("SHA-256").digest(s.toByteArray())).long
}class HashRing {
private final TreeMap<Long, String> ring = new TreeMap<>(); // position on the ring → server
private final int virtualNodes;
HashRing(Collection<String> nodes, int virtualNodes) {
this.virtualNodes = virtualNodes;
nodes.forEach(this::add);
}
void add(String node) { for (int i = 0; i < virtualNodes; i++) ring.put(hash(node + "#" + i), node); }
void remove(String node) { for (int i = 0; i < virtualNodes; i++) ring.remove(hash(node + "#" + i)); }
String nodeFor(String key) {
Map.Entry<Long, String> entry = ring.ceilingEntry(hash(key));
return (entry != null ? entry : ring.firstEntry()).getValue(); // past the end: wrap around
}
private static long hash(String s) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));
return ByteBuffer.wrap(digest).getLong();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}function fnv1a(s: string): number { // a fast 32-bit hash
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193) >>> 0;
}
return h;
}
class HashRing {
private points: { hash: number; node: string }[] = []; // sorted by hash
constructor(nodes: string[], private readonly virtualNodes = 100) {
nodes.forEach((n) => this.add(n));
}
add(node: string): void {
for (let i = 0; i < this.virtualNodes; i++) this.points.push({ hash: fnv1a(`${node}#${i}`), node });
this.points.sort((a, b) => a.hash - b.hash);
}
remove(node: string): void {
this.points = this.points.filter((p) => p.node !== node);
}
nodeFor(key: string): string {
const h = fnv1a(key);
let lo = 0, hi = this.points.length;
while (lo < hi) { // first point with hash >= h
const mid = (lo + hi) >> 1;
if (this.points[mid].hash < h) lo = mid + 1; else hi = mid;
}
return this.points[lo % this.points.length].node; // past the end: wrap around
}
}- Each server is added 100 times, as
cache-1#0,cache-1#1… , so its points are scattered around the ring. nodeForfinds the first point at or after the key’s position (ceilingEntry, or a binary search); if there is none, it wraps around to the first point.- Adding a server only inserts its points: keys that now fall just before them move to it, and nothing else changes.
Predict the output
A cache cluster grows from 10 to 11 servers. Roughly what share of keys changes server with hash % N, and with a consistent hash ring?
With modulo, a key stays only if hash % 10 equals hash % 11, which is true for about 1 in 11 keys, so ~91% move. With a ring, the new server takes over its share of the ring, about 1/11 ≈ 9% of keys, and every other key keeps its server. For a cache, that's the difference between a short dip in hit rate and a stampede on the database.
Tap the line with the bug.
fun serverFor(key: String, servers: List<String>): String {
val index = abs(key.hashCode()) % servers.size
return servers[index]
}String serverFor(String key, List<String> servers) {
int index = Math.abs(key.hashCode()) % servers.size();
return servers.get(index);
}function serverFor(key: string, servers: string[]): string {
const index = Math.abs(hashCode(key)) % servers.length; // a Java-style 32-bit hash
return servers[index];
}Hint: Two problems: one appears when a server is added, one only for a very particular key.
- Modulo placement: adding or removing a server remaps almost every key (~91% going from 10 to 11), which empties a cache cluster at once. Use a hash ring (or rendezvous hashing).
absoverflow: a 32-bit hash can beInt.MIN_VALUE(−2,147,483,648), andabsof it is still negative in Kotlin and Java, so the index is negative and the call crashes, for one unlucky key in four billion that happens to hash there. UseMath.floorMod(hash, size)(Kotlin:hash.mod(size)), or mask the sign bit.
Choosing a placement scheme
| Scheme | Movement on change | Balance | Lookup | Typical use |
|---|---|---|---|---|
hash % N | ~N/(N+1) of keys | Even | O(1) | Fixed clusters that never change size |
| Ring + virtual nodes | ~1/N | Good with 100+ vnodes | O(log V) | Memcached/Redis clients, Dynamo-style stores |
| Rendezvous (HRW) | ~1/N | Even | O(N) | Small clusters, CDN node selection |
| Jump hash | ~1/N | Perfect | O(log N) | Numbered shards that grow at the end |
| Fixed slots (e.g. 16,384) | Explicit slot moves | Operator-controlled | O(1) | Redis Cluster, many databases |
Membership must be agreed on (all clients must see the same ring), usually via a coordination service or gossip; clients with different views send the same key to different servers during changes, so caches tolerate it and databases use explicit rebalancing with ownership handoff.
- Modulo remaps ~N/(N+1) keys on resize; a ring moves ~1/N. Ownership = successor on the ring.
- Virtual nodes for balance, proportional capacity, and spreading a failed node’s load; O(log V) lookup.
- Replicas on the next R distinct physical nodes; quorums.
- Alternatives: rendezvous hashing, jump hash, fixed slots (Redis Cluster 16,384). Consistent membership views matter.
- Hot keys remain hot: replicate the key, coalesce requests, cache locally. Beware
abs(Int.MIN_VALUE).
Check this part
On a hash ring, which server owns a key?
Why give each server many virtual nodes?
What does consistent hashing not solve?
What is Math.abs(Integer.MIN_VALUE) in Java?