Search

Search papers and lessons

Consistent Hashing

Level 3 · 9 min read

Consistent hashing places servers and keys on the same ring of hash values, so adding or removing a server moves only the keys next to it instead of reshuffling almost everything.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Calculus
  • Algorithms
  • Distributed systems
  • Sign in to see your progress

TL;DR

Consistent hashing spreads keys across a set of servers so that adding or removing one server moves only a small share of the keys. Both the servers and the keys are hashed (turned into numbers by a Hash Function) onto the same circle of numbers. A key belongs to the first server found going clockwise from the key's position.

Where you'll see it: distributed key-value stores (databases that look up a value by its key), cache clusters that choose a server per key, and content delivery networks that route each request to a cache node.

Intuition

Suppose you have four shops and a stock of cards, each labelled with a customer ID. (This is the situation of a Distributed System that spreads data over several machines.) The simplest rule is to send each ID to shop number ID mod 4, a rule of the kind used in a Hash Table, where a mod 4a \bmod 4 means the remainder after dividing aa by 4. That works until you open a fifth shop. Now the rule is ID mod 5, and almost every card goes to a different shop. Every shop has to restock, and the stock is in the wrong place until it moves.

Consistent hashing avoids that. Place the shops around a circle, each at a spot chosen by hashing its name. Place each card on the same circle by hashing its ID. A card goes to the next shop clockwise from its spot. Open a new shop: it takes over only the cards between it and the shop before it on the circle. Close a shop: its cards pass to the next shop clockwise, and nothing else moves.

The problem it solves is churn. A cache (a fast store of recently used answers; see Cache Eviction Policy) or database spread over many machines must change when machines fail or are added. A plain hash rule would send most keys to new machines at once, and that wipes the caches and floods the database. Consistent hashing makes each change local.

The math

Fix a hash function hh that maps any key to an integer in a large range, [0,232)[0, 2^{32}) in many systems. Read the range as a ring, where the value after 232−12^{32} - 1 wraps back to 00. Arithmetic on the ring is Modular Arithmetic with M=232M = 2^{32}.

Given servers s1,…,sNs_1, \dots, s_N, place each server at h(si) mod Mh(s_i) \bmod M on the ring. For a key kk with position p=h(k) mod Mp = h(k) \bmod M, define its owner as the first server clockwise from pp:

owner(k)=sjwhere h(sj) is the smallest server position with h(sj)≥p,\text{owner}(k) = s_j \quad \text{where } h(s_j) \text{ is the smallest server position with } h(s_j) \geq p,

and if no such server exists, the owner wraps around to the server with the smallest position.

When a server is added, the keys that move are exactly those in the arc between the new server and the server before it. When a server is removed, its keys move to the next server clockwise. Nothing else changes.

If the hash spreads keys uniformly, each server owns about 1/N1/N of the ring. Adding an (N+1)(N+1)th server takes about 1/(N+1)1/(N+1) of the keys, and every one of them comes from the server that was next to it. The total moved is about 1/(N+1)1/(N+1) of all keys. Compare this with the naive rule h(k) mod Nh(k) \bmod N. A key stays on its server only when the old and new remainders match, so about N/(N+1)N/(N+1) of the keys move.

Each server holds one point on the ring, so the arcs can be uneven. Give each server vv points, called virtual nodes, and the owned shares average out. With more virtual nodes, each server's share gets closer to 1/N1/N.

Worked examples

Example
A small ring with twelve positions
  1. Place three servers on a ring of 12 positions: A at 2, B at 6, C at 10.
  2. Key k1 hashes to 4. The first server clockwise is B at 6, so k1 goes to B.
  3. Key k2 hashes to 11. Going clockwise from 11 there is nothing until the wrap, then A at 2. So k2 goes to A.
  4. Key k3 hashes to 8. The first server clockwise is C at 10. So k3 goes to C.
  5. Remove B. Now k1 at 4 goes to the next clockwise server, C at 10. k2 still goes to A, and k3 still goes to C.
  6. Only k1 moved, and it moved from B to C, the server after B. Keys that were on A or C did not change.
  7. Add D at 5. The key k1 at 4 now finds D at 5 first, so k1 moves to D. Every other key is still where it was.
Example
Four servers, then a fifth
  1. Use a ring of 100 positions. Servers A, B, C, D sit at 10, 40, 65 and 90.
  2. Key at 25 goes to B (first server clockwise). Key at 70 goes to D. Key at 95 goes to A after wrapping. Key at 5 goes to A.
  3. Add E at 55. It takes the arc from 41 to 55 that previously belonged to C. That arc is part of C's range, so keys in (40,55](40, 55] now go to E.
  4. The arc length is 15 of 100, so about 15 percent of keys move, and they all come from C. Keys in (55,65](55, 65] still go to C, and the key at 70 still goes to D.
  5. The same change with the naive rule h(k) mod Nh(k) \bmod N moves keys between N = 4 and N = 5 in a different way. Take the 20 residues 00 to 1919. A residue stays put only if its remainder mod 4 equals its remainder mod 5. That holds for 0,1,2,30, 1, 2, 3 only, so 4 of 20 stay and 16 of 20 move, which is 80 percent.
  6. Interpretation: consistent hashing moved about 15 percent of keys, and the naive rule moved about 80 percent. For a large cache, the difference is the difference between a small miss burst and a cold cache.
Example
Removing one server from ten, with virtual nodes
  1. Ten servers, each with 100 virtual nodes, so the ring has 1000 points. Each server owns about 10 percent of the keys.
  2. Remove one server. Its 10 percent of keys is spread across the arcs of its virtual nodes, which fall next to many different surviving servers.
  3. Those keys are shared among the 9 survivors, about 10/9≈1.1110/9 \approx 1.11 percent extra each. A survivor goes from about 10 percent to about 11.1 percent of the keys.
  4. Moved keys: about 10 percent of the total. The remaining 90 percent do not move at all.
  5. Interpretation: the removal cost matches the ideal 1/N1/N fraction, and the extra load is spread evenly. With one point per server, the load would be lumpier and one neighbour could take a much larger share.

Tradeoffs and failure modes

SituationProblemBetter choice
Few servers, few points eachArcs are uneven, so one server may own a large shareAdd virtual nodes, for example 100 or more per server
Hash function is weakKeys cluster, so arcs carry unequal loadUse a well-mixed hash, not a simple modulo of the key
Servers differ in capacityEqual virtual nodes give equal load regardless of sizeGive bigger servers more virtual nodes in proportion to capacity
Keys have a hot spotOne key or key range gets most of the trafficConsistent hashing does not fix hot keys; replicate them or split the key
Need exact placement controlThe ring decides placement, not the operatorUse an explicit lookup table, at the cost of storing the table
Replicas are neededOwner alone is one point of failureStore each key on the next several servers clockwise

One failure mode deserves a warning. Moving keys is cheap, but moving the data behind them is not. Right after a server joins, the cache misses for the keys it took, and a backing store may take a spike. Rebalancing should be gradual where the system allows it.

History

The idea was introduced in 1997 by David Karger and colleagues at MIT, in work on distributed caching for the web. It was motivated by caches spread over many machines, where a change of machines should not invalidate the whole cache. The technique later became a standard part of large distributed systems. Amazon's Dynamo key-value store, described in 2007, used a ring with virtual nodes to place data and replicas. Many client libraries for caches and databases implement a similar ring. The key idea has not changed since the 1997 paper: hash both servers and keys into one space and let each key follow its nearest server.

Recap

Taking keys mod the server count reshuffles almost everything when the count changes. Consistent hashing puts servers and keys on one ring, assigns each key to the next server clockwise, and so moves only about 1/(N+1)1/(N+1) of the keys when a server joins, and only the leaving server's keys when one leaves. Virtual nodes even out the shares and can be weighted by capacity. It leads next to replication on successive ring neighbours and to the storage systems built on it, such as Dynamo.

Check yourself

QuestionIn one sentence, why does a plain rule of hash mod N cause a problem that a ring does not?Show answer

With hash mod N, changing N changes the remainder for most keys, so most keys move to new servers. On a ring, changing a server affects only the arc it sits on, so only the keys in that arc move.

QuestionA ring has positions 0 to 99 and servers at 20, 50 and 80. A new server is placed at 65. Which arc of keys moves, and how many of the 100 positions does it cover?Show answer

The new server at 65 takes the arc from just after 50 up to 65, that is positions 51 to 65. That is 15 positions, so 15 percent of the ring moves. The keys in that range that previously went to the server at 80 now go to the server at 65. Keys in 66 to 80 stay with the server at 80.

QuestionWhy do virtual nodes help even when the hash function is good?Show answer

A good hash places points uniformly in expectation, but with only one point per server the arcs are random and can differ a lot in length. Many virtual nodes per server make each server's total share an average of many small arcs, so the shares concentrate near one over N. The good hash makes the positions random; the virtual nodes make the totals even.

QuestionApplied: a cache cluster of 8 servers loses one server. Roughly what fraction of cached keys is lost, and what happens to the hit rate?Show answer

About one eighth of the keys were on the failed server, roughly 12.5 percent. Those keys now miss in the cache until they are fetched again and stored on their new owners. The other keys keep their servers and still hit. The hit rate drops by about the share of traffic those keys carried, and recovers as they refill. Replicating each key on a second server would cut the loss to near zero.

Sources

Consistent Hashing — explained simply | ungoon.me