Problem
Product and data teams often need the number of unique users or items: users who viewed a post, or items matching a complex filter. Exact counting needs a lot of time or memory, while an approximate value with a preset accuracy is usually enough. Set sizes range from a handful to hundreds of millions, and one structure must handle both ends.
Example from the article: counting the unique users who viewed a post on a social network, where views range from a few to hundreds of millions.
Solution in brief
HyperLogLog (HLL) hashes each element and keeps only the maximum hash "rarity" in each of buckets, so memory is constant and elements are not stored. The author fixes the bias at small sizes with a bias correction and LinearCounting, and adds a sparse representation for tiny sets. Two HLLs merge by a per-register maximum, which gives unions, intersections and differences.
Questions this case answers
- How to count distinct elements in a stream with constant memory and a known error bound when exact counting is too expensive
- How to combine counts of overlapping groups of items and estimate their union, intersection and difference from precomputed compact summaries
- How to count unique users or items in a stream with fixed, small memory?
- How to keep the accuracy of a distinct count good for both tiny and huge sets?
Tools and methods
- HyperLogLog — distinct count in constant memory.
- Bias correction — polynomial fit of the raw-estimate bias.
- LinearCounting — estimate from empty registers, better on small sets.
- Sparse representation — 32-bit (index, rank) pairs for small sets.
- HLL merge — register-wise maximum, then inclusion-exclusion.
Google or a one-time email code. No password.