PATTERN · ORIGINAL
Counting at scale: exact when it matters, approximate when it does not
Sharded counters, write batching, tumbling and sliding windows, HyperLogLog for distinct counts, count-min sketch for heavy hitters, and presence counts that decay on their own.
Counting looks like the easiest thing in system design: add one. It gets interesting when millions of people add one to the same thing, when you need "how many in the last hour" rather than "how many ever", or when the question is "how many different people". Each of those has a standard tool, and each tool is a trade between accuracy, freshness and cost.
Start with who reads the number
Before choosing a structure, decide three things about the count:
- How exact? An account balance or remaining inventory must be exact. A like count shown as "1.2M" can be off by thousands and nobody can tell. An analytics dashboard can be off by 1% if it says so.
- How fresh? A viewer count that is 5 seconds old is fine. A rate limiter that is 5 seconds old lets an attacker through.
- Can it go down? Unlikes, refunds and departures mean decrements, which some approximate structures cannot do.
Writing these down usually rules out half the options. The like counter needs durable, accurate-enough totals under hot keys. The page viewer count is presence, which decays. Live like updates is about pushing changes to watchers. They sound alike and need different tools.
Exact counts: sharded counters
A single counter row is serialized by its lock. Assume one row sustains about 1,000 increments per second. A post going viral at 50,000 likes per second needs at least 50 rows working in parallel.
A sharded counter keeps N rows per key, (post_id, shard) for shard 0 to N-1. Each increment picks a random shard. A read sums all N. Writes now scale with N; reads cost N lookups, so cache the sum for a second or two. You can start every key at 1 shard and grow N only for keys that run hot, which keeps reads cheap for the long tail.
For likes specifically, the count is not the source of truth. The truth is the set of (user_id, post_id) pairs, protected by a unique constraint so a double tap cannot like twice. The counter is a derived, rebuildable view of that set. That framing makes retries safe and gives you a way to repair drift.
Batching and aggregation
The bigger win is not to send one write per event at all.
- In-process batching: each API server accumulates deltas per key in memory and flushes every second. A post with 50,000 likes per second across 100 servers becomes 100 writes per second. If a server crashes, you lose up to a second of increments, which is acceptable for display counts only if you can rebuild from the source of truth.
- Log then aggregate: write each event to a durable log first, then have aggregators consume it and apply summed deltas per key per window. The log is the record, so a crashed aggregator replays from its last committed offset.
The subtle part is exactly-once application. If an aggregator writes a delta and crashes before committing its log offset, it will replay and apply the delta twice. Store the last applied offset in the same transaction as the delta, and skip anything at or below it. Consistency and idempotency covers this pattern in general. Keying the log by post ID also keeps one post's events in one partition, which is the trick from partitioning and ordering.
Time windows
"Shares in the last hour" is a different question from "shares ever". Two window shapes cover most needs:
- Tumbling windows are fixed and non-overlapping: 10:00 to 10:01, 10:01 to 10:02. Each event belongs to exactly one. They are cheap and good for rollups and charts.
- Sliding windows answer "the last 60 minutes as of now". Computing them event by event is expensive, so approximate: keep 60 one-minute tumbling buckets in a ring and sum them. The answer is accurate to within one bucket at the edge, and the work per query is 60 additions.
For several horizons, roll up: one-minute buckets for the last hour, hourly buckets for the last week, daily buckets for the last year. A 30-day count then reads 30 values, not 43,200. This is the backbone of most-shared articles and metrics aggregation.
Late events are the catch. A phone that was offline sends a share stamped 10:00:58 at 10:03. Decide on a lateness allowance (say 2 minutes) after which a bucket is final, and either drop or separately count anything later. Stream processors call the moving cutoff a watermark; on paper it is enough to say "buckets close 2 minutes after their end".
Distinct counts: HyperLogLog
"How many unique visitors this week" cannot be done by adding numbers: a person who visits on Monday and Tuesday must count once. Exact answers need a set of every visitor ID per page, which for a site with 10,000 popular pages and 5 million visitors each is far too much memory.
HyperLogLog trades a small error for tiny, fixed memory. The intuition: hash each ID, and track the longest run of leading zeros you have seen. Seeing a hash that starts with 20 zeros suggests roughly a million distinct inputs. Doing this across many registers and averaging tames the luck. The standard error is about 1.04 divided by the square root of the register count. With 16,384 registers (around 12 KB), that is under 1%.
Three properties make it a design tool, not just a trick:
- Fixed size. 12 KB whether you saw ten visitors or ten billion.
- Mergeable. The union of daily sketches gives a weekly sketch. Build one per page per day, and any range of days is a merge.
- No removal. You cannot subtract a visitor. For presence that decays, use buckets (below).
Use it in web analytics for unique visitors, and anywhere a dashboard says "unique" and can tolerate 1%.
Frequencies and heavy hitters: count-min sketch
Sometimes you need a count per item for millions of items, but only care about the big ones: the most-shared URLs, the IPs sending the most requests. A count-min sketch is a small grid of counters, d rows by w columns, with one hash function per row. To add an item, increment one counter in each row. To estimate, take the minimum across rows.
Collisions only ever add, so estimates are never low, only sometimes high. Size it from the error you can accept: width w = e / ε and depth d = ln(1/δ). For estimates within 0.1% of the total stream with 99% confidence, that is about 2,720 by 5, roughly 13,600 counters or 54 KB. On a stream of 100 million shares, 0.1% is 100,000, which is useless for small items and fine for spotting anything with over a million.
For top K, keep a count-min sketch alongside a min-heap of the K largest estimates seen so far, or use the Space-Saving algorithm, which tracks exactly K candidates with fixed memory. Pair either with tumbling buckets for windowed rankings. Top-K rankings adds anti-gaming and stable ordering on top; this gives you the raw candidates.
Presence: counts that decay
"3,412 people are viewing this page" is not a running total. It is how many sessions are alive right now, and the count must fall when people close the tab without saying goodbye. Heartbeats with expiry handle this:
- Each open page sends a heartbeat every 30 seconds with a session ID.
- The server records the session in the current 30-second bucket for that page.
- The viewer count is the number of distinct sessions in the current and previous bucket. Anyone who stopped heartbeating disappears within 60 seconds.
Do the arithmetic. 10 million concurrent viewers with 30-second heartbeats is about 333,000 writes per second. That is manageable in a partitioned in-memory store, keyed by page. A single page with 2 million viewers is a hot key; switch its buckets to HyperLogLog sketches, which merge across shards and keep memory flat, and display a rounded number. Rounding to "about 2.1M watching" also hides the 1% noise.
The same lease idea appears in reservations and contention for concurrent stream limits, where the count is enforced, not just shown. Pushing the changing number to watchers is a delivery problem, covered in fan-out and real-time delivery.
| Option | Wins when | Costs |
|---|---|---|
| Single counter row | Per-key write rate stays under about a thousand per second and the count must be exact. | One hot key serializes all writers. |
| Sharded counter | Exact totals with a few very hot keys. | Reads sum N shards; you need logic to grow N for hot keys. |
| Log plus windowed aggregation | High event volume, many keys, and seconds of staleness is fine. | Seconds of lag, an aggregation tier, and offset bookkeeping for exactly-once. |
| HyperLogLog | Distinct counts where about 1% error is acceptable and windows must merge. | Approximate; no deletes; no per-item answers. |
| Count-min sketch plus heap | Finding heavy hitters among millions of items in fixed memory. | Overestimates small items; needs a separate structure for the actual ranking. |
| Heartbeat buckets | Live presence that must decay without explicit leave events. | Constant heartbeat traffic; count lags reality by up to two buckets. |
TAKE THIS TO YOUR NEXT SKETCH
- Decide how exact, how fresh and whether the count can decrease before you choose a structure.
- Keep the source of truth (who liked what) separate from the derived count, so counts can be rebuilt and retries are safe.
- Batch before the database: in-process deltas or a log plus aggregators turn per-event writes into per-window writes.
- Build sliding windows from tumbling buckets and roll up to coarser buckets for long horizons; set a lateness cutoff.
- Reach for HyperLogLog for distinct counts, count-min or Space-Saving for heavy hitters, and heartbeat buckets for presence.
PRACTICE WITH THIS
Now sketch one.
OFF-SITE READING · NOT WRITTEN BY US
Further reading
- HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm
The original algorithm; the first two pages give the intuition and the error formula you need for a design discussion.
- HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm
How a team that runs it at scale fixed small-range bias and memory use, a good reminder that the textbook version needs tuning.
- Efficient Computation of Frequent and Top-k Elements in Data Streams
Introduces the Space-Saving algorithm, a simple fixed-memory way to track heavy hitters that pairs well with the windowing ideas here.
- Count-min sketch
A practical look at sizing a count-min sketch by error and probability, and at its overestimate-only behavior.