Advanced partitioning
hard 30 minRunning a partitioned database means keeping it balanced.
See it run
Rebalance a hot shard, ask every shard, cure a hot key, and combine two keys.
Operations
Rebalance
Four shards, one hot. Split it while it serves.
Step 1 of 6
Initial state
- Shard 1
- 85%
- Shard 2
- 25%
- Shard 3
- 20%
- Shard 4
- 30%
Hot spot on shard 1
Shard 1 has 1,500 records and 85% load. It is a hot spot.
Step 1: Initial state
def rebalance(): avg = mean(s.records for s in shards) for s in shards: if s.records > 1.5 * avg: cut = median_key(s) new = create_shard(cut, s.high) copy_and_follow(s, new) switch_map(new)- Shards asked
- 1
- Data moved
- 750 records
- Move everything
- 2,750 records
Begin at 60% full. A copy needs disk, network and processor on the very machine that has none left.
In the real world
The same advanced partitioning doing real jobs. Pick one and step through it.
Ten rows per page, sorted by time over all shards.
Step 1 of 4
Page 1
40 rows for 10
Each shard sends its first 10 rows. 40 rows travel, 10 are kept.
Step 1: Page 1
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Cutting the interval in the middle
majorRows are rarely even over the keys, so one half may be almost empty.
Wrongcut = (s.low + s.high) // 2Rightcut = median_key(s)Merging ranges that are apart
criticalThe merged bounds swallow keys that other shards own.
Wronglow = min(s.low for s in picked)high = max(s.high for s in picked)Rightif a.high != b.low: raise ValueError("not neighbours")Dropping errors while gathering
criticalA missing shard silently gives a smaller total.
Wrongparts = [p for p in parts if not p.error]return sum(parts)Rightif any(p.error for p in parts): return Partial(sum_ok(parts), missing=...)Averaging averages
majorShards have different numbers of rows.
Wrongreturn mean(s.average() for s in shards)Rightreturn (sum(s.total() for s in shards) / sum(s.count() for s in shards))
Interview tips
How to explain it
- Rebalance: split, merge, move.
- Hot key: cache or salt.
- No key: scatter, execute, gather, merge.
Memory trick: RHCC
- Rebalancing, Hot spots.
- Cross-shard, Composite.
- Mail: post office, houses, replies, total.
Safe moves
- Copy, stream, check, switch.
- Limit the speed.
- Keep a way back.
Watch out for
- One key that cannot be split.
- Old maps in routers.
- Automatic moves during an incident.