Sub topic 3
Modulo Hashing and Why Resizing Hurts
This chapter assumes you know what a hash function is, what a cache or shard is, and how to read short Python programs. You will see how hash(key) mod N assigns keys to nodes. Then you will work out how many keys change owner when N changes, and why that makes resizing painful for a cache or sharded store.
The simplest placement rule
Suppose you run a cache with N servers numbered 0 to N-1. Clients need a rule that maps a key to a server, and every client must compute the same answer with no central coordinator. The usual first answer is:
node_index = h(key) % NHere h is a deterministic hash function that spreads keys roughly uniformly. In this chapter h returns a large integer, built from MD5 so that results are the same on every run and every machine. Python's built-in hash() is a poor choice for strings, because it is salted per process by default. Two clients would disagree about where a key lives.
The rule has real strengths:
- It needs no lookup table. Each client only needs to know
Nand the ordered list of nodes. - Lookup is a single hash and a single modulo operation.
- With a good hash, each node receives about
1/Nof the keys, so load is even.
For a cluster that never changes size, this is hard to beat. The trouble starts when N changes.
What happens when N changes
Take 4 nodes and add a fifth. Each key's index is now h(key) % 5 instead of h(key) % 4. A key stays put only if the two remainders are equal.
The table shows hash values r from 0 to 9.
| h(key) | h mod 4 | h mod 5 | Same node? |
|---|---|---|---|
| 0 | 0 | 0 | yes |
| 1 | 1 | 1 | yes |
| 2 | 2 | 2 | yes |
| 3 | 3 | 3 | yes |
| 4 | 0 | 4 | no |
| 5 | 1 | 0 | no |
| 6 | 2 | 1 | no |
| 7 | 3 | 2 | no |
| 8 | 0 | 3 | no |
| 9 | 1 | 4 | no |
The pattern repeats every 20 values, because 20 is the least common multiple of 4 and 5. In each block of 20 consecutive hash values, only the first four (h mod 20 equal to 0, 1, 2, or 3) keep their node. The other 16 move. So 80% of the keys change owner.
This is not an accident of the numbers 4 and 5. For any N, the moduli N and N+1 share no common factor, so the pattern repeats every N(N+1) values. The remainders agree only when h mod N(N+1) is less than N. That is N values out of N(N+1), a fraction of 1/(N+1). So:
- Fraction of keys that stay:
1 / (N+1). - Fraction of keys that move:
N / (N+1).
The fraction that moves approaches 100% as the cluster grows.
Measuring it
You can confirm this experimentally. This script is the same experiment as the table, run on 10,000 real keys.
import hashlib
def h(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
keys = [f"key{i}" for i in range(10000)]
moved = sum(1 for k in keys if h(k) % 4 != h(k) % 5)
print(moved / len(keys))The printed value is close to 0.8. It will not be exactly 0.8, because 10,000 keys is a finite sample.
The next script compares several cluster sizes against the formula and against an ideal rule. The ideal rule moves only the keys the new node should take over, which is 1/(N+1) of them.
import hashlib
def h(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
keys = [f"key{i}" for i in range(10000)]
hashes = [h(k) for k in keys]
for n in (2, 4, 9, 49, 99):
moved = sum(1 for x in hashes if x % n != x % (n + 1)) / len(hashes)
print(f"{n} -> {n + 1}: measured {moved:.3f}, "
f"formula {n / (n + 1):.3f}, ideal {1 / (n + 1):.3f}")Expect the measured and formula columns to agree within about one percentage point. The table below shows the formula and ideal values.
| Resize | Keys moved by modulo | Keys moved in the ideal case |
|---|---|---|
| 2 to 3 | 66.7% | 33.3% |
| 4 to 5 | 80.0% | 20.0% |
| 9 to 10 | 90.0% | 10.0% |
| 99 to 100 | 99.0% | 1.0% |
The gap widens as the cluster grows. Adding the hundredth node to a hundred-node cluster should disturb about 1% of the data, but modulo hashing disturbs 99%.
Where the moved keys go
Modulo hashing does worse than moving too many keys. Many of the moved keys go to the wrong place.
When you add node 4 to a 4-node cluster, the new node should receive its share and nothing else should move. Under modulo, only the keys with h mod 5 == 4 land on the new node. That is 20% of all keys. The other 60% of keys, which also moved, shuffle between nodes that already existed. This shuffling is pure waste. Node 1 loses keys to node 3 and gains keys from node 0, even though neither of those nodes changed.
You can measure the split directly:
import hashlib
def h(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
hashes = [h(f"key{i}") for i in range(10000)]
moved = [x for x in hashes if x % 4 != x % 5]
to_new = [x for x in moved if x % 5 == 4]
print("moved:", len(moved) / len(hashes))
print("moved to the new node:", len(to_new) / len(hashes))
print("moved between old nodes:", (len(moved) - len(to_new)) / len(hashes))You should see roughly 0.80, 0.20, and 0.60.
Why this hurts in practice
Consider a cache in front of a database, where the cache has a 95% hit rate. The database sees 5% of the read traffic.
Now add one node to a 4-node cache. Clients immediately start using the new mapping. For any key that moved (80% of them), the client asks a node that does not hold the entry. Only the 20% of keys that kept their node can still hit. The hit rate drops from 95% to about 19% (0.95 × 0.20). The database miss traffic rises from 5% to about 81% of reads, which is roughly 16 times the load.
This happens exactly when you least want it. People add capacity because the system is under load. Removing a failed node causes the same effect from the other direction. Going from N to N-1 nodes moves (N-1)/N of the keys, because the same arithmetic applies in reverse. The surge of misses can overload the database, which slows responses, which causes more timeouts and retries.
The diagram traces this chain of events.
Stores that hold data as the source of truth have a worse problem. There, a moved key must be physically copied to its new node. Moving 80% of the dataset over the network takes a long time and competes with normal traffic.
Edge cases and partial fixes
Modulo hashing has a few special cases. Knowing them helps you judge when it is still acceptable.
- Doubling. Going from
Nto2Nmoves only half of the keys. A key keeps its node whenh mod 2N < N. Half is the minimum possible here, since the new nodes must receive half of the data. Doubling is therefore the best case for modulo, but it forces you to grow in large steps and wastes capacity. - Non-adjacent changes. Moving from
NtoN+2, or from 10 to 15, moves a large fraction too. The fraction that stays isgcd(N, M) / M-shaped, so it is only large when the two sizes share large factors. - Removing a middle node. Modulo needs contiguous indices from
0toN-1. If node 2 of 5 fails, you must either leave a hole, so that keys mapping to slot 2 fail, or renumber the nodes. Renumbering changesN, and the full remap follows. - Fixed slots. Some systems hash to a large fixed number of slots, such as 16,384, and keep a separate table that assigns slots to nodes. Moving a slot between nodes moves only that slot's keys. This works, but it needs a coordinated table that every client shares. That is the thing modulo hashing avoided.
- Planned resizes. If the cluster changes rarely and you can drain or rebuild the cache offline, the cost may be acceptable. A cold cache that is warmed in advance avoids the miss surge.
The goal for the next chapters is a placement rule that needs no shared table, like modulo, but moves only about 1/(N+1) of the keys when a node joins. That is the ideal value in the table above. The hash ring achieves it by hashing the nodes onto the same space as the keys, so that a node's identity is no longer its position in a list.
Exercise
A cache cluster has 9 nodes and uses h(key) % N. You add a tenth node. What fraction of keys will change nodes, and what fraction is the minimum that must move?
Show answer
Under modulo, the fraction that stays is 1/(N+1) = 1/10, so 9/10 = 90% of keys move. The minimum is the share the new node should own, which is 1/10 = 10%. Modulo therefore moves nine times as many keys as necessary.
Exercise
A cache with a 90% hit rate has 5 nodes using h(key) % N. You add a sixth node. Assuming the hit rate on keys that stay is unchanged and keys that moved always miss, what is the hit rate immediately afterward, and how many times larger is the miss rate than before?
Show answer
The fraction that stays is 1/6, so the hit rate is 0.90 × 1/6 = 0.15, or 15%. The miss rate rises from 10% to 85%, which is 8.5 times larger.
Exercise
With modulo hashing, you grow a cluster from 4 nodes to 5. Of all keys, 80% move. How many of those moved keys land on the new node, and where do the rest go?
Show answer
Keys land on the new node (index 4) when h mod 5 == 4, which is 20% of all keys. The remaining 60% of all keys move between nodes that already existed. That reshuffling is unnecessary work.