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.

Video lesson · Chapter 1 of 5

A five-second scoreboard keeps the stands responsive

0:00 / 3:32

Theory

Read or listen first. About 1 min.

What it is

The idea of a sharded counter fits in one sentence: write one shard, read and add all. Running one for years raises other questions. How old may the total be? What is lost when a machine stops? How do you add or remove shards while people are counting?

This topic answers them one by one. Each answer is a small mechanism with a number attached: a refresh time, a buffer time, a trigger, a lag.

Why it exists

A counter looks harmless, and its mistakes are quiet. Nothing crashes when a count is 2% too high. Somebody notices weeks later, when an invoice or a chart does not fit. So the design has to say in advance which errors are possible and how large they can be.

The mechanisms also work against each other. Buffering makes writes cheap and reads older. Deleting the cache after each write makes reads fresh and the cache useless. Knowing the numbers is what lets you choose.

A short history

  1. 2007

    The HyperLogLog paper: an estimate of how many different items were seen, with a typical error of about 2% in 1.5 kB.

  2. 2011

    Conflict-free replicated data types are formally defined. The PN-counter keeps increments and decrements apart so that replicas can merge.

  3. 18 March 2014

    Java 8 is released. Its LongAdder grows the number of cells when threads collide: resharding a counter inside one process.

Words to know

TTL
Time to live: how long a cached value may be used.
Write-behind
Collect writes in memory and send them later as one.
Replication lag
How far a replica is behind its primary.
Failover
A replica takes over from a failed primary.
Drain
Stop writing to a shard, then move what is left.
Idempotent
Doing it twice has the same effect as doing it once.

How it works

Step through the idea, or press Play.

Step 1 of 3

Make it cheap. Cached totals for readers, buffers for writers

Understand it

Start here

The tally keeper

Asha now runs all the gates of the orchard. Counting is easy. Deciding is the job: how many gates, when to write down, what to do when a clicker breaks, and how to close a gate without losing its count.

Five decisions at the gates
0Gate 10Gate 20Gate 30Gate 460 a minute / 20 = 3 gates

In every frame the total can be explained. That is the whole point.

Shape

The production picture

Buffers, shards with replicas, a cached total, metrics

Clients add to and read from a counter service with two instances, each with its own buffer. Buffer 1 sends plus 37 to shard 2 and buffer 2 sends plus 42 to shard 1. Each of the three shards has a primary copying to a replica. The service reads totals from a cache and sends metrics to a monitoring system.
Between writers and shards there is a buffer, between shards and readers a cache.
  • Caching

    A cached total for readers, a buffer for writers.

  • Consistency

    Eventual, read your own writes, or fresh.

  • Resharding

    Grow and shrink without stopping.

  • Monitoring

    Per shard, with alerts and a recount.

Reads

A cached total

Read through a cache

One miss costs N reads. When the value expires, let one process recompute it, or a background job refresh it before it expires.

How old can a read be?

age≤tbuffer+tlag+tTTL0.1 s+0.2 s+5 s=5.3 s\text{age} \le t_{\text{buffer}} + t_{\text{lag}} + t_{\text{TTL}} \qquad 0.1 \text{ s} + 0.2 \text{ s} + 5 \text{ s} = 5.3 \text{ s}
Buffer time, replica lag (if reads use replicas) and cache time add up. The values are examples; add the time of one aggregation.

Do not delete the cached total on each flush. Twenty servers that flush every 100 ms would delete it 200 times a second, and it would hardly ever be hit. Let it expire by time.

Where to cache

In the processShared, such as Redis
SpeedFastest, no networkOne network hop
ViewEach server has its own ageAll servers see the same
MemoryOnce per serverOnce
FailureDies with the processOne more service; fall back to the last known total
Both together work well: 1 s in the process, 5 s shared. A very hot total is itself a hot key: see high-concurrency caching and distributed caching.

Writes

Buffer before you write

Each server adds in memory and flushes as one increment after 100 ms or 1,000 operations, whichever comes first.

Write-behind

Three requests, one write. At high rates it is hundreds to one.

Example: 45,230 increments a second over 20 servers

writes=20×10.1 s=200/slost in one crash≤45,23020×0.1≈226\text{writes} = 20 \times \frac{1}{0.1 \text{ s}} = 200/\text{s} \qquad \text{lost in one crash} \le \frac{45{,}230}{20} \times 0.1 \approx 226
If each flush goes to one shard. One random shard for every increment would make up to N writes per flush instead.

You gain

  • Far fewer writes
  • Cheap increments for the caller
  • Often no need for many shards
  • Short outages of a shard can wait in the buffer

You pay

  • A crash loses the buffer
  • Reads are older by the buffer time
  • Memory for waiting deltas
  • A flush that times out may be applied or not

A correct flush

  1. 1

    Swap, then send

    Take the buffer out under the lock and replace it by an empty one. Send outside the lock, so writers do not wait for the network.

  2. 2

    Flush on a timer

    Not only when the next increment arrives, or the last ones wait for ever.

  3. 3

    Flush on shutdown

    Deployments stop servers every day. That must not lose counts.

  4. 4

    Put back only what certainly failed

    After a timeout nobody knows. Retry with an id, or accept a small error and recount later.

Retries

Counting once

An increment is not idempotent. If the reply is lost and the client repeats it, the count is one too high; if the client gives up, it may be one too low. Choose per counter.

MethodHowFor
Accept itNo retry, or retry and overcount a littleViews
Unique rowInsert user and post first; count only if it was newLikes, follows
Event idSame id goes to the same shard, which remembers recent ids and updates both in one stepMetered events
LogAppend to a log, aggregate with a saved position, rebuild when neededBilling, audits

Promise

Three consistency levels

LevelLatencyAvailabilityAccuracyExample
EventualLowHighSeconds oldVideo views
Read your own writesLowHighYour own change is visibleLike button
Fresh sumHigherNeeds all shardsAll confirmed writesOperations view
For a security limit, do not sum shards. Use one owner per user and an atomic check, as in a rate limiter.

Read your own writes. Sending a user back to the same shard shows only that shard, not the total. The simple way is to show the cached total plus the user's own recent change, kept in their session until a newer total includes it.

Fresh sum. Read the primary of each shard. If shards are replicated with quorums, write and read sets must overlap: W+R>nW + R > n for nn copies. A read majority alone is not enough. Even then each shard is read at its own moment, so the sum is not a snapshot.

The consistency window

Between writing and refreshing, readers are behind. Publish the length of this window.

Grow

More shards while running

  1. 1

    Watch

    Writes, latency and queue depth per shard.

  2. 2

    Trigger

    A shard stays above 80% of its measured safe rate. Act at a quiet time, not at the peak.

  3. 3

    Create

    New shards at zero, with replicas.

  4. 4

    Tell readers, then writers

    Readers sum the larger set first. When all have it, writers may use it.

  5. 5

    Leave the old data

    Nothing is moved. Old shards simply hold more for ever, and only the write rate matters.

Powers of two are convenient, not required. Consistent hashing matters for placing keys on machines, not for choosing a random shard. Keep the number of shards as configuration with a version, changed by a policy rather than by hand, and not every few minutes.

Shrink

Fewer shards

Draining a shard

The opposite order of growing. The fourth step must be one transaction: a crash in the middle counts twice or not at all.

If the two keys cannot share a transaction, do not move anything. Keep the old shard as a read-only base value. One extra read is cheaper than a wrong number.

Failure

When a shard fails

Failover

With asynchronous replication, confirmed increments can be lost. Redis documents this for its cluster.
  1. 1

    Detect

    Missed heartbeats, timeouts. Ask each shard, not one server ten times.

  2. 2

    Redirect writes

    Pick another shard while this one is down. Any shard is as good: that is the gift of adding.

  3. 3

    Reads

    Show the last known total. A sum without the shard would make the count drop.

  4. 4

    Promote

    A replica becomes primary. The loss is at most lag times write rate of that shard.

  5. 5

    Reconcile

    Recount from the source of truth if the difference matters.

To lose less, wait for replicas before confirming. That raises write latency, and in Redis the WAIT command improves safety without making the store strongly consistent, as its documentation says.

Watch

Metrics and alerts

Starting points, to be replaced by your own measurements

MetricTargetAlert
Writes a second per shardBelow the safe rate, for example 1,000Above 80% of it
Write latency p99Below 10 msMore than twice the normal
Read latency p99Below 50 msMore than twice the normal
Cache hit rateAbove 95%Below 90%
ErrorsBelow 0.1%Above it for 5 minutes
Replica lagBelow 1 sAbove 5 s
HeartbeatEvery few secondsMissing: page someone
Counter minus recountWithin the promised errorOutside it
The last row is the one that tells you whether the number is right.

A dashboard might say 45,230 writes a second, 8.2 ms average, 16 shards, 0.02% errors. That is 2,827 a second for each shard. Averages hide the one shard at 95%, so draw all sixteen bars.

Summary

The whole topic in one minute.

Serve a cached total that one job refreshes, and buffer increments in each server for a short time. Say the two resulting numbers: how old a read can be, and how many increments a crash can lose.

Grow by telling readers first, shrink by telling writers first and then draining. Replicate each shard and know the lag. Make retries safe with event ids or a source of truth, recount regularly, and watch each shard, not only the average.

  • Cache the total by time; never delete it on every write.
  • Buffer per server, flush one delta to one shard, and state the loss: rate per server times buffer time.
  • An increment is not idempotent: accept, deduplicate, or keep a source of truth.
  • Grow: readers first. Shrink: writers first, then drain in one step.
  • Asynchronous failover can lose confirmed increments; a missing shard must not lower the shown total.
  • Watch each shard, and recount.

Sources