Sharded counters in detail
hard 28 minWhat a sharded counter needs in production: a cached total, write buffering with a known loss, a clear consistency promise, changing the number of shards live, replicas and failover, retries that do not count twice, and monitoring.
See it run
Cache, buffer, replicate, grow and shrink a counter, and see what each step can lose.
Operations
Cached total
Readers take one key; a miss sums three.
Step 1 of 4
Miss
500 + 498 + 502
The cache is empty, so all shards are read.
Step 1: Miss
def total(): v = cache.get("total") if v is not None: return v v = sum(store.mget(shards)) cache.set("total", v, ttl=5) return v- Saves
- N reads
- Price
- Seconds of age
- No cache
- every read asks every shard
Zero is a valid cached value. Compare with None.
In the real world
The same sharded counters in detail doing real jobs. Pick one and step through it.
Detection, redirect, promotion, and what was lost.
Step 1 of 4
Healthy
28 everywhere
Replicas copy from the primary a moment later.
Step 1: Healthy
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Deleting the total on each flush
majorThe cache is empty whenever traffic is high, which is when you need it.
Wrongstore.incrby(shard, d)cache.delete("total")Rightstore.incrby(shard, d)# "total" expires by timeLosing the last increments
majorIf only add() flushes, the buffer waits for a next request that may never come.
Wrongdef add(n): buffer += n if old(): flush()Rightevery(0.1, flush)on_shutdown(flush)Sum without the failed shard
criticalThe public count drops by a tenth and jumps back later.
Wrongsum(v or 0 for v in values)Rightif any(v is FAILED for v in values): return last_known_totalOne ping for all shards
minorThe same server answers ten times. Nine shards were never checked.
Wrongfor i in shards: redis.ping()Rightfor s in shards: connection_of(s).ping()
Interview tips
Memory trick: CACHE
- Cache totals
- Async write-behind
- Consistency trade-offs
- Health monitoring
- Elastic resharding
Memory trick: SCALE
- Shard above 80%
- Create new shards
- Adjust routing
- Leave old data
- Even distribution
Give three numbers
- How old a read can be.
- What a crash loses.
- What a failover loses.
Order of changes
- Grow: readers first.
- Shrink: writers first.
- Move values in one step.