Video in progress

Strong Middle 🏗️ System design

How does consistent hashing work, and why do you need virtual nodes?

Servers and keys are both hashed onto one ring, and a key belongs to the first server clockwise from it. When a server is added or removed, only the keys in the neighboring range move. Virtual nodes spread the load more evenly.

📖 Answer

With a plain hash(key) % N, if N changes from 4 to 5, about 80 percent of the keys land on a different server. For a cache that means almost a complete miss and a hit on the DB.

Consistent hashing has a ring from 0 … 2^32. Each server is placed at a point on the ring. A key walks clockwise from its hash and goes to the first server it meets. When a new server is added, it takes over only the range just before it — on average a 1/N share of the keys move.

The problem: 3–4 points land on the ring at random and the ranges come out very uneven. One server can end up with half the ring. And when a server goes down, its entire load goes to just one neighbor.

Virtual nodes: each physical server appears on the ring as 100–200 points.

TreeMap<Long, String> ring = new TreeMap<>();

void addNode(String node) {
    for (int i = 0; i < 160; i++) {
        ring.put(hash(node + "#" + i), node);
    }
}

String nodeFor(String key) {
    var e = ring.ceilingEntry(hash(key));
    return (e != null ? e : ring.firstEntry()).getValue();
}

Now the load is much more even, and when a server dies its pieces are split among many servers. You can also weight it: give a stronger server more virtual nodes.

Where you see it: partitioning in Cassandra and DynamoDB, Memcached clients, ring_hash balancing in Envoy. Redis Cluster does it differently — it uses 16,384 fixed slots — but the goal is the same: move little on rebalancing.