← Back to blogs

System Design

Consistent Hashing

the problem with  hash(key) % N

· 2 min read
DEMO — naive modulo routing
Node ANode BNode C
0 / 12
KEYS REMAPPED THIS STEP
session-42 → Asession-77 → Bcart-13 → Ccart-88 → Buser-5 → Cuser-9 → Auser-21 → Corder-3 → Aorder-14 → Cview-1 → Cview-2 → Aview-3 → B

Fast, simple, evenly distributed — until N changes. Adding or removing a server changes every subsequent % N, which reassigns almost the entire keyspace, not just the keys that logically should move.

A concrete example

3 nodes (A, B, C), 12 keys, routed by hash(key) % 3. Add a 4th node (D) and recompute with % 4:

keyN=3 ownerN=4 ownermoved?
session-42AA
session-77BA✅
cart-13CC
cart-88BC✅
user-5CA✅
user-9AA
user-21CA✅
order-3AD✅
order-14CD✅
view-1CC
view-2AD✅
view-3BA✅

8 of 12 keys (67%) moved to a different server — for adding one machine. In a real cache cluster, that's 67% of your traffic suddenly missing cache and hammering the database at once. In a real DB shard map, that's a two-thirds data migration to add one node.

This is the failure mode consistent hashing exists to fix: it makes node changes touch a bounded, local slice of the keyspace instead of the whole thing.

Try the live version — add/remove nodes and watch the naive approach vs. the ring side by side: Consistent Hashing, Drawn on a Ring