System Design · 03. Data & Storage · 10 min · Intermediate
Consistent Hashing
Add or remove a server and move only the keys that must move.
In short
Servers and keys share one hash ring; a key belongs to the next server clockwise. Adding or removing a server moves one arc, not the whole data set.
Virtual nodes even out the arcs, the next servers clockwise hold the copies, and a cache fleet loses only one slice when a server dies.
Key ideas
- Servers and keys are hashed into the same space, so they can be compared directly. (step 2)
- Adding a server only touches its clockwise neighbour. Every other server keeps all of its keys. (step 4)
- Skip virtual nodes of a server you already chose, or two copies could end up on the same machine. (step 8)
Good to know
- Looking up the owner is a binary search over the sorted server positions: O(log n). (step 3)
- A stronger machine can get more virtual nodes, and so a bigger share: weights for free. (step 7)
- Memcached clients, DynamoDB, Cassandra and many CDNs place data with a hash ring. (step 9)
Watch out
- Ideally only about 1/5 of the keys would move: the share the new server should take. (step 1)
- D now holds its own keys and C's. If C was busy, D can be overloaded: the next steps fix this. (step 5)
- The busiest server sets the limit for the whole system, however idle the others are. (step 6)
Key numbers
- Servers
- 4
- Keys moved
- 13%
- Biggest share
- 31%
- Hit rate
- 90%
Terms
- Modulo hashing (hash % N)
- Placing keys with hash(key) % N, which moves most keys when N changes.
- Hash ring
- The hash space bent into a circle, with servers and keys placed on it by their hashes.
- Clockwise ownership
- A key belongs to the first server at or after its point, going clockwise.
- Virtual nodes
- Many points on the ring for each server, so the arcs, and the load, even out.
- Replicas on the ring
- Copies of a key kept on the next distinct servers clockwise.
- Cache fleet
- Many cache servers sharing the keys with a hash ring, so losing one loses only its slice.