AlgoViz

Consistent hashing

medium 28 min

Consistent hashing puts keys and machines on one circle.

See it run

Walk the ring: find an owner, add and remove a node, even the shares with virtual nodes, and compare with modulo.

Operations

Find the owner

Hash the key and take the first node clockwise.

Step 1 of 5

Three nodes on the ring

N1N2N3

positions, in degrees

N1 45 · N2 135 · N3 225

sorted tokens

45 N1 · 135 N2 · 225 N3

Each node is hashed to a position: N1 at 45, N2 at 135, N3 at 225 degrees.

Step 1: Three nodes on the ring

def get_node(key):    pos = hash_position(key)    i = bisect_left(tokens, pos)    if i == len(tokens):        i = 0                 # wrap around    return owner[tokens[i]]
Keys moved
None
Lookup
log2 T steps
Ask every node
N messages

The last step, wrapping to the first token, is what makes it a ring and not a line.

In the real world

The same consistent hashing doing real jobs. Pick one and step through it.

A shop adds a cache server before a sale. The database can take 3,000 reads a second.

Step 1 of 4

Today

10,000/s1,000/sShop API4 cache nodesDatabase
Database load
33%

10,000 reads a second, 90% answered by the cache. The database gets 1,000.

Step 1: Today

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Using a salted built-in hash

    critical

    Python salts the hash of strings per process, so two servers place the same key on different nodes.

    Wrong
    pos = hash(key) % 2**32
    Right
    pos = int.from_bytes(md5(key.encode()).digest()[:4], "big")
  • One token per node

    major

    Shares differ widely and a crash doubles the load of one neighbour.

    Wrong
    ring.add("N1")
    Right
    for i in range(150):    ring.add(f"N1#{i}", owner="N1")
  • Counting tokens as copies

    critical

    Two neighbouring tokens may be the same machine. Both copies die together.

    Wrong
    copies = ring.next_tokens(key, 3)
    Right
    copies = ring.next_distinct_machines(key, 3)
  • Deleting a token that another node owns

    minor

    Two tokens can hash to the same position. Removing one node must not remove the other's token.

    Wrong
    del owner[position(f"{node}#{i}")]
    Right
    for p in owned.pop(node):   # only what it really owns    del owner[p]

Interview tips

  • How to explain it

    • Keys and nodes on one circle.
    • First node clockwise owns the key.
    • A change moves one part in N.
  • Memory trick: RING

    • Round and Incremental.
    • Nodes with virtual positions.
    • Go clockwise.
  • Reach for it when

    • Nodes that hold data come and go.
    • A cache must survive a resize.
    • Users should stick to a server.
  • Look elsewhere when

    • You need range scans.
    • N never changes.
    • One key is the whole problem.