Bugpit

Lessons › Design skills

Add a machine, keep your data

Traffic has reached 9,000 req/s and your one cache needs company. Last time you added a machine, nearly every key moved, the cache went empty and the database fell over.

Play this level

Part of Bugpit Pro. It runs in your browser: build the design, press Run, and watch what breaks.

The lesson

To spread keys across machines, the simple way is hash(key) % N, where N is the number of machines. It works until N changes. Then nearly every key lands somewhere new, and the cache misses everything at once.

Consistent hashing puts machines and keys on a circle. Each key belongs to the next machine clockwise. Add a machine and only the keys just before it move, about 1 in N of them.

With few machines, the slices of the circle end up uneven. Virtual nodes fix that by placing each machine at many points around the circle.

Redis Cluster, DynamoDB and Cassandra all use this idea, or a close relative of it, so you rarely build it yourself. You do need to know why it's there.

What you have to achieve

9,000 requests a second at the busiest hour, 2% of them writes.

What you learn

Machines can now come and go without emptying the cache. Whenever data is split across machines, ask what moves when the number of machines changes.

Check yourself

You use hash(key) % N and go from 3 machines to 4. About how many keys move?

Show the answer

About 3 in 4. A key only stays put if its result is the same for both 3 and 4, which is true for about 1 key in 4. The rest move.

With consistent hashing, about how many keys move when you add a fourth machine?

Show the answer

About 1 in 4. The new machine takes one slice of the circle, about 1 in N keys. Everything else stays where it was.

What do virtual nodes fix?

Show the answer

Machines ending up with uneven shares of keys. Placing each machine at many points evens out the slices, so no machine gets stuck with far more than its share.

Try it yourself

More in Design skills

← Fresh or fast One order, many services →