Sub topic 1
Why we need to spread keys across nodes
Consistent hashing exists to answer a question that comes up as soon as one machine can no longer hold your data: which machine should store this key? This chapter sets up that question. It explains why spreading keys is necessary, what a good answer must provide, and how to measure whether a placement scheme works. Later chapters build the hash ring on top of this groundwork.
Prerequisites
This chapter assumes you already know the following:
- What a hash function does and how a hash table uses it to map keys to buckets.
- What a cache, a shard, and a replica are in a distributed system.
- How to read simple Python code, including dictionaries, list comprehensions, and
collections.Counter. - How binary search works. You won't need it until later chapters, but they build on it.
You do not need to know anything about consistent hashing itself.
The problem: one machine is not enough
A single server has hard limits:
- Memory and disk. A cache holding 500 GB of hot data does not fit on a machine with 64 GB of RAM.
- Throughput. One machine can serve a limited number of requests per second. A popular service can exceed that limit even when the data fits.
- Availability. If the only machine fails, every request fails with it.
The usual fix is horizontal scaling. You run many machines and give each a share of the data. Each machine is called a node. The data is a set of keys, such as user IDs, session tokens, or URLs, each with an associated value. Splitting the keys among nodes is called partitioning. The pieces are often called shards.
Partitioning raises a question that a single machine never had to answer. When a client wants the value for user:8841, which node holds it?
flowchart LR
C[Client request for key] --> P{Placement function}
P --> N1[Node A]
P --> N2[Node B]
P --> N3[Node C]
P --> N4[Node D]The diagram above is a sketch, not a rendered diagram block. Here is the proper version:
The box labeled "placement function" is the subject of this tutorial. Every reader and writer must agree on its answer for every key. If a writer stores user:8841 on node B and a reader looks for it on node C, the read misses even though the data exists.
Keys, nodes, and placement
Define the pieces precisely:
- A key is the identifier you look up, usually a string.
- A node is a server, process, or cache instance that stores values.
- A placement function takes a key and the current set of nodes and returns the node that owns the key.
Written as a type, the placement function looks like this:
def place(key: str, nodes: list[str]) -> str:
...The set of nodes is an input, not a constant. This matters because real clusters change. You add nodes for growth, remove nodes for savings, and lose nodes to crashes. A placement scheme is only useful if it keeps working while that set changes.
What a good placement scheme provides
Judge any scheme against these requirements:
- Determinism. The same key and the same node set must always give the same node. Different clients must agree without talking to each other.
- Balance. Each node should hold close to its fair share of keys and traffic. If one node holds 40% of the keys in a four-node cluster, it runs out of memory or CPU first, and the other nodes' capacity goes to waste.
- Stability under change. When a node joins or leaves, as few keys as possible should change owner. A key that changes owner must be moved or refetched, and for a cache, a moved key is a cache miss.
- Cheap lookup. Finding a key's node should take little time and little memory, ideally without a network call.
- No single point of failure. The scheme should not depend on one coordinator that every request must visit.
The third requirement is the one most naive schemes fail. The rest of this tutorial exists because of it.
Option 1: a central directory
The most direct approach is a lookup table. A directory service records which node owns each key.
class Directory:
def __init__(self, nodes):
self.nodes = list(nodes)
self.table = {}
self.counts = {node: 0 for node in nodes}
def place(self, key):
if key not in self.table:
node = min(self.nodes, key=lambda n: self.counts[n])
self.table[key] = node
self.counts[node] += 1
return self.table[key]
directory = Directory(["a", "b", "c", "d"])
for i in range(10):
print(f"user:{i}", directory.place(f"user:{i}"))This scheme has real strengths. Balance is nearly perfect, because each new key goes to the least-loaded node. When a node joins, you decide exactly which keys to move, so movement is as small as you choose.
It also has serious costs:
- The table has one entry per key. With a billion keys, the directory itself becomes a large data store that needs partitioning.
- Every lookup needs the table. Either every client holds a copy that must stay in sync, or every request makes an extra network hop to the directory.
- The directory is a single point of failure unless you replicate it, and then you have a consistency problem to solve.
Some systems accept these costs. Metadata-heavy systems, such as distributed file systems with a master node, do exactly this. Many caches and key-value stores want something lighter.
Option 2: compute the placement from the key
The alternative is to calculate the node from the key with no stored table. Any client holding the list of nodes can compute the answer locally. This gives determinism, cheap lookup, and no central coordinator.
The tool for doing this is a hash function, which turns a key into a large number that looks random. A simple version picks a node by dividing that number by the node count and taking the remainder:
import hashlib
from collections import Counter
NODES = ["a", "b", "c", "d"]
def stable_hash(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
def place(key, nodes):
return nodes[stable_hash(key) % len(nodes)]
keys = [f"user:{i}" for i in range(10000)]
load = Counter(place(k, NODES) for k in keys)
mean = len(keys) / len(NODES)
for node in NODES:
print(node, load[node])
print("max/mean:", max(load.values()) / mean)Running this prints a count for each node. Each count should be close to 2500, and the max/mean ratio should be just above 1.0. The hash spreads sequential-looking keys like user:0, user:1, and so on almost evenly.
Two details in this code matter:
- It uses
hashlib.md5and not Python's built-inhash(). Since Python 3.3,hash()on strings is randomized for each process unlessPYTHONHASHSEEDis set. Two clients runninghash("user:1")would disagree, which breaks determinism. MD5 is used here only for its stable, well-mixed output, not for security. - The result depends on
len(nodes). That dependency is the weakness explained in the chapter on modulo hashing. Changing the number of nodes changes the answer for most keys.
The next chapters cover which properties the hash function needs, then how modulo placement behaves when the cluster resizes.
Measuring a placement scheme
Two numbers let you compare schemes without arguing from intuition.
Load skew measures balance. Count the keys on each node and divide the largest count by the average, as the code above does. A value of 1.0 is perfect. A value of 1.5 means the busiest node carries 50% more than its fair share. Because that node sets the limit on how much the cluster can handle, skew wastes capacity directly.
Movement fraction measures stability. Record the owner of every key before a change, apply the change, record the owners again, and compute the share of keys whose owner differs. For a change from N nodes to N+1 nodes, there is a theoretical minimum. A new node should own about 1/(N+1) of the keys, so at least that share must move. Going from 4 to 5 nodes, the ideal is about 20%. A scheme that moves 80% does four times more work than necessary.
| Metric | What it measures | Ideal value |
|---|---|---|
| Load skew (max / mean) | Balance across nodes | Close to 1.0 |
| Movement fraction | Keys that change owner after a node is added | About 1/(N+1) |
| Lookup cost | Time and memory per lookup | Small and constant, or logarithmic |
Keep these three measures in mind. Each later technique in the tutorial improves one of them, often at some cost to another.
Why movement matters in practice
Consider a cache cluster in front of a database. The cache absorbs most reads, so the database is sized for the misses and not for the full read load. Suppose you add one cache node and 80% of keys change owner. For clients, 80% of cached entries are now stored on the wrong node, so those lookups miss. All of those requests fall through to the database at once.
This is a cache stampede caused by resizing, and it can take down the database that the cache was protecting. Adding capacity made the system fail, which is the opposite of the intent.
For a persistent store, the cost is data transfer. Moving 80% of a multi-terabyte data set across the network takes hours and competes with normal traffic. If the scheme moves only about 20%, the same change is much cheaper.
Other things that skew load
Even a perfect hash cannot fix some imbalance:
- Hot keys. If one key receives a large share of requests, such as a viral post, the node holding that key is overloaded no matter how evenly keys are spread. Hashing balances key counts, not request counts.
- Uneven value sizes. Ten keys with 1 GB values can unbalance a node more than a million tiny keys.
- Uneven node capacity. If one node has twice the memory of the others, an equal split under-uses it. The chapter on weighted nodes returns to this.
This tutorial focuses on spreading keys evenly and moving few of them when the node set changes. Hot keys usually need extra measures such as replicating the hot key or caching it in front of the cluster.
What comes next
The rest of the tutorial answers one design question: how can a placement function be computed locally, as in Option 2, yet stay stable when nodes join and leave? The following chapters cover:
- The properties we need from the hash function.
- Why modulo placement moves most keys on resize.
- The hash ring, which fixes the movement problem.
- Virtual nodes, which fix the balance problem the ring introduces.
By the end you will have a working ring implementation and know when alternatives are a better fit.
Exercises
Exercise
A four-node cluster uses a hash-based placement function. You count keys per node and get 3000, 2500, 2500, and 2000 for 10000 keys. What is the load skew (max / mean), and what does it tell you?
Show answer
The mean is 10000 / 4 = 2500. The maximum is 3000, so the skew is 3000 / 2500 = 1.2. The busiest node carries 20% more than its fair share. Because that node reaches its capacity limit first, the cluster can only be loaded to about 1 / 1.2, or roughly 83%, of its total capacity before one node is full.
Exercise
A cluster grows from 9 nodes to 10. What is the minimum fraction of keys that must change owner, and why can a scheme not do better than that?
Show answer
The minimum is 1/10, or 10%. After the change the new node must hold its fair share of the keys, which is about 1/10 of the total. Those keys can only come from the existing nodes, so at least that many must move. A scheme can move more than 10%, but it cannot move fewer and still stay balanced.
Exercise
Why does the placement example use hashlib.md5 and not Python's built-in hash() for string keys?
Show answer
Python randomizes hash() for strings per process, unless PYTHONHASHSEED is fixed. Two clients, or one client after a restart, would compute different values for the same key and so pick different nodes. The placement function must be deterministic across processes and machines, so it needs a stable hash such as MD5.