Sharding & replication
medium 30 minScale a database past one machine by splitting rows over shards, and keep it available by copying every shard.
See it run
Follow one write to its shard and its copy, grow the cluster, and read through lag.
Operations
Write and copy
A write finds its shard, is logged and applied, and then travels to the follower.
Step 1 of 5
Route
Key goes to shard 1
The router hashes the key and picks shard 1.
Step 1: Route
def write(key, value): shard = route(key) lsn = shard.primary.log.append(key, value) shard.primary.apply(lsn) ship_later(shard.followers, lsn) return lsndef route(key): return machine_of[stable_hash(key) % LOGICAL]- Machines touched
- 1 shard
- Data moved
- None
- Wait for the follower
- safer, slower
Say when the client gets its answer: before or after the follower has the change. That is the whole trade.
In the real world
The same sharding and replication doing real jobs. Pick one and step through it.
Shard 1 loses its primary. What happens depends on how it was copied.
Step 1 of 4
Normal
Asynchronous copy
Primary 1 is at 41. The follower is at 40.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The number of machines in the rule
criticalChanging it gives almost every key a new home.
Wrongmachine = hash(key) % len(machines)Rightlogical = stable_hash(key) % 1024machine = machine_of[logical]Reading from any follower
majorA follower that is behind shows people their own data from the past.
Wrongreturn random_follower().get(key)Rightok = [f for f in followers if f.position >= need]return (ok[0] if ok else primary).get(key)Shards without copies
criticalWith ten machines something is broken ten times as often as with one.
Wrongshards = [Primary(i) for i in range(10)]Rightshards = [Primary(i, followers=2) for i in range(10)]Trusting an old map
criticalA router with an old map writes to a machine that no longer owns the key.
Wrongdef write(key, value): store(key, value)Rightdef write(key, value): if not owns(key): raise WrongShard # router reloads store(key, value)
Interview tips
How to explain it
- Pieces for room, copies for safety.
- Key to logical shard to machine.
- One shard when the key is named, all when it is not.
Memory trick
- The rule is fixed, the map moves.
- Log first, apply second, ship third.
- Position beats guessing.
Reach for it when
- Writes or data exceed one machine.
- Requests name a user or a tenant.
- Indexes, cache and replicas are done.
Watch out for
- One key that is hot.
- Unique values over shards.
- Transactions over shards.