Full answer
The problem with mod N
With node = hash(key) % N, going from 3 to 4 cache servers changes the result for most keys. For a cache that means a sudden wave of misses that can overload the database. For a datastore, it means moving most of the data.
How the ring works
- Hash every node's name to a point on a ring (for example 0 to 2^128 - 1 with MD5, or 2^32 - 1 with a 32-bit hash).
- Hash each key to a point on the same ring.
- Walk clockwise from the key's point; the first node you meet owns the key.
When a node is added, it takes over only the keys between its point and the previous node. When a node is removed, its keys go to the next node clockwise. Everything else stays put.
Virtual nodes
With one point per server, arcs have random sizes, so one server may own far more keys than another. And when a server leaves, all its keys move to one neighbour. Virtual nodes fix this: each server gets many points (for example 100 to 200). Load averages out, and a leaving server's keys spread over many others. Bigger servers can get more virtual nodes.
A small working example
Run with Python 3.13 (output identical on two runs):
import bisect
import hashlib
def h(key: str) -> int:
return int(hashlib.md5(key.encode()).hexdigest(), 16)
class HashRing:
def __init__(self, nodes, vnodes=100):
self.ring = [] # sorted list of (hash, node)
for node in nodes:
self.add(node, vnodes)
def add(self, node, vnodes=100):
for i in range(vnodes):
bisect.insort(self.ring, (h(f"{node}#{i}"), node))
def remove(self, node):
self.ring = [(p, n) for p, n in self.ring if n != node]
def get(self, key):
i = bisect.bisect(self.ring, (h(key),)) % len(self.ring)
return self.ring[i][1]
keys = [f"student:{i}" for i in range(10_000)]
ring = HashRing(["cache-a", "cache-b", "cache-c"])
before = {k: ring.get(k) for k in keys}
ring.add("cache-d")
moved = sum(1 for k in keys if ring.get(k) != before[k])
print(f"moved {moved} of {len(keys)} keys ({moved / len(keys):.1%})")
print("modulo would move", sum(1 for k in keys if h(k) % 3 != h(k) % 4), "keys")Output:
moved 2734 of 10000 keys (27.3%)
modulo would move 7464 keys
The ideal is 1/4 = 25% when going from 3 to 4 nodes; the ring gets close, while mod N moves about three quarters.
Where it is used
Distributed caches (client-side sharding for Memcached), Dynamo-style databases such as Cassandra, and load balancers that need cache affinity. Alternatives include rendezvous (highest random weight) hashing and jump consistent hash, and many databases instead use a fixed number of partitions assigned to nodes.
By level
Fresher: Explain the ring idea and that adding a server should not reshuffle every key. A fresher should explain that only some keys move when a server is added.
Mid: Quantify key movement, explain virtual nodes and replica placement, and implement a lookup with binary search. Expect the 1/N movement figure and the purpose of virtual nodes.
Senior: Compare consistent hashing with fixed partition maps, rendezvous and jump hash, discuss rebalancing traffic, heterogeneous nodes and how membership changes are agreed across clients. The senior answer compares alternatives and how clients agree on membership.
Key points
- mod N remaps most keys when N changes
- On a ring, a key belongs to the next node clockwise
- Adding or removing a node moves only about 1/N of keys
- Virtual nodes balance load and spread moved keys
- Used in caches, Dynamo-style stores and affinity load balancing
Common mistakes
- Claiming no keys move at all
- Forgetting virtual nodes and getting uneven load
- Ignoring replication: real systems store copies on the next few distinct nodes
- Thinking consistent hashing fixes a single hot key
Follow-ups
- How would you place replicas on the ring?
- How does rendezvous hashing compare?
- How many virtual nodes would you use and what does it cost?
Tips
- Explain the mod N failure with a number first
- Draw the ring and walk clockwise
- Mention virtual nodes before the interviewer asks
Evaluation rubric
- Explains why mod N fails
- Correct ring lookup and movement on join or leave
- Explains virtual nodes and their purpose
- Names real uses or alternatives