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.

Intermediate 3 min readLesson 9 of 20

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 hashmod 4mod 5
1020
1131
1202
1313
1424
1530

Every key moved. In general, going from N to N + 1 servers remaps about N/(N+1) of the keys.

The hash ring

  1. Imagine the hash space (say 0 to 2³² − 1) bent into a ring.
  2. Hash each server onto the ring (e.g. hash("cache-a")).
  3. Hash each key onto the ring; it belongs to the first server clockwise from it.
  4. Adding a server takes over only the keys between it and its counter-clockwise neighbour. Removing one hands its keys to its clockwise neighbour.
Ak1Bk2Ck3
Clockwise ring: k1 → B, k2 → C, k3 → A.

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());
    }
}

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

TechniqueIdeaNotes
Rendezvous (HRW) hashingFor each key, compute hash(key, server) for every server; pick the highestNo ring or virtual nodes; O(N) per lookup; minimal movement
Jump consistent hashA tiny arithmetic function mapping a key to one of N bucketsFast and perfectly even, but buckets can only be added or removed at the end
Fixed partitions + directoryHash into e.g. 16,384 slots; a table maps slots to nodesRedis 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.
Key takeaways
  • 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.