Skip to content

Consistent hashing: adding servers without reshuffling

Working knowledgeUnder the hood

With hash(key) % N, adding one server sends most keys somewhere new. Consistent hashing puts servers and keys on one ring, so a new server takes only its neighbours' share. Here is the ring, drawn key by key, and the code to measure it.

01 Why hash % N reshuffles everything

The simplest way to spread keys over servers is hash(key) % N. It spreads them evenly, and every client works out the same answer without asking anyone. The trouble starts when N changes. Go from 3 servers to 4 and hash % 3 and hash % 4 agree for only about one key in four, so roughly three quarters of the keys now belong somewhere else.

For a cache, every moved key is a miss that falls through to the database, all at once. For a database, every moved key is a row that must be copied across the network before the new server is useful. You wanted to add 25% more capacity; you are paying to move 75% of the data.

hash % N, 3 → 4 serversAbout 3 keys in 4 moveThe answer depends on N, so changing N changes it for most keys.
Consistent hashing, 3 → 4About 1 key in 4 movesOnly the keys the new server takes over. Every other key stays where it was.

02 Servers and keys on one ring

Consistent hashing takes N out of the formula. Picture the whole range of hash values bent into a circle, so the largest value sits next to 0. Hash each server's name to a point on that circle, and hash each key with the same function. A key belongs to the first server point you reach walking clockwise from it.

Real rings use 32-, 64- or 128-bit hashes. Here the ring has 100 positions and the hash values are made up, so you can follow the walk.

Placing six keys on a ring of three servers
Step 1 of 7
Keys placed 0 of 6
Ring 0–99, clockwise (toy positions)
0ana 8A 20ben 27cy 44B 50dee 63eve 71C 80fay 92
Owner of each key
Empty
  • key being placed
  • its server
  • key not placed yet
  • just assigned

Three servers have hashed their names onto a ring of 100 positions: A at 20, B at 50, C at 80. Six keys are about to be hashed onto the same ring.

3 servers

Each server owns the arc that ends at its point: A owns 81–99 and 0–20, B owns 21–50, C owns 51–80. Nothing in the rule mentions how many servers there are.

03 A new server takes only its neighbour's share

Now add a server. It lands on one point and splits one arc in two. Keys on the half before its point now reach it first; every other key's walk is exactly as it was.

Server D joins at 35
Step 1 of 5
Ring 0–99 with D (toy positions)
0ana 8A 20ben 27D 35cy 44B 50dee 63eve 71C 80fay 92
Owner of each key
ana→Aben→Bcy→Bdee→Ceve→Cfay→A
Keys that move
Empty
  • not on the ring yet
  • joined or moved
  • key being checked
  • its server
  • checked, unchanged

The same ring, with every key owned as before. Server D is about to join; it hashes to 35. Nothing has moved.

3 servers

The keys that move go to the new server and nowhere else, and they all come from the one server that owned that arc. Removing a server is the mirror image: its keys pass to the next server clockwise, and nobody else is touched.

04 Uneven arcs, and why each server gets many points

With one point per server, the picture has two problems. Hash values land wherever they like, so the arcs can be very different sizes and one server can own half the ring. And when a server leaves, its whole load lands on a single neighbour.

One point per server. `B` leaves, and its whole arc, `ben` and `cy`, falls to `C`, the next server clockwise.
Ring 0–99 after B leaves
0ana 8A 20ben 27→Ccy 44→CB 50dee 63eve 71C 804 keysfay 92
  • left the ring
  • moved
  • now holds double

The fix is to give each server many points, often called virtual nodes or tokens: hash A#0, A#1, A#2… and place all of them. A server now owns many small arcs scattered round the ring. The sizes even out, and a leaving or joining server trades a little with many others instead of a lot with one.

Three points per server (toy positions). When `B` leaves, each of its three arcs goes to whichever point follows it: two to `C`, one to `A`.
Ring 0–99, three points per server
0A 5B 18C 30+B's arcB 40A 55+B's arcC 63B 72C 85+B's arcA 95
  • B's points, removed
  • takes over B's arc

With hundreds of points per server, a leaving server's arcs are scattered all round the ring, so every survivor takes a small, similar slice.

Points also let you weight servers: a machine with twice the memory gets twice as many points, and owns about twice as many keys.

05 Build the ring and count what moves

A ring is a sorted list of points plus a map from point to server. Finding a key's owner is a binary search for the first point after the key's hash, wrapping to the start when it runs off the end. This script places 10,000 keys, adds a fourth server, and counts the moves three ways.

ring.py
import bisect
import hashlib
from collections import Counter
def h(s: str) -> int:
# The first 8 bytes of MD5: the same number on every machine, every run.
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
class Ring:
def __init__(self, nodes, vnodes=1):
self.vnodes = vnodes
self.positions = [] # sorted points on the ring
self.owners = {} # point -> node
for node in nodes:
Text
$ python3 ring.py
Adding D to A, B, C: keys that move, of 10,000
hash % N 7517
ring, 1 per node 5490
ring, 100 per node 2448
Keys per node after adding D
ring, 1 per node {'A': 309, 'B': 124, 'C': 4077, 'D': 5490}
ring, 100 per node {'A': 2577, 'B': 2466, 'C': 2509, 'D': 2448}

These are real numbers from Python 3.14; MD5 gives the same ones on any machine. hash % N moved three quarters of the keys, as predicted. The ring with one point per server moved 5,490, every one of them to D, because D happened to land on a huge arc and now holds more than half the keys while B holds 124. With 100 points per server, a quarter of the keys moved and the four servers each hold close to 2,500.

Every client must build the same ring: the same hash function, the same server names and the same number of points. Python's built-in hash() is randomised per process for strings, and two clients with different server lists send the same key to different places. Usually the server list lives in one shared place, such as a config service, and clients reload it when it changes.

06 Where you meet it

Consistent hashing in systems you may use
SystemHow it uses the ring
Amazon Dynamo (2007 paper)Partitions keys over storage nodes with virtual nodes, and copies each key to the next servers clockwise.
Apache CassandraEach node owns tokens on a ring; `num_tokens` sets how many (16 by default since 4.0, 256 before).
Memcached clientsLibraries based on ketama pick a cache server per key, so adding a cache server keeps most keys warm.
Nginx`hash $request_uri consistent;` in an upstream block sends each URL to the same backend using ketama.

The ring is not the only answer. Rendezvous hashing scores every server for each key and picks the highest, which needs no ring at all. Jump consistent hash (Google, 2014) needs no memory but numbers its servers, so it suits shards that are only ever added at the end. Both move about the same small share of keys.

07 When the ring bites

1 point per serverLopsided arcsA few random points rarely split a ring evenly; one server can get half the keys, as in the run above. Use many points per server and check the spread.
hash(key) in PythonClients that disagreeA hash that differs between processes, or clients with different server lists, send one key to two servers. Use a fixed hash such as MD5 or MurmurHash and one shared list of members.
next 3 points clockwiseReplicas on the same machineCopying a key to the next few points can pick two virtual nodes of one server. Walk on until you have found the required number of distinct servers, as Dynamo does.
GET celebrity:1One hot keyThe ring spreads keys, not load. A single key that gets a huge share of the traffic still lands on one server, whatever the ring looks like. That needs its own fix, such as caching or splitting that key.
add 4 servers at onceMoving data is still workFewer keys move, but they still move. A new database node must copy its arcs before it can serve them; stream them in, and add nodes one at a time.

08 Check yourself

Question

A ring has 4 servers with 200 points each. You add a fifth, also with 200 points. About what share of the keys moves?

Question

Each server has one point on the ring. Server B crashes. Where do its keys go?

Question

Two app servers build the same ring from the same list of cache servers, but use Python's built-in hash(). What happens?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?