Video in progress
When should you accept a probabilistic algorithm instead of an exact one? How do you agree on this decision with the business?
When the exact answer gets expensive (memory, latency, or the cost of merging across many nodes) and the error margin doesn't affect a business decision. I ask "who will make which decision based on this number?". Money, legal matters and user-visible promises must be exact; analytics, monitoring and recommendations are usually approximate.
📖 Answer
Typical pairs:
| Question | Exact | Approximate | Error |
|---|---|---|---|
| Unique users | COUNT(DISTINCT), O(n) memory |
HyperLogLog, ~12 KB | ~0.8% |
| Is the element present | HashSet |
Bloom filter | false positives, tunable |
| Frequency, top-K | a full Map |
Count-Min, Space-Saving | overestimate |
| Quantiles (p99) | all the values | t-digest, HdrHistogram | relative, more precise in the tail |
The hidden strength of approximate structures is merging. 50 servers send their own HyperLogLog, and at the center you take the maximum register by register to get the overall unique count. For an exact unique count you would have to gather all the IDs in one place. In Redis that's PFADD/PFCOUNT/PFMERGE.
This is the order I think in:
- Who uses the number? "1,204,331 people visited the site today": on a dashboard, saying 1.2 million is enough. "A plan for more than 1,000 active users this month": that's billing, and it must be exact.
- Is the error close to the decision threshold? In an A/B test the difference is 0.5% and the sketch error is 1%: you can't make a decision with an approximate result.
- In which direction is the error? A Bloom filter can only say "there's an extra one", Count-Min can only overcount. In rate limiting, an overestimate means a slightly stricter limit, which is usually acceptable.
- The cost of explaining. If a user-visible "1,245 views" turns into 1,239 the next day, support tickets come in. For numbers that must be monotonic, an approximate algorithm is awkward.
I put the agreement with the business in writing: "unique visitors: HyperLogLog, up to ±2%, for analytics only; billing is counted separately and exactly". A year later, that's a ready answer to "why don't the numbers match?".
There is a hybrid too: the real-time dashboard is approximate, and at night a batch job computes it exactly and replaces the daily number. Often that is the best compromise.
Sign up to mark studied questions and save your progress.