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.
Video lesson · Chapter 1 of 5
A five-second scoreboard keeps the stands responsive
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
2007
The HyperLogLog paper: an estimate of how many different items were seen, with a typical error of about 2% in 1.5 kB.
2011
Conflict-free replicated data types are formally defined. The PN-counter keeps increments and decrements apart so that replicas can merge.
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.
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.
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
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
How old can a read be?
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 process | Shared, such as Redis | |
|---|---|---|
| Speed | Fastest, no network | One network hop |
| View | Each server has its own age | All servers see the same |
| Memory | Once per server | Once |
| Failure | Dies with the process | One more service; fall back to the last known total |
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
Example: 45,230 increments a second over 20 servers
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
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
Flush on a timer
Not only when the next increment arrives, or the last ones wait for ever.
- 3
Flush on shutdown
Deployments stop servers every day. That must not lose counts.
- 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.
| Method | How | For |
|---|---|---|
| Accept it | No retry, or retry and overcount a little | Views |
| Unique row | Insert user and post first; count only if it was new | Likes, follows |
| Event id | Same id goes to the same shard, which remembers recent ids and updates both in one step | Metered events |
| Log | Append to a log, aggregate with a saved position, rebuild when needed | Billing, audits |
Promise
Three consistency levels
| Level | Latency | Availability | Accuracy | Example |
|---|---|---|---|---|
| Eventual | Low | High | Seconds old | Video views |
| Read your own writes | Low | High | Your own change is visible | Like button |
| Fresh sum | Higher | Needs all shards | All confirmed writes | Operations view |
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: for 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
Grow
More shards while running
- 1
Watch
Writes, latency and queue depth per shard.
- 2
Trigger
A shard stays above 80% of its measured safe rate. Act at a quiet time, not at the peak.
- 3
Create
New shards at zero, with replicas.
- 4
Tell readers, then writers
Readers sum the larger set first. When all have it, writers may use it.
- 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
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
- 1
Detect
Missed heartbeats, timeouts. Ask each shard, not one server ten times.
- 2
Redirect writes
Pick another shard while this one is down. Any shard is as good: that is the gift of adding.
- 3
Reads
Show the last known total. A sum without the shard would make the count drop.
- 4
Promote
A replica becomes primary. The loss is at most lag times write rate of that shard.
- 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
| Metric | Target | Alert |
|---|---|---|
| Writes a second per shard | Below the safe rate, for example 1,000 | Above 80% of it |
| Write latency p99 | Below 10 ms | More than twice the normal |
| Read latency p99 | Below 50 ms | More than twice the normal |
| Cache hit rate | Above 95% | Below 90% |
| Errors | Below 0.1% | Above it for 5 minutes |
| Replica lag | Below 1 s | Above 5 s |
| Heartbeat | Every few seconds | Missing: page someone |
| Counter minus recount | Within the promised error | Outside it |
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.