The shape
Every system counts something, and it often pays for the exact answer. It pays in memory, in coordination (the locks and round trips that make machines agree on one number), or in both. The move is to notice that nobody needs the exact value, decide how much error is acceptable, and trade that error for a large saving.
The saving can be a factor of thousands. To count distinct items exactly, you have to keep every item you have seen, so memory grows with each new one. The alternative is a sketch: a small, fixed-size summary that answers "how many distinct" without storing the items at all. A 12 KB sketch is accurate to within about 1 percent, whether you saw 1,000 things or 1 billion. The exact set keeps growing for as long as new items arrive, and the sketch stays at 12 KB. Some designs are only possible because of that difference.
Three examples:
- "How many distinct users viewed this?" The exact answer needs a set of every user id. The approximate answer needs a HyperLogLog sketch, the standard sketch for counting distinct items, which takes a few kilobytes.
- "Has this client exceeded 100 requests per minute?" The exact answer stores a timestamp for every request. The approximate answer estimates the window from two counters, or uses a token bucket, which keeps a count of tokens and never stores a request at all.
- "How many likes does this post have?" The exact answer locks the row and reads the latest committed value. The approximate answer reads a cached total that is a few seconds behind.
All three have the same structure. A number drives a decision, and the decision stays the same across a range of values. If that range is wide, you are paying for precision that nobody uses.
The moves
Three different techniques share this name, and each one gives up something different. Mixing them up is a common mistake.
How many distinct? This technique is called probabilistic cardinality, where cardinality means the number of distinct items. A HyperLogLog sketch answers it from 12 KB with a standard error of about 0.81 percent, whatever the true count is. Standard error means a typical estimate lands within about 0.81 percent of the true count. Two properties matter as much as the size. First, sketches merge. A sketch is an array of small numbers called registers, and you merge two sketches by taking the larger value at each position. The result is exactly the sketch you would have got by counting both streams together from the start. So each shard counts on its own with no coordination, and you combine the sketches at read time. Second, the error is calculated, not measured in testing. The 0.81 percent follows from the sketch's size before you count anything, so you can put it in a design review the way you would put a latency budget in one.
Bloom filters belong to the same family, but they answer a different question: is this item in the set, rather than how many items there are. Their error runs in one direction only. A Bloom filter can say an item is present when it is not. It never says an item is absent when it is in the set. So it is safe for "skip the expensive lookup if this is definitely not here", and never safe for "this is definitely present".
How many in total? This technique is called bounded staleness. Each node keeps a counter in memory and, on a timer, adds it to a shared data store such as a database or Redis. Each of those writes is a flush. At any moment the total in the store is behind by at most one flush interval times the write rate. Once every node has flushed, the total is exact, unless a node crashed and lost the count it held in memory. You give up freshness, not accuracy, and you choose the maximum error when you set the interval.
How many recently? This technique is called windowed estimation. You keep one counter per fixed window, such as each calendar minute. To estimate a sliding window, such as the last 60 seconds, you add the current minute's count to a share of the previous minute's count. The share is the part of the previous minute that still falls inside the last 60 seconds. That is two integers per key instead of a list of timestamps. The error does not come from chance. It comes entirely from assuming the previous window's traffic was evenly spread, so a burst at the wrong moment makes the estimate too high or too low.
Counting distinct viewers of one popular item:
exact, a set of 8-byte user ids
10M distinct = 80 MB
100M distinct = 800 MB
per item, and it grows forever
HyperLogLog sketch
10M distinct = 12 KB
100M distinct = 12 KB
standard error = 0.81%
⇒ at 10M distinct, 6,600x less memory
⇒ at 100M distinct, 66,000x less memory
⇒ the sketch does not grow. That is the point.
Now the question that decides whether it is allowed:
the number is rendered as "10.2M views". The display
rounds to three significant figures anyway, so it has
already thrown away about 0.5% either way. The sketch's
0.81% error is the same size as that rounding.
Nobody can see the error. It was never in the output.This is the general test. Follow the number to the place where a person or a decision uses it, and check how much precision is still there. Often the steps after the count were already throwing the exactness away, through rounding, a chart axis, or a threshold with a wide range around it.
How to tell you have this problem
Memory grows with distinct things rather than with active things. Look for a per-item structure that gets bigger the longer the item exists, and that holds identifiers only so it never counts anyone twice. That is the cardinality case. Plot that structure's size over time. If the line never flattens, you have this problem.
A counter is a coordination point. If each increment needs a lock, a round trip to the one node that owns the counter, or a transaction, and increments arrive fast, that is the staleness case. Look for a row whose write rate is 100 times or more above the rest of its table.
You are storing timestamps to answer a question about a window. If you keep a list of request times per key and trim it on every read, that is the windowed case. The sign is that memory per key grows with the request rate instead of staying fixed.
Before choosing any technique, ask one question: who or what uses this number? A billing system needs it exact, because it charges money against it. A dashboard does not, because nobody looking at a chart can tell it is off by 1 percent. If the answer is "we show it on a page", or "we compare it to a threshold somebody picked by feel", then nothing after the count needs it exact. You can trade the exactness for memory or for coordination.
What it costs
The error has a direction, and you must know which. A rate limiter that undercounts lets abuse through. One that overcounts rejects real users. The two are not equally bad, and the product usually prefers one of them strongly. "Roughly 100 requests a minute" is not a specification. "At most 5 percent over, never under" is: up to 5 percent extra may get through, and nobody under the limit is ever rejected.
Approximate numbers end up in places that need exact ones. The count you showed on a page gets copied into a report, and then into an invoice. Nothing in the type system stops this. The defence is the name: call the field estimated_views, not views, so the next person has to think about it.
You cannot look inside a sketch when it is wrong. You can open an exact set and diff it against another. A HyperLogLog register array tells you nothing when you look at it. So when a count seems wrong, you cannot tell whether it is the expected error, a bug in the merge, or a real change in the count. The fix is a control: pick a handful of keys and count them both ways, exactly and with the sketch. If the two stay within the sketch's expected error, it is working as designed. If they drift further apart, you have a bug, not noise.
The staleness bound breaks during incidents. The count is at most one flush interval behind only while flushes succeed. When the data store is down and flushes start to queue, the gap grows with no limit. This happens exactly when people are looking at dashboards to understand the incident.
Merging has its own rules. Two sketches merge correctly only if they use the same parameters and the same hash function. So changing a parameter is a migration. If you mix versions, you get wrong answers rather than errors, and nothing warns you.
Where it shows up in the course
| article | the form it takes there |
|---|---|
| Bloom Filters and Probabilistic Structures | the membership half of the family, and why a Bloom filter cannot answer a question about how many |
| Design a Leaderboard / Ranking Service | ranks deep in the board are estimated from counts taken once a second; the top 10,000 and final standings stay exact |
| Design an Ad Click Aggregator | billed clicks stay exact: a 1 percent error in the live count would mislead pacing and hide the gaps reconciliation looks for |
| Distributed Rate Limiter | the sliding window counter, estimating a rolling window from two fixed ones, and the burst pattern that defeats the even-spread assumption |
| URL Shortener | HyperLogLog for unique visitors, where exact distinct counts over a petabyte cost far more than the answer is worth |
| Live Comments and Reactions | hearts are summed on each gateway and sent on once a second, so a gateway that dies loses a second of taps that nobody can see |
Getting it wrong
Reaching for a sketch before stating the tolerance. The error you can accept, the error budget, should choose the technique. If you pick the technique first, the budget becomes whatever the technique happens to give. That is the wrong way round.
Assuming the error is the same for every count. HyperLogLog's 0.81 percent is a standard error, a typical spread across many counts. It is not a promise about your one count, and roughly one estimate in three lands further out than that. Small counts use a different method entirely, linear counting rather than the HyperLogLog formula, because that formula is known to be biased when the count is small.
Using an approximate count where money or law is involved. Billing, quota that customers pay for, and anything that gets audited need the exact count. You can show the estimate and bill from the ledger. You cannot bill from the estimate.
Forgetting that the sliding window estimate assumes even traffic. The estimate is exact only if the previous window's traffic was evenly spread. Bursts around window boundaries are exactly the traffic a rate limiter is meant to catch.
Letting staleness be undefined. "Eventually consistent" is not a bound. The flush interval is. Put it in the design, and put the time since the last successful flush on a dashboard. During an incident, that number tells you whether the counts you are looking at can be trusted.