AlgoViz

Inside a key-value store

medium 24 min

A distributed key-value store keeps simple pairs on many machines.

See it run

Four nodes on a ring, three copies of each key: follow a write, a read, a new node and a failure.

Operations

Put

A write goes to all three replicas and counts after two answers.

Step 1 of 6

Client request

The ringClientCoordinatorPUT user:123Node Aat 0%Node Bat 25%Node Cat 50%Node Dat 75%

PUT user:123 reaches a node that acts as the coordinator.

Step 1: Client request

def put(key, value):    pos = hash(key)    nodes = ring.replicas(pos, n=3)    new = next_version(key)    send_all(nodes, key, new, value)    acks = wait_for(nodes, count=W)    return "ok" if acks >= W else "unknown"
Waits for
W = 2 of 3
Survives
1 lost node
W = 3
waits for the slowest

Say it exactly: send to N, wait for W. The third copy is late, not skipped.

In the real world

The same inside a key-value store doing real jobs. Pick one and step through it.

A match result is read by everybody. The team doubles the nodes, and nothing improves.

Step 1 of 3

Four nodes

The ringClientCoordinatorNode A100% busyNode B5% busyNode C100% busyNode D100% busy

The key lives on C, D and A. They are full; B idles.

Step 1: Four nodes

Common mistakes

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

  • Placing keys with hash mod N

    critical

    Every change of N moves almost all keys at once.

    Wrong
    node = nodes[hash(key) % len(nodes)]
    Right
    node = ring.first_after(hash(key))
  • Two copies on one machine

    critical

    With virtual nodes, neighbours on the ring can be the same machine. One failure then takes two copies.

    Wrong
    copies = next_tokens(pos, 3)
    Right
    copies = next_different_machines(pos, 3)
  • Treating an error as not written

    major

    Some replicas may have stored the write. A blind second increment counts twice.

    Wrong
    if put_failed:    increment(key)      # again
    Right
    if put_failed:    put(key, value, request_id)  # safe to repeat
  • Sizing for storage only

    minor

    Quorums multiply the operations. Load often needs more nodes than disk space does.

    Wrong
    nodes = data / disk
    Right
    nodes = max(storage_nodes, load_nodes, N)

Interview tips

  • How to explain it

    • Key, hash, ring position, N replicas.
    • Send to N, wait for W or R.
    • Repair what was missed.
  • CHURN

    • Consistent hashing, high availability.
    • Uniform distribution with virtual nodes.
    • Read and write quorums, N replicas.
  • Good for

    • Sessions, profiles, carts and caches.
    • Lookups by one key.
    • Writes that must be accepted during failures.
  • Not for

    • Joins and complex queries.
    • Locks, unless it uses consensus.
    • Transactions over many keys, unless offered.