Sharded counters
medium 22 minOne 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
- 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
- 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
criticalTwo writers read 10 and both write 11. One increment is lost.
Wrongn = get(key)set(key, n + 1)Rightincrby(key, 1)All shards in one slot
criticalThe hash tag puts every key on the same node.
Wrongkey = f"{{video_123}}:shard_{i}"Rightkey = f"video_123:shard_{i}"Returning a partial sum
majorWhen a shard times out, the count drops and then jumps back.
Wrongreturn sum(v for v in values if v)Rightif any_failed(values): return last_known_totalSharding everything
minorA million quiet counters with 100 shards are 100 million keys.
Wrongshards = 100Rightshards = 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.