Consistent Hashing
System Design · Scaling & Data · Intermediate · 14 min
Spread data over servers so adding a server only moves a little data.
Servers and keys sit like seats around a round table. Each guest is served by the next waiter clockwise. A new waiter who sits down only takes over the guests between them and the previous waiter; everyone else keeps their waiter. Give each waiter several seats and the work evens out.
The idea in everyday words
Seats around a round table. Guests (keys) sit at their spot and are served by the next waiter (server) clockwise. If a new waiter joins, only the guests between the new waiter and the previous one switch. Everyone else keeps their waiter.
The problem with key % N
With server = hash(key) % N, changing N from 3 to 4 moves most keys: a cache stampede and massive data shuffling. See for yourself:
keys = [f"user{i}" for i in range(20)]
h = lambda s: sum(ord(c) * 31 ** i for i, c in enumerate(s))
moved = sum(1 for k in keys if h(k) % 3 != h(k) % 4)
print(moved, "of", len(keys), "keys moved when going from 3 to 4 servers")
The ring
Put servers AND keys on a circle (0–359°) using a hash. A key belongs to the first server clockwise. Adding a server only steals keys from its neighbour → roughly 1/N of keys move.
Virtual nodes: place each server at many points on the ring so load is even.
Used by: DynamoDB, Cassandra, Discord, CDNs, distributed caches.
Step by step
- Place servers:
A=40°, B=160°, C=290°
- Place key:
user7 → 100° → next clockwise = B
- Add D at 120°:
user7 now → D. Keys in 40°–120° move; nothing else changes
- Remove C:
C's keys move to A (the next one clockwise)
Code example
import bisect
ring = sorted([(40, "A"), (160, "B"), (290, "C")])
positions = [p for p, _ in ring]
def owner(pos):
i = bisect.bisect_left(positions, pos)
return ring[i % len(ring)][1]
for k, pos in [("user1", 10), ("user7", 100), ("cart", 200), ("photo", 350)]:
print(k, pos, "->", owner(pos))Interview tips
Say: 'I'd use consistent hashing with virtual nodes so scaling the cache only remaps ~1/N keys.'
Know that DynamoDB/Cassandra use it.
Challenge: Find the Owner on the Ring
servers is a dict/object of name → position (0–359). For each key position in keys, return the owning server: the server with the smallest position ≥ key, wrapping to the smallest position overall.
Example: ring_owner({"A": 40, "B": 160, "C": 290}, [10, 100, 350]) → ["A", "B", "A"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Find Smallest Letter Greater Than Target (Easy)
- Search Insert Position (Easy)
- DynamoDB: partitions and data distribution
More in Scaling & Data
- Scaling & Load Balancers
- Caching (Redis & CDN)
- Databases: SQL, NoSQL, Sharding
- Choosing a Database on AWS
- DynamoDB Data Modeling
Previous: DynamoDB Data Modeling · Next: CAP, PACELC & Consistency