Implementing and measuring a hash ring
Build a hash ring with virtual nodes and replica placement in standard-library Python, then measure its load spread and key movement against hash mod N, test the guarantees it makes, and see what three replicas change.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Check Python and create the folder
- Step 2: Write the ring
- Step 3: Try it on a tiny ring
- Step 4: Measure balance and key movement
- Step 5: Test the guarantees
- Step 6: See what replicas change
- Check your understanding
- Apply it
- Review prompt
Lessons of Consistent Hashing
- Why hash mod N breaks when the cluster changes Concept · 15 min
- The ring, virtual nodes and replica placement Concept · 20 min
- Implementing and measuring a hash ring Lab · 30 min
- Rendezvous and jump hashing Concept · 15 min
- Rings in practice: cache clients and Dynamo-style stores Worked example · 20 min
- Consistent hashing check Knowledge check · 6 questions
What you will learn
- Implement a hash ring with virtual nodes and measure load balance and key movement when a node is added or removed.
01. Goal and setup
In this lab you implement the ring from the previous lesson and measure it. By the end you will have numbers for three questions: how evenly does the ring spread keys for 1 to 200 virtual nodes per node, how many keys move when an eleventh node joins or one leaves, and how replicas change that count. You will also check, with code, that the ring keeps its promises and that hash % N does not.
You need Python 3.10 or newer; the lab was run with Python 3.12.13 on Linux. Everything uses the standard library, so there is nothing to install. The terminal blocks use bash, as on Linux and macOS; on Windows, run them in WSL or Git Bash, or save the body of each python3 - <<'EOF' block as a .py file and run it with python. The inputs are fixed: keys user:0 to user:99999, nodes node-0 to node-9, and a BLAKE2b hash. Your numbers should therefore match the expected output exactly. Each script runs in a few seconds.
02. Step 1: Check Python and create the folder
python3 --version
mkdir ring-lab
cd ring-labPython 3.12.1303. Step 2: Write the ring
Save the code below as ring.py in ring-lab. It has four parts:
h64turns any text into a stable 64-bit number. It never uses Python'shash(), which changes between processes.ModNis the modulo scheme from the first lesson, kept for comparison.HashRinggives each nodevnodestokens namednode#0,node#1and so on, and keeps them in one sorted list.bisect.insortinserts each token in order, andremovefilters a node's tokens out.walkyields the owners of the tokens clockwise from a key's position. The%wraps the walk past the last token back to the first.ownertakes the first step of the walk, andreplicaskeeps walking, skipping nodes already chosen, until it has r distinct nodes.
Lookups build a small generator for each key. That keeps the code short; a production ring would return the owner directly from the binary search and would rebuild its token list in one go.
"""A hash ring with virtual nodes, and hash mod N to compare it with (stdlib only)."""
import bisect
import hashlib
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")
class ModN:
"""Owner = nodes[hash % N]. Balanced, but changing N moves most keys."""
def __init__(self, nodes: list[str]):
self.nodes = list(nodes)
def owner(self, key: str) -> str:
return self.nodes[h64(key) % len(self.nodes)]
class HashRing:
"""Each node puts `vnodes` tokens on a 64-bit ring. A key belongs to the
first token at or after its hash, wrapping past the top back to the start."""
def __init__(self, nodes: list[str], vnodes: int = 100):
self.vnodes = vnodes
self.tokens: list[int] = [] # sorted token positions
self.token_owner: dict[int, str] = {}
for node in nodes:
self.add(node)
def add(self, node: str) -> None:
for i in range(self.vnodes):
token = h64(f"{node}#{i}") # depends on the node's name only
self.token_owner[token] = node
bisect.insort(self.tokens, token)
def remove(self, node: str) -> None:
self.tokens = [t for t in self.tokens if self.token_owner[t] != node]
self.token_owner = {t: self.token_owner[t] for t in self.tokens}
def walk(self, key: str):
"""Yield token owners clockwise from the key's position (with repeats)."""
start = bisect.bisect_left(self.tokens, h64(key))
for step in range(len(self.tokens)):
# % wraps past the last token back to the first one
yield self.token_owner[self.tokens[(start + step) % len(self.tokens)]]
def owner(self, key: str) -> str:
return next(self.walk(key))
def replicas(self, key: str, r: int) -> list[str]:
"""The first r distinct nodes clockwise: skip tokens of nodes already chosen."""
chosen: list[str] = []
for node in self.walk(key):
if node not in chosen:
chosen.append(node)
if len(chosen) == r:
break
return chosenCheck that the file imports and builds a ring: two nodes with three tokens each should give six tokens, kept in sorted order.
python3 -c "import ring; t = ring.HashRing(['a', 'b'], 3).tokens
print(len(t), t == sorted(t))"6 True04. Step 3: Try it on a tiny ring
Before measuring 100,000 keys, check the logic on a ring small enough to follow by hand: three nodes with two tokens each. The positions are printed as a fraction of the ring, from 0.0 to 1.0.
python3 - <<'EOF'
from ring import HashRing, h64
ring = HashRing(["node-a", "node-b", "node-c"], vnodes=2)
for token in ring.tokens: # positions shown as a fraction of the ring
print(f"token at {token / 2**64:.3f} -> {ring.token_owner[token]}")
for key in ["user:1", "user:2", "user:3", "user:7"]:
print(f"{key} at {h64(key) / 2**64:.3f} -> {ring.replicas(key, 2)}")
EOFtoken at 0.105 -> node-a
token at 0.396 -> node-c
token at 0.575 -> node-c
token at 0.586 -> node-b
token at 0.825 -> node-b
token at 0.999 -> node-a
user:1 at 0.830 -> ['node-a', 'node-c']
user:2 at 0.334 -> ['node-c', 'node-b']
user:3 at 0.131 -> ['node-c', 'node-b']
user:7 at 0.604 -> ['node-b', 'node-a']Check two keys by hand. user:2 sits at 0.334, so its first token is 0.396 (node-c). The next token, 0.575, is also node-c, so the walk skips it and takes 0.586 (node-b) as the second replica. user:1 sits at 0.830; its first token is 0.999 (node-a), and then the walk wraps to 0.105, which is node-a again, so it is skipped too and node-c at 0.396 becomes the second replica. If your output differs, compare ring.py with the listing above before going on.
05. Step 4: Measure balance and key movement
Save measure.py next to ring.py. For modulo and for rings with 1, 10, 50 and 200 tokens per node it places the keys, reports the standard deviation of the per-node counts (in keys and as a percentage of the mean of 10,000), the busiest node's load divided by the mean, and node-3's share. Then it builds the same scheme with node-10 added, and again with node-3 removed, and counts the keys whose owner changed. An optional argument sets the number of keys.
"""Balance and key movement of hash mod N and of a ring with 1 to 200 vnodes."""
import statistics
import sys
from collections import Counter
from ring import HashRing, ModN
N_KEYS = int(sys.argv[1]) if len(sys.argv) > 1 else 100_000
KEYS = [f"user:{i}" for i in range(N_KEYS)]
NODES = [f"node-{i}" for i in range(10)]
def owners(router) -> list[str]:
return [router.owner(key) for key in KEYS]
def moved(before: list[str], after: list[str]) -> float:
return sum(a != b for a, b in zip(before, after)) / N_KEYS
print(f"{N_KEYS:,} keys on {len(NODES)} nodes, then add node-10 or remove node-3")
print(f"{'scheme':<10}{'std dev':>9}{'(%)':>7}{'max/mean':>10}{'node-3 had':>12}"
f"{'moved on add':>14}{'moved on remove':>17}")
for vnodes in (None, 1, 10, 50, 200):
if vnodes is None:
name = "mod N"
router = ModN(NODES)
grown = ModN(NODES + ["node-10"])
shrunk = ModN([n for n in NODES if n != "node-3"])
else:
name = f"ring v={vnodes}"
router = HashRing(NODES, vnodes)
grown = HashRing(NODES, vnodes)
grown.add("node-10")
shrunk = HashRing(NODES, vnodes)
shrunk.remove("node-3")
before = owners(router)
load = Counter(before)
counts = [load[n] for n in NODES]
mean = N_KEYS / len(NODES)
sd = statistics.pstdev(counts)
print(f"{name:<10}{sd:>9,.0f}{sd / mean:>7.1%}{max(counts) / mean:>10.2f}"
f"{load['node-3'] / N_KEYS:>12.1%}{moved(before, owners(grown)):>14.1%}"
f"{moved(before, owners(shrunk)):>17.1%}")
print(f"{'ideal':<10}{0:>9}{0:>7.1%}{1:>10.2f}{1 / 10:>12.1%}"
f"{1 / 11:>14.1%}{1 / 10:>17.1%}")python3 measure.py100,000 keys on 10 nodes, then add node-10 or remove node-3
scheme std dev (%) max/mean node-3 had moved on add moved on remove
mod N 59 0.6% 1.01 10.0% 90.9% 90.1%
ring v=1 10,124 101.2% 3.72 6.2% 0.3% 6.2%
ring v=10 2,597 26.0% 1.51 9.0% 7.5% 9.0%
ring v=50 1,152 11.5% 1.14 9.9% 11.5% 9.9%
ring v=200 843 8.4% 1.17 11.7% 8.9% 11.7%
ideal 0 0.0% 1.00 10.0% 9.1% 10.0%Read the table one column at a time.
Modulo has almost no spread, a standard deviation of 59 keys, but it moves about 90% of the keys on either change. A ring with one token per node is the opposite: one node carries 3.72 times its fair share. Its "moved on add" figure of 0.3% looks excellent until you see why: node-10's single token landed in a tiny arc, so the new node took almost nothing and relieved almost no one.
On a ring, "moved on remove" always equals "node-3 had". Only the leaving node's keys move, so the cost of a removal is whatever that node held, 6.2% to 11.7% here, not a fixed 10%. Likewise, "moved on add" is exactly the share that node-10 ends up owning, from 0.3% to 11.5%. Neither matches the ideal line (10% and 9.1%) exactly, because the ring's balance is random.
The standard deviation falls from 101% of the mean to 26%, 11.5% and 8.4% as tokens go from 1 to 10, 50 and 200. A square-root rule predicts about 100%, 32%, 14% and 7%. The max/mean column is noisier, which is why 200 tokens show 1.17 against 1.14 for 50: the busiest of only ten nodes is an extreme value, and extremes vary more than averages.
06. Step 5: Test the guarantees
Numbers in a table can hide a bug, so test the properties directly. check_ring.py builds rings with 50 tokens per node and checks four things: on an add every moved key went to the new node; on a removal every moved key came from the removed node; the owner of every key is the same when the node list is given in reverse order; and a key that hashes past the last token belongs to the first token's node. The last line counts the same kind of moves for modulo.
"""Check the properties a ring promises, and show that mod N breaks them."""
from ring import HashRing, ModN, h64
KEYS = [f"user:{i}" for i in range(100_000)]
NODES = [f"node-{i}" for i in range(10)]
def moves(before, after) -> list[tuple[str, str]]:
"""(old owner, new owner) for every key whose owner changed."""
pairs = ((before.owner(k), after.owner(k)) for k in KEYS)
return [(old, new) for old, new in pairs if old != new]
ring = HashRing(NODES, vnodes=50)
grown = HashRing(NODES, vnodes=50)
grown.add("node-10")
added = moves(ring, grown)
print(f"add node-10: {len(added):,} keys moved;",
f"all to node-10: {all(new == 'node-10' for _, new in added)}")
shrunk = HashRing(NODES, vnodes=50)
shrunk.remove("node-3")
removed = moves(ring, shrunk)
print(f"remove node-3: {len(removed):,} keys moved;",
f"all from node-3: {all(old == 'node-3' for old, _ in removed)}")
reverse = HashRing(list(reversed(NODES)), vnodes=50)
print("same owners when the node list is reversed:", not moves(ring, reverse))
top = max(ring.tokens)
key = next(k for k in KEYS if h64(k) > top) # hashes past the last token
print(f"{key} hashes past the last token; owner is the first token's node:",
ring.owner(key) == ring.token_owner[ring.tokens[0]])
mod_moves = moves(ModN(NODES), ModN(NODES + ["node-10"]))
between_old = sum(new != "node-10" for _, new in mod_moves)
print(f"mod N, add node-10: {len(mod_moves):,} keys moved;",
f"{between_old:,} of them between old nodes")python3 check_ring.pyadd node-10: 11,489 keys moved; all to node-10: True
remove node-3: 9,949 keys moved; all from node-3: True
same owners when the node list is reversed: True
user:433 hashes past the last token; owner is the first token's node: True
mod N, add node-10: 90,890 keys moved; 81,800 of them between old nodesAll four ring checks print True. Modulo fails the first one badly: of the 90,890 keys it moves when node-10 joins, 81,800 go from one old node to another. Keep check_ring.py. Whenever you change the ring, for example to add weights, run it again; if a check turns False, the change has broken a guarantee that the measurements alone might not reveal.
07. Step 6: See what replicas change
replicas.py keeps three copies of every key with ring.replicas(key, 3) and compares the replica sets before and after node-10 joins. It also counts how often a naive walk, which simply takes the next three tokens, would put two copies on one node.
"""Three replicas per key: what changes when node-10 joins?"""
from itertools import islice
from ring import HashRing
KEYS = [f"user:{i}" for i in range(100_000)]
NODES = [f"node-{i}" for i in range(10)]
R = 3
ring = HashRing(NODES, vnodes=50)
grown = HashRing(NODES, vnodes=50)
grown.add("node-10")
primary_moved = sets_changed = new_copies = 0
for key in KEYS:
old, new = ring.replicas(key, R), grown.replicas(key, R)
primary_moved += old[0] != new[0]
sets_changed += set(old) != set(new)
new_copies += len(set(new) - set(old)) # copies that must be streamed
print(f"keys whose primary moved: {primary_moved / len(KEYS):.1%}")
print(f"keys whose replica set changed: {sets_changed / len(KEYS):.1%}")
print(f"copies streamed, of all {R * len(KEYS):,}: {new_copies / (R * len(KEYS)):.1%}")
# A naive walk takes the next R tokens, even when two belong to one node.
doubled = sum(len(set(islice(ring.walk(k), R))) < R for k in KEYS)
print(f"naive walk, keys with a node twice: {doubled / len(KEYS):.1%}")python3 replicas.pykeys whose primary moved: 11.5%
keys whose replica set changed: 27.7%
copies streamed, of all 300,000: 9.2%
naive walk, keys with a node twice: 28.5%The first owner changes for 11.5% of keys, but 27.7% of keys get a different replica set, close to 3/11. Each of those keys gains a copy on node-10 and loses one elsewhere. The data that must stream to node-10 is 9.2% of all copies, close to 1/11. So "how much moves" depends on what you count: first owners, keys affected, or bytes copied. State which one you mean. Finally, the naive walk would put two copies of 28.5% of the keys on the same machine, which is why the walk must skip nodes it has already chosen.
08. Check your understanding
09. Apply it
Complete the practice task for this skill with the code you now have:
- Run
python3 measure.py 1000000and record, for modulo and for 1, 50 and 200 tokens per node, the standard deviation and the share of keys moved when node-10 joins. - Add 800 tokens to the list in
measure.pyand check your answer to the last practice question. - Give
HashRinga weight per node (tokens = weight × vnodes), give node-0 a weight of 2, and confirm withcheck_ring.pythat the guarantees still hold. - Write a short report: a table of your results and three sentences on which token count you would choose, and why.
Then read Rendezvous and jump hashing, which compares the ring with two schemes that need no token table.
10. Review prompt
Without looking at your output, explain why a ring with one token per node can move very few keys on a join and yet be a poor choice, why the cost of removing a node is that node's own share, and why three replicas make about three times as many keys change their replica set while the data copied stays near 1/(N + 1).
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.