Algorithms · Huge scale
Consistent hashing
The ring that lets Discord add servers without chaos. Add one computer and almost nothing moves. That’s consistent hashing.
The problem
Discord has a huge number of guilds (what you call servers), and each guild's live state has to be handled by exactly one process at a time. Every message, join and presence update for that guild must be routed to its one owner.
Then the fleet changes: you add a machine for growth, or one dies. If every guild suddenly needs a new owner, that's a stampede of handoffs. Discord has written about routing guilds to processes with a hash ring to avoid exactly that.
The obvious way
The first idea is hash(key) % number_of_servers. It's simple and spreads keys evenly. But the answer depends on the server count, so going from 4 to 5 servers changes the divisor for every key. Most keys land on a different server, and each one has to move.
The clever idea
Picture a clock face. Hash each server to a spot on the clock. Hash each key to a spot too. A key belongs to the first server you meet walking clockwise from it, like a bus stop served by the next bus that arrives.
Add a new bus and it takes over only the stops just before it. Everyone else keeps their bus. This is consistent hashing, popularised by the 1997 Karger et al. paper and used in Amazon's Dynamo paper (2007). Dynamo also uses virtual nodes: each server gets many spots on the ring so the load evens out.
How the code does it
Both approaches share the fingerprint function on line 4. The obvious way is one line: modulo_owner. The ring is a sorted list of (position, server) points built by build_ring. To find an owner, ring_owner binary-searches that list for the first point at or after the key.
The payoff is these two counts. With 4 servers becoming 5, expect modulo to move most keys, while the ring should move only roughly the share the new server takes over, around one fifth. The last bars show that with 50 virtual nodes each, the five servers end up with similar loads.
Trade-offs
The ring costs memory (a list of points, many per server) and a little lookup work instead of one %. Balance depends on how many virtual nodes you use: try 1 and watch the bars get lopsided. And moved keys still need real handoff work. The ring just keeps that small. If your server count never changes, plain modulo is simpler and fine.
Where else you'll see it
Distributed caches, databases and load balancers use the same trick; Dynamo is the famous example. To read a production-grade version, Discord open-sourced an Elixir hash ring library: github.com/discord/ex_hash_ring.
What does % len(ring) on line 15 do?
- Wraps keys past the last point back to the first
- Removes duplicate servers from the ring
- Picks a random server for the key
Show the answer
Wraps keys past the last point back to the first. bisect returns len(ring) when the key is past the last point. The modulo turns that into index 0, closing the circle.
- Change vnodes=50 to 1
- Add "F" to new
- Change range(1000) to range(5000)
The code
Python, with what each line means beside it. It compares the clever way with hash(key) % number_of_servers.
import hashlibLoad the tool that makes fingerprints.from bisect import bisectLoad fast sorted-list lookup. def h(text):Define a function turning text into a number. return int(hashlib.md5(text.encode()).hexdigest()[:8], 16)Fingerprint the text; keep a big number. def modulo_owner(key, servers):Define the obvious way to pick a server. return servers[h(key) % len(servers)]Number divided by server count; remainder picks. def build_ring(servers, vnodes=50):Define building the ring, with 50 spots each. points = [(h(f"{s}#{v}"), s) for s in servers for v in range(vnodes)]Hash every server-spot onto the circle. return sorted(points)Sort spots around the circle. def ring_owner(key, ring):Define how the ring picks a server. i = bisect(ring, (h(key), "")) % len(ring)Find the next spot clockwise, wrapping around. return ring[i][1]Return the server at that spot. keys = [f"guild{i}" for i in range(1000)]Make 1000 fake guild names.old = ["A", "B", "C", "D"]Start with four servers.new = old + ["E"]Add a fifth server.ring_old, ring_new = build_ring(old), build_ring(new)Build a ring for each lineup. mod_moved = sum(modulo_owner(k, old) != modulo_owner(k, new) for k in keys)Count keys whose modulo owner changed.ring_moved = sum(ring_owner(k, ring_old) != ring_owner(k, ring_new) for k in keys)Count keys whose ring owner changed.print("modulo moved:", mod_moved, "| ring moved:", ring_moved)Print both counts.show([mod_moved, ring_moved], "keys moved: modulo vs ring")Draw both counts as bars. load = {s: 0 for s in new}Start each server's key count at zero.for k in keys:Go through every key. load[ring_owner(k, ring_new)] += 1Add one to its owner's count.show(list(load.values()), "keys per server (A to E)")Draw keys per server as bars.- the fragile part line 8len(servers) is in the formula, so changing the server count reshuffles almost every key.
- virtual nodes line 11Each server is hashed 50 times with a different suffix, giving it 50 scattered spots on the ring.
- clockwise + wrap line 15bisect finds the next point after the key. The modulo wraps past the last point back to the first.
- the experiment lines 23–24Same keys, same before-and-after servers. Only the placement rule differs, so the counts are a fair comparison.
Read more
- github.com: Consistent hashing
- The real code: discord/ex_hash_ring
- Ask Bento: What happens when a server is removed?
- Ask Bento: How many virtual nodes are enough?
- Ask Bento: How does binary search work?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.