Sub topic 1
Why We Need to Spread Keys Across Nodes
Prerequisites
Assume you know that a hash function maps a value to a number, and that a distributed cache or database may split data across several nodes. You should also be comfortable with basic binary search.
The key distribution problem
A cluster spreads keys across nodes so that no single node becomes a bottleneck. A useful assignment should be:
- Deterministic: every client chooses the same node for a key.
- Balanced: nodes receive roughly similar amounts of data and traffic.
- Stable: adding or removing one node moves as few keys as possible.
A cache lookup fails when a client stores user:42 on one node but later searches another. The client needs a repeatable mapping from each key to its current owner.
What the hash function must provide
A hash function should distribute typical keys uniformly across its output space. Uniformity reduces accidental hot spots. It must also be deterministic: the same input must produce the same output during every lookup.
Cryptographic strength is usually unnecessary. Systems often choose a fast, well-distributed hash instead. The important property here is stable distribution, not resistance to attackers.
Modulo hashing and why resizing hurts
The simplest mapping is:
node_index = hash(key) % number_of_nodesWith four nodes, a key belongs to bucket 0, 1, 2, or 3. If the cluster grows to five nodes, the divisor changes, so most results change too.
| Cluster change | Keys likely to move |
|---|---|
| 4 nodes to 5 nodes | About 80% |
| 5 nodes to 6 nodes | About 83% |
This movement can invalidate caches, overload storage, and trigger large data transfers.
The hash ring
Consistent hashing places both keys and nodes in one circular hash space. A key belongs to the first node found while moving clockwise from the key's position. When a node joins, it takes only the keys in the interval immediately before its position. When it leaves, its keys move to the next node clockwise.
This design limits remapping, although a plain ring can still have uneven loads. Virtual nodes, covered later, place each physical node at many positions to smooth that distribution.
Exercise
Why does changing the divisor in hash(key) % N move many keys?
Show answer
The same hash is tested against a different modulus, so most keys receive a different remainder and therefore a different node.