AlgoViz

Consistent hashing

medium 28 min

Consistent hashing puts keys and machines on one circle.

Video lesson · Chapter 1 of 6

Walk clockwise to the owner

0:00 / 5:45

The hash ring in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Data that does not fit on one machine is spread over several, so every read has to answer one question first: which machine holds this key? Consistent hashing answers it with arithmetic instead of a list of every key.

A hash function turns any text into a number. Draw all those numbers on a circle, the hash ring. Hash each machine's name to a point on the ring, and each key too. A key belongs to the first machine you meet going clockwise.

Why it exists

The obvious answer, the hash of the key modulo the number of machines, works until that number changes. Then almost every key has a new home, and for a cache that means almost every request misses at once.

On a ring a new machine takes over only the stretch just before it. Nobody else's keys move. Growing from three machines to four moves about a quarter of the keys, the least that can be moved if the fourth machine is to get its fair share.

A short history

  1. 1996

    David Thaler and Chinya Ravishankar at the University of Michigan invent rendezvous hashing, a different way to reach the same goal.

  2. 1997

    David Karger and colleagues publish "Consistent Hashing and Random Trees" to spread web requests over a changing set of caches. The paper introduces the name.

  3. 2007

    Amazon publishes the Dynamo paper: a key-value store that partitions data on a ring and gives each machine many points on it, called virtual nodes.

  4. 2014

    John Lamping and Eric Veach publish jump consistent hash, which needs almost no memory but numbers its buckets from 0 to n - 1.

  5. 2016

    Mirrokni, Thorup and Zadimoghaddam publish consistent hashing with bounded loads, which caps how much any one machine can receive.

Words to know

Hash function
Turns any input into a number that looks random but is always the same for the same input.
Hash ring
The whole range of hash values bent into a circle, so the largest is followed by zero.
Token
One point on the ring that belongs to a machine.
Virtual node
One of several tokens owned by the same machine. Vnode for short.
Successor
The next machine clockwise.
Preference list
The first few different machines clockwise from a key, where its copies live.
Rebalancing
Moving data so that every machine holds a fair share again.

How it works

Step through the idea, or press Play.

Step 1 of 3

Put machines on a ring. Hash each machine's name to one or more points

Understand it

Start here

A round campfire

Picture a camp at night. The sleeping bags lie in a circle around the fire, and little lanterns stand along the circle too. The rule is simple: start at a lantern and walk clockwise. The first camper you reach looks after it. So each camper tends one stretch of the circle.

Who looks after which lantern?
ABCLanternsA2B2C2

A lantern that is far more popular than the rest still has one camper. The circle shares out lanterns, not visitors.

Another picture of the same idea is a circular race track. The stations are the machines and every car stops at the first station ahead of it. A new station catches only the cars that now reach it first, and nobody else is disturbed.

The problem

Why not hash modulo N?

The first idea is hash(key) % N, where N is the number of machines. It is fast and even. The trouble starts when N changes, because the remainder of nearly every number changes with it.

Three keys, from 3 machines to 4

KeyHashhash % 3hash % 4Result
key171 = B3 = Dmoved
key252 = C1 = Bmoved
key390 = A1 = Bmoved
In this small sample every key moves. Over many keys the share is 75%, as the next equation shows.

How many keys move when one machine is added?

modulo: NN+1ring: 1N+1N=3:;75% against 25%\text{modulo: } \frac{N}{N+1} \qquad \text{ring: } \frac{1}{N+1} \qquad N=3:; 75\% \text{ against } 25\%
With modulo a key stays only when both remainders agree, which happens for one key in N + 1. On the ring only the new machine's share moves. Measured on 20,000 keys with MD5: 74.5% for modulo from 3 to 4.

One machine is added

The ring breaks this chain at the second step: only about a quarter of the keys get a new home.

The ring

Three steps

  1. 1

    Hash the nodes

    position = hash(node id). In a small example on 0 to 359 degrees: N1 at 45, N2 at 135, N3 at 225. Real systems use a range such as 0 to 2^32 - 1 or larger.

  2. 2

    Hash the keys

    The same function: user:42 lands at 100 degrees and order:7 at 200 degrees.

  3. 3

    Walk clockwise

    From 100 the first node is N2 at 135. From 200 it is N3 at 225. A key at 300 passes the end of the ring and reaches N1 at 45.

Where the ring lives

Users send requests to an application server. Inside it, a ring library holds the sorted tokens. It sends the key user:42, at 100 degrees, to cache node N2, which owns 46 to 135. The other nodes N1 and N3 own the other stretches.
The ring is only a sorted list in the memory of whoever routes the request: a client library, a proxy or the database nodes themselves.

Lookup

Finding the owner fast

Python
import bisecttokens = [45, 135, 225]owner = {45: "N1", 135: "N2", 225: "N3"}def get_node(position):    i = bisect.bisect_left(tokens, position)   # first token >= position    return owner[tokens[i % len(tokens)]]      # wrap past the endfor key, pos in [("user:42", 100), ("order:7", 200), ("late", 300), ("edge", 135)]:    print(key, pos, "->", get_node(pos))
Binary search over T tokens takes about log2 T comparisons. With 10 nodes and 150 tokens each that is 1,500 tokens and about 11 comparisons.
Edit and run it in your browser

One read

No other machine is asked. Every client with the same token list reaches the same answer.

Change

Adding and removing a node

A node joins

  • Hash the new node to its positions
  • Find the successor of each position: it holds the data now
  • Copy the keys between the predecessor and the new node
  • Update the routing list, then delete the old copies

A node leaves

  • Identify its stretches
  • Find the successor of each one
  • Copy all its keys there, or promote replicas if it crashed
  • Remove it from the routing list

Only one neighbour takes part

Before: node N2 owns 46 to 135 and node N3 owns 136 to 225. New node N4 joins at 110. It copies the keys from 46 to 110 out of N2. N2 keeps 111 to 135. N3 is not touched.
With one token for each node, one join copies from one machine. With many tokens it copies a little from many.

How much data moves

join: KN+1leave: KNK=12 million,;N=5:;2M and 2.4M\text{join: } \frac{K}{N+1} \qquad \text{leave: } \frac{K}{N} \qquad K=12\text{ million},; N=5:; 2\text{M and } 2.4\text{M}
K is the number of keys and N the number of nodes before the change. These are averages; with one token for each node a single join can move much more or much less.

Balance

Virtual nodes

Three random points rarely cut a circle into equal parts. One node may own 50% of the ring, another 30% and the last 20%. Virtual nodes fix this: node A is hashed many times, as A#0, A#1 and so on up to A#149, and owns all those short stretches.

Measured: 20,000 keys on 5 nodes, then a sixth joins

Tokens per nodeBusiest node, times the averageKeys moved to the sixth
11.7519.5%
101.2916.2%
1001.1316.6%
1501.0618.7%
2001.0917.4%
One run with MD5 and these node names; another run gives other digits. The ideal is 1.00 and 16.7%. More tokens help quickly at first and slowly later.

How uneven is it?

spread of a node’s share≈1VV=100:;10%V=150:;8%\text{spread of a node's share} \approx \frac{1}{\sqrt{V}} \qquad V=100:; 10\% \qquad V=150:; 8\%
V is the number of tokens for each node. A rule of thumb: to halve the unevenness you need four times the tokens.
  • Even shares

    More points mean shorter stretches and a fairer total.

  • Mixed hardware

    A machine with twice the memory gets twice the tokens.

  • Smooth failure

    When a node dies, its short stretches fall on many other nodes instead of one.

  • Replicas need care

    Neighbouring tokens may belong to the same machine, so skip repeats when choosing copies.

Copies

Replicas on the ring

To keep three copies, continue clockwise and take the first three different machines. The Dynamo paper calls this the preference list. Real systems also skip machines in the same rack or zone. How copies agree is the job of replication and consistency models.

Choosing three copies

Without the first question, two copies could end on one machine and die together.

Limits

What the ring does not fix

It gives you

  • Few keys moved on a change
  • A lookup without a central table
  • Roughly equal numbers of keys
  • Easy weights

It does not give you

  • Protection from one hot key
  • Range scans: neighbours on the ring are unrelated
  • Agreement about who is a member
  • Copies that are consistent

For a hot key, cache it closer to the reader, split it into several keys, or use bounded loads: a node that already has, say, 1.25 times the average passes the request to the next node. For range scans use range partitions; see partitioning strategies.

Alternatives

Other ways to the same goal

MethodIdeaGoodWeak
Ring with vnodesSorted tokens, go clockwiseAny node can leave; weights are easyToken list to store and share
RendezvousScore every node for the key, highest winsEven, no list of tokensEach lookup scores all N nodes
Jump hashA short loop gives a bucket numberAlmost no memory, very evenOnly the last bucket can be removed
Fixed slotsKey to one of many slots, slots to nodes in a tableOperators decide what movesThe table has to be stored and agreed
Modulohash % NSimplestNearly everything moves
Redis Cluster uses fixed slots: 16,384 of them, shared out among the masters. Envoy offers a ring and Maglev, a table-based relative.

Which one?

In practice

Who uses it

SystemWhat its own documents say
Dynamo (2007 paper)Ring, virtual nodes, preference list
Apache CassandraTokens on a ring, 16 per node by default
Riak KVEach node manages a set of vnodes
nginxhash with consistent uses the ketama method
EnvoyRing hash and Maglev load balancers
Amazon DynamoDBAn internal hash function chooses the partition; the ring is not documented
Ketama is the well-known ring library for memcached clients. Dynamo is a paper and DynamoDB a product: do not mix them up.

Summary

The whole topic in one minute.

Consistent hashing places keys and machines on one ring and gives each key to the first machine clockwise. A lookup is a binary search over sorted tokens. When a machine joins or leaves, only the keys in its own stretches move, about one part in N.

One token per machine gives uneven shares, so real systems give each machine many tokens. They even out the load, let a bigger machine take more, and spread a failed machine's work over many others. The ring balances keys, not popularity: one very hot key still lands on one machine.

  • Keys and nodes share one ring; a key belongs to the first node clockwise.
  • A change moves about one part in N of the keys. Modulo moves nearly all of them.
  • The stretch that moves to a new node lies between its predecessor and itself.
  • Virtual nodes even out the shares, allow weights and spread failures.
  • Copies go to the next different machines clockwise.
  • It does not cure hot keys, range scans or disagreement about members.

Sources