AI Hints
System Design · Lesson 45 of 120

Consistent Hashing

Moving less data.

⏱ 2 min read▶ Video at 53:00🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Hash mod N has a hidden problem. When you add one shard, N changes, and almost every key moves to a different shard. Consistent hashing fixes this.

Consistent Hashing
From the video: Consistent Hashing
  • Hash mod N
  • Add a shard...
  • ...almost everything moves

How much moves?

Let's measure. We place a thousand keys on four shards, then add a fifth, and count how many keys change shard. Run it. With hash mod N, about eighty percent of keys move. With consistent hashing, only about a fifth move, just the ones the new shard takes over.

ring.pypython
import hashlib, bisect

def h(s):
    return int(hashlib.md5(s.encode()).hexdigest(), 16)

def ring_owner(key, nodes, vnodes=100):
    ring = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
    points = [p for p, _ in ring]
    i = bisect.bisect(points, h(key)) % len(ring)
    return ring[i][1]

keys = [f"user{i}" for i in range(1000)]
before, after = ["s0", "s1", "s2", "s3"], ["s0", "s1", "s2", "s3", "s4"]

mod = sum(h(k) % 4 != h(k) % 5 for k in keys)
ring = sum(ring_owner(k, before) != ring_owner(k, after) for k in keys)
print(f"hash mod N moved: {mod / 10:.0f}%")
print(f"consistent moved: {ring / 10:.0f}%")
Output
hash mod N moved: 80%
consistent moved: 18%

The ring

Here's the idea. Imagine a ring of numbers. Each shard is placed at several points on the ring. Each key is hashed onto the ring too, and belongs to the next shard clockwise. When a new shard joins, it only takes keys from its neighbours. Everyone else stays put.

  1. Hash shards onto a ring
  2. Hash keys too
  3. Next shard clockwise
  4. New shard: small move
The ring
From the video: The ring

Summary

Consistent hashing places keys and shards on a ring, so adding a shard moves only a small share of keys. Databases like Cassandra and DynamoDB use it. Next, what happens when one key is far too popular.

Key takeaways
  • A ring of hashes
  • Next shard clockwise
  • Small moves
Next up: Hot Spots — the celebrity problem