Video in progress

You need to count unique users in real time on a huge table. How does HyperLogLog work, and what are its limitations?

It tracks the number of leading zeros in each element's hash: a long run of zeros means many distinct elements were seen. It splits the hash across m registers and estimates with a harmonic mean. With ~12 KB of memory it gives ~0.8% error for billions of elements, and sketches can be merged. Subtraction, intersection and exact counts are its weak side.

📖 Answer

The intuition: you're flipping a coin. If someone says "I got heads 20 times in a row", you assume they flipped it about a million times. The hash bits are the coins.

The mechanism:

  • the first p bits of a 64-bit hash are the register index (p = 14 → 16,384 registers);
  • the position of the first 1 in the remaining bits is ρ;
  • register[idx] = max(register[idx], ρ);
  • the estimate is ≈ α·m² / Σ 2^(−register[j]), with corrections for the small and large ranges.

The standard error is ≈ 1.04 / √m. With m = 16,384 that's ~0.81%. Each register is 6 bits, so ~12 KB in total.

Its strengths:

  • Merging. Two sketches combine as the maximum per register. A weekly sketch from daily sketches, an overall count from sketches across services. An exact COUNT(DISTINCT) can't do this: you can't add up daily uniques to get weekly uniques.
  • memory is fixed: 1 thousand or 1 billion elements, still 12 KB.

Limitations you hit in practice:

  • Intersection and difference. "Users who came from both iOS and web": you can compute it by inclusion-exclusion, |A| + |B| − |A∪B|, but if the intersection is small, the error becomes larger than the result. If intersection matters, use a Theta sketch (Apache DataSketches).
  • You can't delete: if a user is deleted under GDPR, you can't remove them from the sketch.
  • For very small sets you need a special "sparse" mode; Redis does this automatically.
  • A bad hash (say the 32 bits of String.hashCode()) ruins the distribution. Use MurmurHash3 or 64-bit xxHash.

Where it exists: Redis (PFADD, PFCOUNT, PFMERGE), the PostgreSQL hll extension, ClickHouse uniqHLL12 and uniqCombined (plain uniq uses adaptive sampling), BigQuery APPROX_COUNT_DISTINCT, Spark approx_count_distinct.

Architecture: I store a sketch per hour (and per needed dimension), and at query time I merge the ones in the required range. Memory is 12 KB per hour times the number of dimension combinations; be careful when adding dimensions, because the combinations explode.