TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About · Labs · Cheat sheets · Learning paths

All concepts · distributed systems · caching · sharding

Consistent hashing

A way to spread keys across servers so that adding or removing a server moves only a small share of keys. Servers and keys are hashed onto a ring, and each key belongs to the next server clockwise.

9 min4 animations

📚 Builds on📕 Sharding

🖨️ Cheat sheet

Counting off seats

Guests have numbered tickets, and you seat them by dividing by the number of tables and using the remainder. It works, until you add a table. Now you divide by a different number and almost everyone is told to get up and move.

Why modulo breaks

Spreading keys over N cache or database servers with hash(key) % N is even and simple. But change N, by adding a server or losing one, and most keys map to a different server. For a cache, that means a sudden flood of misses hitting the database; for a database, moving most of the data.

Counting off seats2 steps
👥Guests🍽️Table 0🍽️Table 1🍽️Table 2
Press play and watch it happen!

The round table

Instead, everyone sits around a round table. Each plate is put down at a spot on the table and slides clockwise to the next person. When a new person sits down, they only take the plates from the gap just before them. Everyone else keeps theirs.

The hash ring

Hash both servers and keys onto the same circular range (say 0 to 2³² − 1). A key belongs to the first server at or after its position, going clockwise. Adding a server takes over only the keys between it and its predecessor; removing one hands its keys to its successor. On average only 1/N of keys move.

Finding the owner is a binary search over sorted server positions, so lookups stay fast.

The round table3 steps
👩Ana👨Ben🧑Cy🍰A plate of cake
Press play and watch it happen!

Several seats each

With one seat each, someone might sit next to a big empty stretch and get far more plates. So everyone takes many seats spread around the table. The gaps even out, and when someone leaves, their plates are shared by everyone.

Virtual nodes

Each physical server is placed at many points on the ring (virtual nodes). Many small ranges average out to an even share, a failed server's load spreads across all the others, and more powerful servers can simply get more points.

Used by Cassandra, DynamoDB, Riak, memcached clients and many load balancers. Redis Cluster uses a related idea: 16,384 fixed hash slots assigned to nodes, moved slot by slot.

Several seats each3 steps
👩Ana👨Ben🧑Cy⭕Round table
Press play and watch it happen!

When the table goes wrong

One day Ana leaves in a hurry. All her plates slide to Ben, the next person clockwise, and Ben suddenly has twice as much to carry. Worse, the plates that arrive are empty: the cake is still back in the pantry, so Ben keeps running to fetch it, and the pantry gets swamped. The fix is many seats each, so Ana's plates are shared out, and a bit of patience while his plates fill up again.

Some trouble no seating plan can fix. If everyone wants the same slice of cake, whoever holds that slice is run off their feet. The answer is to bake extra copies of that one slice and put them at several seats.

And people may not all hear that someone sat down or left at the same moment. A waiter with an old seating chart carries a plate to the wrong person. Letting everyone see the same chart quickly keeps this rare. When a new guest sits down, the plates in their gap really have to be carried over, which takes time.

What can go wrong

  • A node dies and its whole range lands on one neighbour. With a single point per node, the failed node's keys all go to its clockwise successor, which now carries roughly double the load. Because those keys were cached on the dead node, the successor starts cold: a burst of cache misses falls through to the database (a stampede), which you see as a spike in miss rate and database load or latency. Mitigate with many virtual nodes (the dead node's range is spread over all the others, as in Virtual nodes above), request coalescing so one miss reloads a key, jittered expiry, and database capacity to survive a cold node. See distributed caching.
  • Uneven load. Random positions with too few virtual nodes give some nodes much larger ranges. You see one node with higher CPU, memory or eviction rate than its peers. Add more virtual nodes, or give bigger machines more.
  • Hot keys. A ring spreads keys, not requests. One very popular key always hashes to one node, however many virtual nodes exist. You see a single node saturated while others idle. Fix it outside the ring: a small local cache in the client, or replicate the key under several derived names (key#1, key#2) and read a random one.
  • Clients disagree about the ring. Each client computes the owner from its own list of nodes. While a membership change is still spreading, one client sends a key to the old owner and another to the new one. Reads miss, or a write lands on a node that is no longer the owner and is later lost or served stale. Mitigate with a shared source of membership (a service registry or gossip), short cache TTLs, versioned membership, and treating the cache as disposable.
  • Data has to move when nodes join. A new node owns its ranges but starts empty (a cache) or must receive them (a database). Reads for those keys miss, or are slow, until the data is copied or refilled; streaming it also competes with live traffic. Add nodes one at a time, throttle the transfer, and warm the cache before taking traffic.
ChoiceYou gainYou pay
More virtual nodesEven load and a failed node's load spread widelyBigger ring to store and search, more ranges to stream and track, more membership state
Fewer virtual nodesA small, simple ringUneven ranges and one neighbour absorbing a failure
Replicate along the ring (next nodes clockwise hold copies)A failure leaves warm copies, so fewer misses and much less risk of data lossMore storage and write work, plus copies that can disagree
No replicationSimplest and cheapest, fine for a rebuildable cacheA dead node means cold misses or lost data
Bounded-load variant (a server takes at most a set percentage of the average concurrent requests; the excess goes to the next server)Caps hot spots and uneven load, e.g. HAProxy hash-balance-factorA request may go to a different node than the key's owner, lowering cache hit rate
Plain ringOwner depends only on the key and the nodesNo protection against overload
A node dies5 steps
🤵Waiter👩Ana👨Ben🥫 Pantry
Press play and watch it happen!

🧩 Quick quiz

Quick quiz! 4 questions about Consistent hashing, told the same way as the story.
  1. You seat guests by dividing their ticket number by the number of tables. What goes wrong when you add a table?
  2. A new person sits down at the round table. Whose plates change hands?
  3. Why does everyone take many seats around the table?
  4. Ana leaves the round table and has only one seat. Her plates all slide to Ben, who has none of that cake ready. What happens?
Answer every question to check.Passing marks Consistent hashing as done.
Got the hang of Consistent hashing? Mark it as done, and your paths show how far you’ve got.

Saved in this browser.

🕸️ Distributed systems from zeroStep 5 of 7

← Previous on the path📕 ShardingNext on the path →📋 Distributed caching

👉 Read next

  • 🐝HazelcastWorker bees sharing honey in numbered cells, each copied to a second bee, so work goes to the honey.