Bitpath

Lesson 2 · Unit 03

Consistent hashing

Add a node without moving everything

12 exercisesabout 3 min

What you practise

  • hash % N moves almost everything when N changes
  • The ring moves only a neighbour's share
  • Virtual nodes even out the load (simulated in Python)

Try a question from this lesson

Pick one

Twelve keys sit on 4 shards by remainder. A fifth shard is added, so every key is divided by 5 instead. What does this print: how many keys must move?

Python
keys = range(12)
moved = [k for k in keys
         if k % 4 != k % 5]
print(len(moved))
Hint

Try a few keys by hand. A key stays only if both remainders agree.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The hash ring

Picture the hash positions as a circle, say 0 to 99. Each node is hashed to a spot on it, and so is each key.

A key belongs to the first node at or after its position, going clockwise and wrapping around at the end.

Adding or removing a node only affects the keys in one arc of the circle.

ring positions 0..99

  node A at 10
  node B at 40
  node C at 75

  key at 52 -> next node is 75 -> C
  key at 80 -> wraps to 10     -> A

Concept

Virtual nodes

With one spot per node, arcs differ wildly in size, and a leaving node dumps everything on one neighbour.

So each machine is placed on the ring many times, at positions hashed from names like A#0, A#1 and so on. These are virtual nodes.

Many small arcs average out to a fair share, and a leaving machine's load spreads over all the others.

9 more exercises in the app

  • 3× multiple choice
  • 3× type the answer
  • 1× true or false
  • 1× order the lines
  • 1× fill the blanks

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy