cloudpatterns.appClassroomKatasWhiteboardBlog
Z3 · Data & Storage

Consistent hashing

Consistent hashing

Gold

To find a key's shard, you hash the key. The simple way — hash mod the number of shards — breaks when that number changes, because almost every key lands on a different shard and the data must move. Consistent hashing puts shards and keys on a ring, and each key belongs to the next shard round the ring. Adding a shard then moves only the keys it takes over — about 1/N of them — and removing one hands on only its own keys. Giving each server many points on the ring (virtual nodes) keeps the slices even.

Use when
Shards or cache servers are added and removed while the system runs · A cache cluster where a reshuffle would send almost every lookup to the database at once · Mapping keys to servers without a central lookup table
Avoid when
The number of shards never changes — a plain hash is simpler · You need range scans over adjacent keys — hashing scatters them · One key gets more traffic than one server can take — the ring won't split it (see hot keys)
Trade-offs
Only ≈ 1/N of the keys move per change, but the ones that do still have to be copied · Many virtual nodes even out the slices, but add more neighbours and more maintenance work · Fixed slots (hash slots, virtual partitions) make moves simple, at the price of a slot → node map to keep
Requires
Sharding
3 objectives · 12 misconceptions
  • predict Predict roughly what share of the keys move to another shard when one shard is added, with hash mod N and with a hash ring.
  • explain Explain how a ring finds a key's shard, and why adding or removing a shard only touches the keys next to it.
  • explain Explain why each server takes many points on the ring, and what that changes when a server joins or fails.
  • Not true: With hash mod N, adding a shard only moves the keys that go to the new shard.
  • Not true: Once a key is placed, changing the number of shards leaves it where it is.
  • Not true: A key belongs to the nearest server on the ring, in either direction.
  • Not true: A key placed after the last server on the ring has no owner.
  • Not true: With one point per server the slices are only a little uneven, so the busiest server just runs a bit hot.
  • Not true: A hash ring reshuffles the keys just like hash mod N when a shard is added.
  • Not true: With consistent hashing, adding a shard moves no data at all.
  • Not true: One point per server on the ring splits the keys evenly.
  • Not true: On a basic ring with one point per server, a failed server's keys spread evenly over all the others.
  • Not true: Even with many points per server, a server that leaves hands all its keys to one neighbour.
  • Not true: Consistent hashing spreads one very busy key over several shards.
  • Not true: Consistent hashing is only used inside databases.

Stories here

Neighborhood

builds onSharding
Consistent hashing
unlocksHot keys
On linesScale Line

Progress is saved on this device