Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 1

Why hash mod N breaks when the cluster changes

Measure how hash mod N moves about nine keys in ten when one node joins or leaves a ten-node cluster, see why most of those moves are wasted, and learn what a consistent scheme promises instead.

Contentsand lesson path

What you will learn

  • Compare modulo, ring, rendezvous and jump hashing by balance, key movement and lookup cost.

01. Why it matters

A distributed cache or a partitioned database splits its keys across several machines, called nodes. For every request, a client has to answer one question: which node holds this key? The answer must be quick to compute, and every client must compute the same answer. If two clients disagree, a value written through one of them is invisible to the other.

The first idea most people have is hash(key) % N. You turn the key into a large number with a hash function, divide by the number of nodes N, and use the remainder as the node number. It is fast, it needs no shared state, and with a good hash it spreads keys very evenly. It works perfectly as long as N never changes.

Clusters do change. You add a node before a busy weekend, a node crashes, or you replace a machine. This lesson measures what happens to the keys then, why that means a wave of cache misses or a large data migration, and what a better scheme must promise. If you are new to splitting data across machines, read Scale up, scale out and the scale cube first.

02. Step zero: a hash every client agrees on

Before counting moves, check the hash itself. Every client must turn the same key into the same number, on every machine and after every restart. Python's built-in hash() fails this test for strings. The Python documentation states that the hash values of str and bytes objects are salted with a random value chosen when the process starts: they stay constant inside one process but differ between runs. This protects dictionaries against attackers who send keys designed to collide.

Each Python process normally picks its salt at random. The PYTHONHASHSEED environment variable fixes it, which lets us imitate three separate processes in a repeatable way. The terminal blocks in this skill use bash; on Windows, run them in WSL or Git Bash.

Terminal · three processes, three salts
for seed in 1 2 3; do
  PYTHONHASHSEED=$seed python3 -c 'print(hash("user:42") % 10)'
done
Expected output (CPython 3.12 on a 64-bit machine)
9
0
4

Three processes send the same key to nodes 9, 0 and 4. In a real fleet, that means each app server would read and write the key on a different cache node, and most reads would miss. The fix is a hash that is defined by the bytes of the key alone. Python's hashlib module provides several. The examples in this skill use BLAKE2b cut to 8 bytes, which gives a 64-bit number; MD5, SHA-1, MurmurHash3 and xxHash are common choices in other libraries. It need not be secure against attackers; it must be stable and spread similar keys, such as user:41 and user:42, to unrelated numbers.

Terminal · a stable 64-bit hash with hashlib
python3 - <<'EOF'
import hashlib
digest = hashlib.blake2b(b"user:42", digest_size=8).digest()
print(int.from_bytes(digest, "big") % 10)
EOF
Expected output (the same in every process, on every machine)
2

03. Counting the keys that move

The script below places 100,000 keys, user:0 to user:99999, on ten nodes with hash % N. Then it applies four changes to the node list and compares each key's node before and after. Every run prints the same numbers, in a few seconds, with only the standard library.

It prints three shares of all keys for each change:

  • moved: the key now maps to a different node;
  • had to move: the key's old node left, or its new node is new, so no scheme could have kept it in place;
  • moved needlessly: the key moved between two nodes that were there before and after the change.
Python 3.12 · mod_n.py (standard library only)
"""How many keys does hash mod N move when the node count changes?"""
import hashlib
from collections import Counter


def h64(text: str) -> int:
    """Stable 64-bit hash: the same value on every machine, process and run."""
    digest = hashlib.blake2b(text.encode(), digest_size=8).digest()
    return int.from_bytes(digest, "big")


HASHES = [h64(f"user:{i}") for i in range(100_000)]
NODES = [f"node-{i}" for i in range(10)]


def owners(nodes: list[str]) -> list[str]:
    return [nodes[h % len(nodes)] for h in HASHES]


before = owners(NODES)
counts = Counter(before).values()
print(f"10 nodes: {min(counts):,} to {max(counts):,} keys each (mean 10,000)")

changes = {
    "add node-10": NODES + ["node-10"],
    "remove node-9 (the last)": NODES[:9],
    "remove node-3": [n for n in NODES if n != "node-3"],
    "double to 20 nodes": NODES + [f"node-{i}" for i in range(10, 20)],
}
print(f"{'change':<26}{'moved':>8}{'had to move':>13}{'moved needlessly':>18}")
for change, nodes in changes.items():
    after = owners(nodes)
    moved = must = 0
    for old, new in zip(before, after):
        if old != new:
            moved += 1
            # A move is necessary only if the old node left or the new one is new.
            if old not in nodes or new not in NODES:
                must += 1
    share = len(HASHES)
    print(f"{change:<26}{moved / share:>8.1%}{must / share:>13.1%}"
          f"{(moved - must) / share:>18.1%}")
Terminal
python3 mod_n.py
Expected output
10 nodes: 9,879 to 10,092 keys each (mean 10,000)
change                       moved  had to move  moved needlessly
add node-10                  90.9%         9.1%             81.8%
remove node-9 (the last)     89.9%        10.1%             79.9%
remove node-3                90.1%        10.0%             80.1%
double to 20 nodes           50.2%        50.2%              0.0%

Start with the first line: the busiest node has 10,092 keys and the quietest 9,879, within about 1% of the mean. Balance is not the problem with hash % N.

Movement is. Adding one node to ten moves 90.9% of all keys, but only 9.1% had to move: the new node's fair share, one key in eleven. The other 81.8% moved between old nodes that did nothing at all. The reason is arithmetic. A key stays put only if h % 10 equals h % 11, and for a well-mixed hash that happens for about one key in eleven. Removing a node is just as bad, about 90%, and it makes no difference whether you remove the last node or one from the middle. hash % N knows only positions in a list, not names, so removing node-3 shifts every node after it to a new position.

The last row is the exception. Doubling from 10 to 20 nodes moves 50.2% of the keys, and every one of them goes to a new node, which is the minimum possible. An in-memory hash table can afford to rehash every entry whenever it grows, because moving entries inside one process is cheap. A cluster pays for each moved key with a miss or a network copy, and you do not double a cache tier because one node died.

04. What the moves cost

In a cache, a moved key becomes a miss. The client asks the key's new node, which does not have it, so the request falls through to the database and the value is loaded again. When 90% of keys move at once, the tier behaves for a while like a freshly restarted cache, and it happens at a bad moment: you were adding capacity because the system was busy, or you had just lost a node. The lesson Hit-ratio math and sizing a cache tier shows how quickly database load grows as the hit ratio falls. The old copies also stay behind on their former nodes, wasting memory. Worse, if a flapping node (one that keeps failing and recovering) makes the list change back, clients may read those old copies, which can be stale.

In a partitioned database, a moved key is data that must be copied across the network before the new layout can serve it, while something tracks which copy is current. On a large store that is a lot of work for nothing: if the nodes hold 40 TB and can copy about 1 GB/s between them in total, moving the needless 80% (32 TB) takes about nine hours, on top of normal traffic. Databases therefore use schemes that keep most data in place: see Database scaling and the rest of this skill.

05. What a consistent scheme promises

Karger and colleagues introduced consistent hashing in 1997 for web caches. Two of the properties they defined matter most for a cluster:

  • Balance: each node receives about the same share of keys.
  • Monotonicity: when nodes are added, a key may move from an old node to a new one, but never from one old node to another.

For removals we want the mirror image: when a node leaves, only its own keys move. Ideally they also spread over the remaining nodes instead of piling onto one, a question of balance that the next lesson measures. If a scheme has these properties, then when one node joins a cluster of N, the expected share of keys that moves is about 1/(N + 1). When a node leaves, the share that moves is whatever that node held, about 1/N if the nodes are balanced. This is where the familiar rule "only about K/N keys move" comes from, for K keys and N nodes.

Treat that rule as an estimate, not a law. It assumes the hash spreads keys evenly, the scheme is well balanced, each key is stored once, and all keys are equal. Each assumption can fail. A ring with one position per node is badly balanced, so a newcomer may take far less or far more than its fair share (the lab measures 0.3% in one case). With three replicas per key, roughly three times as many keys change their set of nodes. And keys are not equal: if the moved range holds a few very large or very popular keys, moving 9% of the keys can mean much more than 9% of the bytes or of the traffic.

The next lessons build schemes that keep these promises: the hash ring with virtual nodes, which you also implement and measure in a lab, rendezvous hashing, and jump hashing, which keeps them only when the last node is added or removed. A different fix keeps N constant: hash keys into a fixed number of slots, such as the 16,384 slots of Redis Cluster, and move whole slots between nodes with a lookup table. The last lesson returns to that design.

06. Check your understanding

Practice check · 3 questions

Hash mod N in practice

Three questions about stable hashes, node replacement and when modulo is fine.

Q1. Two app servers run the same Python 3.12 code, `node = nodes[hash(key) % len(nodes)]`, with identical node lists. Values cached through server A are almost always misses when read through server B. What is the most likely cause?
Q2. A cache tier uses `nodes[h % 4]` with nodes [a, b, c, d]. Node c dies. Instead of deleting it from the list, the operator puts a fresh, empty standby node e in its place, giving [a, b, e, d]. Which reads now miss?
Q3. A nightly job splits 200 million log lines across 32 worker processes with `h(user_id) % 32`, so one worker counts all lines of a user. The job always starts all 32 workers and keeps nothing between runs. A reviewer asks for consistent hashing instead. What is the best reply?
Practice only: not graded, not saved, not evidence.

07. Apply it

This skill's practice task asks you to implement modulo and ring hashing with configurable virtual nodes, place one million keys on ten nodes, and report the load standard deviation and the share of keys moved when an eleventh node joins. Start the modulo half now:

  1. Change mod_n.py to use 1,000,000 keys and also print the standard deviation of the per-node counts (statistics.pstdev).
  2. Add a change that removes two nodes at once, and predict the "moved" share before you run it.
  3. Keep your numbers. The lab in this skill builds the ring half and compares the two side by side.

08. Review prompt

Without looking back, explain to a colleague why adding one node to a ten-node hash % N cluster moves about 90% of the keys, and how many of those moves were necessary. Then give one situation where modulo is a sound choice, and state the assumptions behind the "about K/N keys move" rule for consistent schemes.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check