AlgoViz

Advanced partitioning

hard 30 min

Running 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

Routermap 8Shard 11,500 recordsShard 2400Shard 3350Shard 4500
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

Our systemClientCoordinatorkeeps 10Shard 110 rowsShard 210 rowsShard 310 rowsShard 410 rows

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

    major

    Rows are rarely even over the keys, so one half may be almost empty.

    Wrong
    cut = (s.low + s.high) // 2
    Right
    cut = median_key(s)
  • Merging ranges that are apart

    critical

    The merged bounds swallow keys that other shards own.

    Wrong
    low = min(s.low for s in picked)high = max(s.high for s in picked)
    Right
    if a.high != b.low:    raise ValueError("not neighbours")
  • Dropping errors while gathering

    critical

    A missing shard silently gives a smaller total.

    Wrong
    parts = [p for p in parts if not p.error]return sum(parts)
    Right
    if any(p.error for p in parts):    return Partial(sum_ok(parts), missing=...)
  • Averaging averages

    major

    Shards have different numbers of rows.

    Wrong
    return mean(s.average() for s in shards)
    Right
    return (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.