AlgoViz

Sharded counters in detail

hard 28 min

What 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

Our systemReadersCounter serviceCached totalemptyShard 0500Shard 1498Shard 2502

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

Counter servicePrimary28Replica A28Replica B28

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

    major

    The cache is empty whenever traffic is high, which is when you need it.

    Wrong
    store.incrby(shard, d)cache.delete("total")
    Right
    store.incrby(shard, d)# "total" expires by time
  • Losing the last increments

    major

    If only add() flushes, the buffer waits for a next request that may never come.

    Wrong
    def add(n):    buffer += n    if old(): flush()
    Right
    every(0.1, flush)on_shutdown(flush)
  • Sum without the failed shard

    critical

    The public count drops by a tenth and jumps back later.

    Wrong
    sum(v or 0 for v in values)
    Right
    if any(v is FAILED for v in values):    return last_known_total
  • One ping for all shards

    minor

    The same server answers ten times. Nine shards were never checked.

    Wrong
    for i in shards: redis.ping()
    Right
    for 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.