Split keys with hash mod N
Hashing the partition key and taking it mod N spreads writes evenly across N servers, beating range partitioning's hot-tail problem.
One box has three ways to die, so we need many boxes; the first job is deciding which box owns which key.
Scene 02
Split keys with hash mod N
- Watch
- Try it
- Predict
- Capture
Watch each partition key get hashed and dropped into one of four server bins. Same key always lands in the same bin — that's how a client can later find a row by hashing the key and going straight to the owner.
Highlighted lines are the ones running in the diagram right now.
def route(key, N):h = hash(partition_key(key))return servers[h mod N]# same key → same h → same server,# every time, on every client.
# ranges = [(-inf, b0), (b0, b1), ..., (b_{N-2}, +inf)]def route(key, ranges):i = upper_bound(ranges, key)return servers[i]# monotonically-increasing keys (timestamps, auto-incr ids)# all return the same i — the rightmost bin.
Where this sits in Build a wide-column store (Cassandra / DynamoDB family)
Scene 02 of 13, in the Sharding act — Hash mod N spreads load — until adding a server reshuffles 80% of keys.. Hash the key, take it mod N, route to that server — keys spread evenly across the cluster.
Up next. Hash mod N spreads load beautifully — until the day we add the fifth server, when N suddenly changes and almost every key needs a new home.
All 13 scenes in Build a wide-column store (Cassandra / DynamoDB family) · Every curriculum