Consistent hashing and virtual nodes
How to spread keys across servers so that adding or losing a server moves only a small slice of the data, and why every server owns many small arcs instead of one big one.
In one sentence
Put servers and keys on the same hash ring; each key belongs to the next server clockwise. When a server joins or leaves, only the keys of one arc move, about 1/N of them, instead of almost all.
The problem with hash mod N
The obvious way to pick a server is hash(key) % N. It spreads keys evenly, until N changes. Go from 4 to 5 cache servers and about 80% of the keys now map to a different server. For a cache cluster that means a sudden wave of misses hitting the database; for a sharded database, moving most of the data.
The ring
- Hash every server's name to a position on a circle (0 to 2³²).
- Hash every key to a position on the same circle.
- A key belongs to the first server clockwise from it.
- Add a server: it only takes the keys between itself and the previous server. Remove one: only its keys move, to the next server.
Virtual nodes: fixing the uneven arcs
With one point per server, the arcs are random sizes: one server can own twice the keys of another. And when a server dies, all its keys land on a single neighbour, which may then overload too.
The fix: give each server many points (virtual nodes), for example 100 to 256. Each server owns lots of small arcs scattered around the ring, so the load evens out, and a failed server's keys are spread over all the others. A bigger machine can simply get more virtual nodes.
Where it's used
| System | What it distributes |
|---|---|
| Amazon Dynamo, DynamoDB, Cassandra | Rows across storage nodes |
| Memcached / Redis clients | Cache keys across cache servers |
| CDNs and load balancers | Requests to servers, keeping the same user or URL on the same machine |
| Chat and realtime systems | Which gateway server holds each user's connection |
Key takeaways
- 01hash mod N reshuffles almost every key when N changes.
- 02On a hash ring each key goes to the next server clockwise, so changes only move one arc.
- 03Virtual nodes give each server many small arcs: even load and graceful failures.
- 04It's the routing behind Dynamo-style databases, distributed caches and many load balancers.
Check your understanding
1 of 3
On a hash ring, which server owns a key?
Related concepts
Sharding
Sharding splits one big database into several independent databases (shards), each holding a slice of the rows, so storage and writes scale with the number of machines.
8 min read →Caching
A cache stores copies of data that are expensive to get (slow query, far away server) so the next request can be answered from somewhere fast and close.
9 min read →Load balancers
A load balancer is the single entry point that receives every request and forwards it to one of many healthy servers, so no single server is overloaded and failures stay invisible to users.
8 min read →