AlgoViz

Sharded counters

medium 22 min

One counter that everybody increments becomes a hot key: all writes wait in one line.

See it run

Heat up one counter, split it, write in parallel, and add it up again.

Operations

The hot key

One row, locked for 5 ms by each increment.

Step 1 of 4

Quiet

Clients 1Clients 2Clients 3One counter20/s
Row busy
10%

No problem

20 increments a second use a tenth of the row.

Step 1: Quiet

BEGINUPDATE counters SET n = n + 1 WHERE id = 'video_123'COMMIT                # the lock is held until here
Write
Up to 200/s
Read
1 key
10 shards
up to 2,000/s

Ask how long the lock is held. The limit is one divided by that.

In the real world

The same sharded counters doing real jobs. Pick one and step through it.

10 million views in one hour.

Step 1 of 4

Before

Clients 1Clients 2Clients 3One counter20/s
Row busy
10%

Fine

One counter, 20 views a second.

Step 1: Before

Common mistakes

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

  • Read, add, write

    critical

    Two writers read 10 and both write 11. One increment is lost.

    Wrong
    n = get(key)set(key, n + 1)
    Right
    incrby(key, 1)
  • All shards in one slot

    critical

    The hash tag puts every key on the same node.

    Wrong
    key = f"{{video_123}}:shard_{i}"
    Right
    key = f"video_123:shard_{i}"
  • Returning a partial sum

    major

    When a shard times out, the count drops and then jumps back.

    Wrong
    return sum(v for v in values if v)
    Right
    if any_failed(values):    return last_known_total
  • Sharding everything

    minor

    A million quiet counters with 100 shards are 100 million keys.

    Wrong
    shards = 100
    Right
    shards = ceil(peak / safe_rate)   # often 1

Interview tips

  • How to explain it

    • One key has one owner.
    • Adding has no order.
    • So add in many places and combine.
  • Memory trick: SHARD

    • Split the counter
    • Horizontally scale writes
    • Aggregate for reads
    • Random shard
    • Distribute evenly
  • Reach for it when

    • Writes pass the safe rate of one key.
    • A few seconds of age are fine.
    • Batching alone is not enough.
  • Avoid it when

    • A limit must be checked on each write.
    • The exact value is needed at once.
    • Writes are few.