Sub topic 2
What We Need from the Hash Function
This chapter assumes you can read short Python programs and know what a hash function and a hash table are. You should also know why a distributed cache or sharded store needs a rule that maps each key to a node. The next chapters build on that rule. Here we ask a narrower question: what must the hash function guarantee before any placement scheme can work?
Why the hash function matters
Every placement scheme in this tutorial turns a key into an integer, then uses the integer to pick a node. Modulo hashing computes h(key) mod N. The hash ring, introduced later, compares h(key) with the integer positions of nodes. In both cases the scheme is only as good as the integers it receives.
Two properties matter most:
- Determinism. The same key always gives the same integer, on every machine and in every process, at all times.
- Uniformity. Across many keys, the integers spread evenly over the whole output range.
Three secondary properties also matter in practice: a wide enough output range, good mixing of similar inputs, and acceptable speed.
Determinism: every client must agree
In a cache cluster, many clients compute placement independently. Client A writes user:42 to node 3. If client B hashes the same key to node 1, it misses the cache. Nothing coordinates the two clients, so agreement has to come from the function itself.
Determinism has to hold across processes, restarts, machines, and often programming languages. Python's built-in hash() for strings does not meet this requirement. Python randomizes it per process, as a defense against hash-flooding attacks, unless PYTHONHASHSEED is fixed. This program shows it:
import os
import subprocess
import sys
def builtin_hash_in_new_process(seed):
env = dict(os.environ, PYTHONHASHSEED=str(seed))
result = subprocess.run(
[sys.executable, "-c", "print(hash('user:42'))"],
env=env,
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
print(builtin_hash_in_new_process(1) == builtin_hash_in_new_process(2))The program prints False. The same string gave different integers in two processes. Two clients using hash() would disagree about where every key lives.
A stable alternative takes the bytes of the key and returns the same integer every time:
import hashlib
def stable_hash(key):
return int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16)
print(stable_hash("user:42") == stable_hash("user:42"))This prints True, and it prints True on any machine. This is the same h used in the other chapters of this tutorial.
What else can break agreement
Using a stable algorithm is necessary but not sufficient. These differences also change the result:
- Encoding. The string
"café"has different bytes in UTF-8 and Latin-1. Fix one encoding, normally UTF-8, in every client. - Key formatting.
"User:42","user:42", and"user:42 "are different keys to a hash function. Decide how keys are built, and build them in one shared function. - Seeds and parameters. Some functions, such as MurmurHash3 and xxHash, take a seed. Every client must use the same one.
- Integer width and signedness. Some libraries return signed 32-bit values, and others return unsigned 64-bit values. Mixing them across languages gives different positions for the same key.
- Truncation. If one client keeps all 128 bits and another keeps the first 32, they place keys in different spaces.
Uniformity: every region gets its share
Uniformity means that each equal-sized slice of the output range receives about the same number of keys. If the hash function sends 40% of keys to the lowest 5% of the range, a placement scheme built on it will overload whichever node owns that region.
Uniformity is about the hash function's effect on your real keys, not on random strings. Real keys are often sequential or structured: key0, key1, order-2026-11-26-0001. A good hash function scrambles such patterns.
You can measure this directly. Divide the output range into equal buckets and count the keys in each. This test compares MD5 with a poor hash that just adds up the bytes of the key:
import hashlib
from collections import Counter
SPACE_BITS = 128
def md5_hash(key):
return int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16)
def sum_hash(key):
return sum(key.encode("utf-8"))
def bucket_counts(hash_fn, keys, buckets=16):
counts = Counter((hash_fn(k) * buckets) >> SPACE_BITS for k in keys)
return [counts.get(b, 0) for b in range(buckets)]
keys = [f"key{i}" for i in range(10000)]
print(bucket_counts(md5_hash, keys))
print(bucket_counts(sum_hash, keys))The expression (h * buckets) >> SPACE_BITS maps a 128-bit value to a bucket number from 0 to 15, by taking its position within the full range. With MD5, each bucket should hold roughly 625 keys, typically between about 550 and 700. With sum_hash, every value is a small number, so all 10,000 keys land in bucket 0 and the other fifteen buckets stay empty.
The second result is an extreme case, but it shows the failure. The sum of bytes ignores the order of characters, and its output range is tiny compared with the space the placement scheme expects.
Mixing: small input changes, large output changes
A related property is the avalanche effect: flipping one bit of the input changes about half the output bits, unpredictably. Without it, similar keys get similar hashes. Then user:1000 through user:1999 could land next to one another in the hash space and load a single node.
Cryptographic and good non-cryptographic hash functions are designed for this. Home-made functions, such as a polynomial rolling sum with a small multiplier, often are not. If you need a quick fix to a poor hash, do not add more arithmetic. Switch to an established function.
Output range
The hash space is the set of integers the function can return. The range should be large compared with the number of things you place in it.
- Collisions. Two different inputs with the same hash are a collision. With a 32-bit hash, the birthday effect makes a collision likely once you have tens of thousands of items. For keys, a collision is harmless: both keys go to the same node, as any two keys might. For virtual node positions on a ring, which a later chapter covers, a collision means two nodes claim one position, and your code needs to handle it.
- Resolution. A ring needs enough distinct positions to place hundreds or thousands of virtual nodes finely. A 32-bit space (about 4.3 billion positions) is usually enough. A 128-bit space makes collisions negligible.
- Arithmetic cost. Python handles 128-bit integers natively. In languages with 64-bit integers, you will probably truncate to 64 bits, which is fine if every client truncates the same way.
Do you need a cryptographic hash?
Usually not. Placement needs determinism and uniformity. It does not need resistance against someone deliberately finding inputs that collide. The table compares common choices.
| Function | Output size | Stable across processes | Notes for placement |
|---|---|---|---|
| Python `hash()` | 64-bit | No (randomized for strings) | Unsuitable |
| Sum of bytes | Small, variable | Yes | Poor uniformity and poor mixing |
| MD5 | 128-bit | Yes | Good uniformity, widely available, slower than modern non-cryptographic hashes |
| SHA-256 | 256-bit | Yes | Good uniformity, slower, more output than placement needs |
| MurmurHash3 | 32 or 128-bit | Yes, with a fixed seed | Fast, designed for hash tables and placement |
| xxHash | 32, 64, or 128-bit | Yes, with a fixed seed | Very fast, good distribution |
| SipHash | 64-bit, keyed | Yes, with a fixed key | Resists attackers who do not know the key |
MD5 is cryptographically broken, meaning attackers can craft collisions. That is irrelevant when you only want an even spread of keys, so the examples in this tutorial use it for convenience: hashlib is in the standard library. Murmur or xxHash is a common production choice because of speed.
The exception is when an attacker controls key names and wants to overload one node, for example by choosing keys that all hash to the same region. A keyed function such as SipHash, with a secret key shared by all clients, makes this hard. A cryptographic hash does not help by itself, because the attacker can compute it too.
Hashing nodes and keys into the same space
Later chapters place both keys and nodes in one hash space. This needs one function to hash both, or at least functions with the same output range. Nodes are hashed from stable identifiers, such as "cache-a" or "10.0.0.7:6379". The identifier matters: if you hash an address that changes when a machine is replaced, the node moves in the space for no reason. Choose a name that survives restarts and replacement.
A node also needs many positions, not one. A common approach is to hash f"{node}#{i}" for i = 0, 1, 2, .... This relies on the mixing property above: "a#0" and "a#1" are nearly identical strings, and they must still land far apart.
Common mistakes
- Using a per-process randomized hash, so clients disagree.
- Taking
h(key) % 100on a hash whose low bits are weak, then finding some buckets unused. Check uniformity on the bits you actually use. - Changing the hash function or seed during a rolling deployment, so old and new clients place keys differently. A change of hash function is as disruptive as resizing the cluster: it can remap nearly every key.
- Mixing key encodings between services written in different languages.
- Testing only on random strings and missing a pattern in real keys.
Exercise
A team runs three cache clients in Python, Go, and Java. The Python client uses the built-in hash(key) and the other two use MurmurHash3 with seed 0. Name two separate problems with this setup and the fix for each.
Show answer
First, Python's built-in hash() is randomized per process, so it gives different values on every restart and differs from MurmurHash3, which means the Python client places keys on nodes the other clients do not use. Second, even with the same algorithm, the clients must agree on the key encoding (UTF-8), seed, output width, and signedness, or the Go and Java values can still differ. The fix is to use one specified hash algorithm in all three clients, with a fixed seed and UTF-8 bytes, and to verify it with a shared test file of keys and expected hash values.
Exercise
Run the bucket count from this chapter on 10,000 keys of the form key{i}, using md5_hash. Then write a second hash function that returns only the first 8 bits of the MD5 value shifted into the top of the 128-bit range, and explain what the bucket counts would look like with 16 buckets.
Show answer
Use (md5_hash(k) >> 120) << 120. This keeps the top 8 bits and sets the rest to zero. With 16 buckets, the bucket number depends only on the top 4 bits, so the counts stay close to uniform, roughly 625 each. The loss shows up at finer resolution: only 256 distinct values remain, so any placement scheme needing more than 256 distinct positions would see many collisions. Uniform bucket counts at one resolution do not guarantee enough resolution for a ring with many virtual nodes.