AlgoViz

Sharded counters

medium 22 min

One 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

0:00 / 3:29

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 NN smaller counters, called shards, for the same thing. A write picks one shard and adds to it. A read fetches all NN 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

  1. 2007

    The HyperLogLog paper shows how to estimate how many different items were seen with very little memory: the other classic counting problem.

  2. 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.

  3. 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.

Step 1 of 3

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.

One clicker, then four
12Gate 1One gate, one queue

Writers became fast because readers took over the adding.

Problem

Why one counter becomes hot

Everyone writes one key

Three groups of clients all send add 1 to one database node that holds one counter.
More database nodes do not help: one key lives on one primary.
  • 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

ratemax⁡=1tlock=10.005 s=200 per second\text{rate}_{\max} = \frac{1}{t_{\text{lock}}} = \frac{1}{0.005 \text{ s}} = 200 \text{ per second}

Solution

Write one, read all

Three shards on three nodes

Writers and readers reach a counter service through a load balancer. The write path sends one write to shard 1 on node 1. The read path reads shard 1, 2 and 3 on three nodes.
Pink: a write touches one shard. Blue: a read touches all.
  1. 1

    Create N shards

    N keys instead of one, each starting at zero, on different nodes.

  2. 2

    Distribute writes

    Pick a shard at random and increment it.

  3. 3

    Aggregate reads

    Fetch all shards and add.

  4. 4

    Add shards

    When traffic grows, raise N. Old values stay where they are.

The write path

One step, no coordination with other writers: O(1).

The read path

N values are fetched in parallel and added: O(N) work.

Data

The keys

Text
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,724
The number of shards belongs to the counter: small counters can have 1.

Choose

Which shard does a write use?

StrategyRuleGoodLess good
RandomA random number below NSimple, no stateUneven for short moments
Round robinNext number, modulo NEvenA shared position is a hot counter itself; keep one per process
HashHash of user or request, modulo NSame input, same shardOne busy user loads one shard
Random is the default. Hash by request id when a retry must reach the same shard, for example to recognise a duplicate.

Numbers

How many shards?

Shards from the peak

N=⌈peak writes per secondsafe writes per second of one shard⌉N = \left\lceil \frac{\text{peak writes per second}}{\text{safe writes per second of one shard}} \right\rceil
Peak is three times the average unless you know better. Measure the safe rate on your store and leave room.

Worked examples

Peak writesSafe rate of a shardShardsEach shard gets
1,000/s100/s (locked rows)10100/s
10,000/s200/s50200/s
100,000/s1,000/s1001,000/s
The safe rates are assumptions to replace by your measurement. Capacity grows in proportion to N as long as the shards are on independent machines.

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

P(at least one slow)=1−0.99NN=10:9.6%N=100:63%P(\text{at least one slow}) = 1 - 0.99^{N} \qquad N = 10: 9.6\% \qquad N = 100: 63\%
If each shard is slow once in a hundred requests and they are independent, almost two reads in three at 100 shards meet a slow one.

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

CounterShard it?Why
Views of a viral videoYesMany writes, a few seconds of age do not matter
Likes on a popular postYesKeep the list of who liked as the truth
Page hits, metricsYesWritten constantly, read by a dashboard
API rate limit per userRarelyOne user is seldom hot, and the limit needs a fresh value
Tickets left to sellNoMust never go below zero
Bank balanceNoNeeds a check and a write in one step
20 writes a secondNoOne row is enough

Should I shard this counter?

Alternatives

Other ways to count a lot

  1. 1

    Buffer and batch

    Each server adds in memory and writes +500 once. Often this alone is enough. A crash loses the buffer.

  2. 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. 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

Between the second and the last step the total is already right, because empty shards add zero.

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.

Sources