Part 2 of 12 · Data Structures
How do you count unique visitors without storing them?
An exact set of 10 million visitor IDs took 289 MiB. A HyperLogLog sketch of 16 KiB counted them within about 1%, and seven daily sketches merged into a weekly count without the raw data. How it works, measured at four precisions, and where Redis and PostgreSQL already have it.
The verdict, which the measurements below will earn: use HyperLogLog when “about 1% off” is fine: daily active users, unique searches, distinct IPs, per-tenant usage. A 16 KiB sketch counted 10 million distinct items with a typical error under 1%, while an exact set of the same IDs took 289 MiB. Sketches merge: seven daily sketches combine into a weekly count with the same accuracy, which is what makes them useful for analytics. Keep exact counts for anything billed or audited.
The case starts innocently: a dashboard wants “unique visitors”, so somebody keeps a set of every ID. Then the set reaches hundreds of megabytes, and someone asks for weekly uniques, and adding the daily numbers gives a total that’s plainly too big. The obvious suspects are “buy more memory” or “store the raw events forever”. The real answer is more beautiful than either.
HyperLogLog is one of my favourite algorithms. It counts millions of things by remembering almost nothing, using a fact about coin flips you could explain to a child. Let’s see how.
The code is in systems-data-structures (Go, standard library only).
Case file
The case A set of visitor IDs reaches hundreds of megabytes, and weekly uniques come out too big Suspects “Buy more memory”, “store the raw events forever” Culprit Keeping every ID, and adding daily unique counts The fix A HyperLogLog sketch per day, merged on read Evidence 10 million IDs: 289 MiB exact vs 16 KiB sketch, within about 1%
The key insight #
Hash each item to 64 random-looking bits. Look at the number of leading zeros: half of all hashes start with 1, a quarter with 01, an eighth with 001. If the longest run of leading zeros you’ve seen is 20, you’ve probably seen around 2²⁰ distinct items, because a run that long is rare. That’s the whole insight: you’re estimating a crowd by the luckiest streak anyone in it managed.
One such guess is noisy, so HyperLogLog (Flajolet et al., 2007) splits the stream. Philippe Flajolet and his colleagues spent years refining this family of ideas, and it shows:
- The first p bits of the hash pick one of 2ᵖ registers (one byte each).
- Each register keeps the longest run seen among the items routed to it.
- The estimate combines all registers with a harmonic mean, plus a correction for small counts.
Duplicates hash identically, so they never change anything. Merging two sketches is taking the larger value of each register: no reconciliation, only a max. Keep that detail in mind; it’s the clue that cracks the weekly-count mystery later.
Diagram source
flowchart LR
I["Item"] --> H["Hash to 64 bits"]
H --> P["First p bits pick a register"]
H --> Z["Count leading zeros of the rest"]
P --> R["Register keeps the longest run"]
Z --> R
R --> E["Harmonic mean of all registers = estimate"]
R --> M["Merge sketches: max per register"]
Clue 1: memory #
First, the evidence against the exact set:
| Distinct items | Exact set (Go map of 64-bit IDs) | HyperLogLog, p = 14 |
|---|---|---|
| 100,000 | 2.3 MiB | 16 KiB |
| 1,000,000 | 36.0 MiB | 16 KiB |
| 10,000,000 | 288.6 MiB | 16 KiB |
The sketch never grows. The set balloons; the sketch sits at 16 KiB and doesn’t move.
Diagram source
xychart-beta
title "Exact set memory in MiB (the sketch stays at 16 KiB)"
x-axis ["100,000", "1,000,000", "10,000,000"]
y-axis "MiB"
bar [2.3 , 36.0 , 288.6]
Clue 2: error, over 20 independent streams each #
| Precision | Memory | Expected σ (1.04/√2ᵖ) | n = 1,000: mean / worst | n = 100,000 | n = 10,000,000 |
|---|---|---|---|---|---|
| 10 | 1 KiB | 3.25% | 1.95% / 6.80% | 2.75% / 6.85% | 2.11% / 6.80% |
| 12 | 4 KiB | 1.62% | 0.95% / 3.00% | 1.12% / 2.72% | 1.24% / 2.99% |
| 14 | 16 KiB | 0.81% | 0.33% / 1.30% | 0.54% / 1.35% | 0.88% / 1.84% |
| 16 | 64 KiB | 0.41% | 0.20% / 0.40% | 0.32% / 0.71% | 0.31% / 0.85% |
Two things this evidence tells us:
- Error depends on memory, not on how many items you count. Precision 14 behaved the same at a thousand and at ten million.
- Plan for the worst case, not the mean. Roughly 1 run in 20 is off by 2σ or more; with precision 14 the worst of my 60 runs was 1.84%.
The reveal: a week from seven days #
200,000 visitors a day for seven days, half of each day’s visitors returning from earlier days, so 800,000 unique visitors in the week. Seven daily sketches (16 KiB each) merged into one:
| Exact weekly uniques | Merged estimate | Error |
|---|---|---|
| 800,000 | 810,545 | 1.32% |
Here’s where the case closes. You can’t add daily unique counts (returning visitors would be counted twice; that was the false lead), and you can’t rebuild a weekly count without keeping every ID, unless you keep sketches. Merge any range of days, any set of pages, any group of tenants. That a simple max per register makes this possible is, to me, the most elegant part of the whole design.
Where it earns its keep #
| Question | How |
|---|---|
| Daily and monthly active users | A sketch per day; merge 30 for the month |
| Unique visitors per page or per short link | A sketch per page per day (URL shortener post) |
| Distinct IPs hitting an endpoint | A sketch per minute to spot scanning or abuse |
| Per-tenant usage in a SaaS | A sketch per tenant per day for “active users” on dashboards (not for billing) |
You may already own one #
- Redis:
PFADD,PFCOUNT,PFMERGE(12 KiB per key, about 0.81% standard error). - PostgreSQL: the
hllextension (maintained by Citus); many analytics databases (BigQuery’sAPPROX_COUNT_DISTINCT, Druid, Snowflake, and ClickHouse’suniqHLL12) use HyperLogLog or a close relative internally; ClickHouse’s defaultuniquses a different, adaptive-sampling sketch. - Privacy: a sketch doesn’t store IDs, but registers do carry some information. Treat sketches of sensitive identifiers as personal data unless you’ve thought it through.
Remember this
- Error depends on memory, not on how many items you count.
- Sketches merge with a max per register: daily sketches make a weekly count.
- Keep exact counts for anything billed or audited.
Case closed: what I’d do by default #
- Exact counts when the set fits comfortably or the number is billed or audited.
- HyperLogLog at precision 14 (or Redis’s built-in) for analytics.
- One sketch per smallest time bucket you’ll query, merged on read.
- State the error on dashboards ("±2%"), so nobody chases a 1% wobble.
Trading a sliver of accuracy for a fixed 16 KiB, with merging thrown in, is about as good a bargain as computing offers. For the neighbouring question, “have we seen this one before?”, see the Bloom filter post.
Measured Nov 2026 with Go 1.27 on a laptop (Intel i7-8550U). Errors come from seeded streams and repeat exactly. Code and full results: systems-data-structures.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.