Inside a key-value store
medium 24 minA 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
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 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
criticalEvery change of N moves almost all keys at once.
Wrongnode = nodes[hash(key) % len(nodes)]Rightnode = ring.first_after(hash(key))Two copies on one machine
criticalWith virtual nodes, neighbours on the ring can be the same machine. One failure then takes two copies.
Wrongcopies = next_tokens(pos, 3)Rightcopies = next_different_machines(pos, 3)Treating an error as not written
majorSome replicas may have stored the write. A blind second increment counts twice.
Wrongif put_failed: increment(key) # againRightif put_failed: put(key, value, request_id) # safe to repeatSizing for storage only
minorQuorums multiply the operations. Load often needs more nodes than disk space does.
Wrongnodes = data / diskRightnodes = 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.