# I added one server to my cache and 80% of the keys moved

Your cache is too big for one machine, so you split it across 4 servers. Every app server needs to agree on which one holds `user:42`, and the obvious rule is:

```python
server = hash(key) % 4
```

It works fine. Then traffic grows, you add a fifth server, and the rule becomes `hash(key) % 5`.

I simulated exactly that with 10,000 keys. Here's what happened.

## The number

```text
[2/3] Add a 5th server. How many keys now live somewhere else?
      method                    keys moved    share
      hash(key) % N                  7,960    79.6%
      hash ring, 100 vnodes          1,656    16.6%
      The ideal is 1/5 = 20%. Of the ring's moved keys, 1,656 went to the new server
      and 0 moved between old servers.
```

Adding one server moved **80% of the keys**.

For a cache, "moved" means "missing". The app asks the server the new rule points to, the key isn't there, and the request falls through to the database. So your hit rate collapses and your database takes the full load at the worst possible moment: right when you were adding capacity because load was high.

The worst part is that most of those keys didn't even move to the new server. They moved between the old servers, which hadn't changed at all. `% 5` just reshuffles almost everything.

## Why % N breaks

Take a key whose hash is 42. With 4 servers it lives on `42 % 4 = 2`. With 5 servers it lives on `42 % 5 = 2`. Lucky, it stayed.

Now try 43: `43 % 4 = 3`, but `43 % 5 = 3`. Also lucky. Try 44: `44 % 4 = 0`, `44 % 5 = 4`. Moved. 45: `1` then `0`. Moved. 46: `2` then `1`. Moved.

A key only stays put when both answers happen to match, and that's true for about 1 key in 5. Everything else moves. Changing N changes the answer for nearly every key.

## The fix: a hash ring

**Consistent hashing** puts servers and keys on the same circle, called the **ring**.

![A hash ring before and after adding a server](https://raw.githubusercontent.com/mannietech15/system-design-mastery/main/assets/03-consistent-hashing.svg align="center")

1. Hash each server's name to a number and place the server at that point on the ring.
2. Hash each key the same way. The key belongs to the first server found walking clockwise from it.
3. When server E joins, it only takes over the keys in the arcs just before its points. Every other key keeps its server.

That's why the ring moved 16.6%, close to the ideal of 1/5. And every one of those 1,656 keys moved *to the new server*. Zero moved between old servers.

## The catch: virtual nodes

With one point per server, the gaps between points are random, so one server can own a huge arc and another a tiny one. Same simulation, 5 servers, ideal is 2,000 keys each:

```text
[3/3] Why virtual nodes? Keys per server (5 servers, ideal 2,000 each):
      vnodes/server     fewest    most  most / ideal
      1                      7   6,369         3.18x
      10                   929   3,001         1.50x
      100                1,656   2,347         1.17x
      1000               1,925   2,082         1.04x
```

With one point each, the busiest server got **3.18x** its fair share, and the quietest got 7 keys. The fix is to give each server many points (`cache-a#0`, `cache-a#1`, ...), called **virtual nodes**. Each server then owns lots of small arcs, and the sizes average out. With 100 points each, the busiest server is at 1.17x.

Virtual nodes have a second benefit. When a server dies, its many small arcs are picked up by all the other servers, instead of one unlucky neighbour taking everything.

## A bug you might not expect

You might reach for Python's built-in `hash()`. Don't:

```text
PYTHONHASHSEED=1: hash('user:42') % 4 = 1
PYTHONHASHSEED=2: hash('user:42') % 4 = 2
```

Python salts string hashes with a random value per process, so two app servers would disagree about where the same key lives. Every client must compute the same number, so use a fixed hash. The demo uses MD5, which is fine here because the goal is an even spread, not security.

## What interviewers listen for

If you're asked to shard a cache in a system design interview, these are the red flags:

- Sharding with `hash(key) % N`. Adding one server moves about 80% of keys.
- Using a language's built-in hash that differs between processes.
- Consistent hashing without virtual nodes. One server got 3.18x its share.
- Claiming consistent hashing fixes hot keys. It balances key *counts*, not traffic. A single viral key still lands on one server.

## Run it yourself

Every number in this post came from a real run, not from a slide. The whole thing is about 150 lines of plain Python, with nothing to install:

```bash
git clone https://github.com/mannietech15/system-design-mastery
cd system-design-mastery/03-consistent-hashing
python demo.py
```

This is chapter 3 of [system-design-mastery](https://github.com/mannietech15/system-design-mastery), 24 system design concepts you can run, from rate limiters to Raft to distributed tracing. Each chapter has a demo, tests, interview questions and two challenges that fail until you build them.

If it's useful, a star is the easiest way to keep it within reach for your next interview, and it helps other developers find it too.

## Go further

- DeCandia et al., [Dynamo: Amazon's Highly Available Key-value Store](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf) (SOSP 2007), sections 4.2 and 4.3.
- Apache Cassandra, [Dynamo-style architecture](https://cassandra.apache.org/doc/latest/cassandra/architecture/dynamo.html): tokens and virtual nodes.
- Lamping and Veach, [A Fast, Minimal Memory, Consistent Hash Algorithm](https://arxiv.org/abs/1406.2294) (2014).
