Sharded counters
medium 22 minOne counter that everybody increments becomes a hot key: all writes wait in one line.
Video lesson · Chapter 1 of 5
A view counter attracts every writer to one row
Theory
Read or listen first. About 1 min.
What it is
A counter is a number that only needs adding to: views, likes, downloads. When very many clients add to the same one at the same moment, they compete for a single row on a single machine. That row is a hot key.
A sharded counter keeps smaller counters, called shards, for the same thing. A write picks one shard and adds to it. A read fetches all and sums them. The true value is the sum; no shard knows it alone.
Why it exists
Adding is special: the order does not matter. Three plus five plus two is ten, however you group it. So the additions can happen in different places at the same time, and be combined later.
Most data cannot be split this way. A counter can, and one of the cheapest tricks in system design turns a write limit of one machine into the limit of many. The price is paid by readers, who now have to ask everybody.
A short history
2007
The HyperLogLog paper shows how to estimate how many different items were seen with very little memory: the other classic counting problem.
2011
Marc Shapiro and colleagues formally define conflict-free replicated data types. The grow-only counter, one number for each replica and a sum to read it, is the textbook example.
18 March 2014
Java 8 is released with LongAdder: one counter inside, many cells under contention, a sum on demand. The same idea inside one process.
Words to know
- Hot key
- One key that receives far more requests than the others.
- Contention
- Waiting because others want the same thing.
- Shard
- One of the partial counters.
- Aggregate
- Combine the partial values, here by adding.
- Atomic increment
- Add in one step, so two writers cannot overwrite each other.
- Fan-out
- One request that causes many.
How it works
Step through the idea, or press Play.
Split. Keep N partial counters on different machines
Understand it
Start here
Counting at the orchard
It is harvest day. Every picker who leaves the orchard must be counted. With one clicker at one gate, everybody waits.
Writers became fast because readers took over the adding.
Problem
Why one counter becomes hot
Everyone writes one key
Lock contention
A transaction holds the row until it commits. The next one waits.
Database hotspot
One row or document is overwhelmed while the rest of the cluster is idle.
One machine's network
All requests for the key arrive at the same node.
No scaling out
Adding nodes moves other keys away, never this one.
How much is too much? It depends on the store. If a transaction keeps a row locked for 5 ms, that row accepts at most 200 increments a second, on any hardware. DynamoDB gives one partition at most 1,000 write units a second. An in-memory server does far more for one key, until its single command thread is full.
The limit of one locked row
Solution
Write one, read all
Three shards on three nodes
- 1
Create N shards
N keys instead of one, each starting at zero, on different nodes.
- 2
Distribute writes
Pick a shard at random and increment it.
- 3
Aggregate reads
Fetch all shards and add.
- 4
Add shards
When traffic grows, raise N. Old values stay where they are.
The write path
The read path
Data
The keys
counter:video_123:shard_0 -> 12,345counter:video_123:shard_1 -> 12,344counter:video_123:shard_2 -> 12,345counter:video_123:shard_3 -> 12,346counter:video_123:shard_4 -> 12,344total 61,724Choose
Which shard does a write use?
| Strategy | Rule | Good | Less good |
|---|---|---|---|
| Random | A random number below N | Simple, no state | Uneven for short moments |
| Round robin | Next number, modulo N | Even | A shared position is a hot counter itself; keep one per process |
| Hash | Hash of user or request, modulo N | Same input, same shard | One busy user loads one shard |
Numbers
How many shards?
Shards from the peak
Worked examples
| Peak writes | Safe rate of a shard | Shards | Each shard gets |
|---|---|---|---|
| 1,000/s | 100/s (locked rows) | 10 | 100/s |
| 10,000/s | 200/s | 50 | 200/s |
| 100,000/s | 1,000/s | 100 | 1,000/s |
A viral video: 10 million views in one hour are 10,000,000 / 3,600 = 2,778 a second on average. Spread over 100 shards that is 28 a second each. If the peak is three times higher, 8,333 a second, each shard sees 83. A row limit of 200 a second would need 42 shards. A store that takes 10,000 a second on one key would need none, so check before building.
Reads
The price, and how to pay less
The slowest shard decides
So do not sum on each page view. Sum every few seconds and cache the result: one read then costs one key. Ten thousand readers a second with a 5 second cache cause one aggregation in 5 seconds for each counter, if only one process recomputes it. The detailed version is in sharded counters in detail; caching one very hot key is in high-concurrency caching.
You gain
- Write capacity in proportion to N
- No waiting for one lock
- Losing one shard stops a part of the writes, not all
- Plain atomic increments
You pay
- Reads visit N shards
- The sum is not one moment in time
- More keys and more code
- Lowering N later needs care
Accuracy
How exact is the total?
Every increment is counted once on its shard, so the total becomes exact when writing pauses. While writes continue, the shards are read at slightly different moments, and the sum may match no single instant. For a counter that only grows, the sum lies between the value when the read began and the value when it ended.
Good and bad fits
| Counter | Shard it? | Why |
|---|---|---|
| Views of a viral video | Yes | Many writes, a few seconds of age do not matter |
| Likes on a popular post | Yes | Keep the list of who liked as the truth |
| Page hits, metrics | Yes | Written constantly, read by a dashboard |
| API rate limit per user | Rarely | One user is seldom hot, and the limit needs a fresh value |
| Tickets left to sell | No | Must never go below zero |
| Bank balance | No | Needs a check and a write in one step |
| 20 writes a second | No | One row is enough |
Should I shard this counter?
Alternatives
Other ways to count a lot
- 1
Buffer and batch
Each server adds in memory and writes +500 once. Often this alone is enough. A crash loses the buffer.
- 2
Log and aggregate
Write each event to a log such as Kafka and let a consumer add them up. The log can be replayed, so counts can be checked and repaired.
- 3
Approximate
To count different visitors use HyperLogLog. In Redis it needs up to 12 KB and has a standard error of 0.81%. Sharded counters count events, not different people.
Growing
Adding shards
Because the total is a sum, a new shard starts at 0 and nothing moves. Going from 5 to 8 shards raises the write capacity by 60% (8 / 5 = 1.6). One rule: readers must learn the new N before writers use it, or the new shards are missing from the sum. Going down is harder, and is covered in the detailed topic. Compare this with sharding a database, where rows must move.
Growing in the safe order
Summary
The whole topic in one minute.
A sharded counter spreads the writes of one hot counter over several shards on different machines. A write is one atomic increment on a shard chosen at random. A read sums all shards, usually once in a while into a cached total.
Choose the number of shards from the peak write rate and the safe rate of one shard. More shards mean more write capacity and slower, less certain reads. If writes are few, do not shard at all.
- One key lives on one primary, so more nodes do not cool a hot counter.
- Write one shard, read and add all.
- Random choice is enough; place shards on different machines.
- Shards = peak writes / safe rate of one shard, rounded up.
- Cache the sum: the slowest shard decides an uncached read.
- Do not shard balances, stock or quiet counters.