Consistent hashing
medium 28 minConsistent hashing puts keys and machines on one circle.
See it run
Walk the ring: find an owner, add and remove a node, even the shares with virtual nodes, and compare with modulo.
Operations
Find the owner
Hash the key and take the first node clockwise.
Step 1 of 5
Three nodes on the ring
positions, in degrees
N1 45 · N2 135 · N3 225
sorted tokens
45 N1 · 135 N2 · 225 N3
Each node is hashed to a position: N1 at 45, N2 at 135, N3 at 225 degrees.
Step 1: Three nodes on the ring
def get_node(key): pos = hash_position(key) i = bisect_left(tokens, pos) if i == len(tokens): i = 0 # wrap around return owner[tokens[i]]- Keys moved
- None
- Lookup
- log2 T steps
- Ask every node
- N messages
The last step, wrapping to the first token, is what makes it a ring and not a line.
In the real world
The same consistent hashing doing real jobs. Pick one and step through it.
A shop adds a cache server before a sale. The database can take 3,000 reads a second.
Step 1 of 4
Today
- Database load
- 33%
10,000 reads a second, 90% answered by the cache. The database gets 1,000.
Step 1: Today
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Using a salted built-in hash
criticalPython salts the hash of strings per process, so two servers place the same key on different nodes.
Wrongpos = hash(key) % 2**32Rightpos = int.from_bytes(md5(key.encode()).digest()[:4], "big")One token per node
majorShares differ widely and a crash doubles the load of one neighbour.
Wrongring.add("N1")Rightfor i in range(150): ring.add(f"N1#{i}", owner="N1")Counting tokens as copies
criticalTwo neighbouring tokens may be the same machine. Both copies die together.
Wrongcopies = ring.next_tokens(key, 3)Rightcopies = ring.next_distinct_machines(key, 3)Deleting a token that another node owns
minorTwo tokens can hash to the same position. Removing one node must not remove the other's token.
Wrongdel owner[position(f"{node}#{i}")]Rightfor p in owned.pop(node): # only what it really owns del owner[p]
Interview tips
How to explain it
- Keys and nodes on one circle.
- First node clockwise owns the key.
- A change moves one part in N.
Memory trick: RING
- Round and Incremental.
- Nodes with virtual positions.
- Go clockwise.
Reach for it when
- Nodes that hold data come and go.
- A cache must survive a resize.
- Users should stick to a server.
Look elsewhere when
- You need range scans.
- N never changes.
- One key is the whole problem.