Why does modulo hashing hurt distributed caches and how does Consistent Hashing solve it?
Quick Summary: Modulo hashing (hash(key) % N) remaps almost every key when node count N changes, triggering massive cache misses; Consistent Hashing arranges nodes and keys on a 0..2^32-1 ring so scaling N moves only ~1/N keys, smoothed by Virtual Nodes.
Direct Interview Answer
Under naive modulo partitioning, adding or losing 1 node changes % N globally—invalidating 80–90% of cached data simultaneously.
Consistent Hashing hashes both server IDs and object keys onto the same conceptual circle (ring). Each key maps clockwise to the first node encountered. Adding or removing a node affects only its immediate counterclockwise neighbor (~K/N keys).
Detailed Technical Explanation
Why Virtual Nodes (vnodes)? Placing only 4 physical servers on a ring can leave huge uneven arcs (hot shards). Assigning 100–200 virtual positions per physical node distributes load uniformly across machines and simplifies heterogeneous node sizing.
Practical Walkthrough
Consistent hash ring key placement moves minimal keys on node addition.
import hashlib, bisect
class HashRing:
def __init__(self, nodes, vnodes=50):
self.ring, self.keys = {}, []
for node in nodes:
for i in range(vnodes):
h = int(hashlib.md5(f"{node}#{i}".encode()).hexdigest(), 16)
self.ring[h] = node
self.keys.append(h)
self.keys.sort()
def get_node(self, item_key: str) -> str:
h = int(hashlib.md5(item_key.encode()).hexdigest(), 16)
idx = bisect.bisect(self.keys, h) % len(self.keys)
return self.ring[self.keys[idx]]
print(HashRing(["redis-1", "redis-2", "redis-3"]).get_node("user:1042"))
redis-2
Real-World Production Use Case
Redis Cluster, Cassandra/DynamoDB token rings, CDN edge routing, and sticky WebSocket load balancers.
Common Interview Mistakes to Avoid
- Omitting virtual nodes, leading to severe shard skew when cluster sizes are small.
- Ignoring replication to the next K distinct physical nodes (skipping consecutive vnodes on the same host).