GOAT EngineerPreparing your learning space…

System Design · Concept Library · Free article

HyperLogLog: Counting Millions of Uniques in Kilobytes

HyperLogLog estimates how many distinct items a stream holds without storing any of them. It hashes each item, keeps the longest run of leading zeros in many small registers, and uses memory that stays flat however large the count grows, at the cost of a small error.

Counting how many unique things you’ve seen is far harder than counting how many things total — because to avoid double-counting, you have to remember who you’ve already seen. Do it exactly and you store every distinct id in a set: perfectly accurate, but the memory grows with the number of uniques, and at scale that’s gigabytes and an out-of-memory crash. HyperLogLog (HLL) throws the ids away entirely and keeps only a tiny statistical fingerprint: it hashes each id to random-looking bits and tracks the longest run of leading zeros it has seen — and because a long run is rare, a long run means you’ve probably hashed a lot of distinct ids. Split that estimate across many little registers and average them to tame the noise, and you can count uniques into the billions with a fixed ~12 KB and around 1% error — memory that doesn’t grow with the count. The trade is exactness for a flat, tiny footprint, and it’s the right trade for almost every "how many unique…" dashboard.

Marketing wants unique visitors — and the obvious way runs out of memory

Hatch’s dashboard can already show total clicks per link — the stream aggregation pipeline keeps a running count, and a viral link just ticks it up. Then Marketing asks the follow-up that sounds almost identical but isn’t: "not total clicks — unique visitors. How many different people clicked MegaDrop?" One person refreshing fifty times should count once, not fifty. Sensible ask. And the obvious implementation is right there: for each link, keep a set of the visitor ids you’ve seen; to count uniques, return the size of the set. A set automatically ignores duplicates — add the same id twice, it’s still in there once. Exact, simple, correct.

It works beautifully in testing and then falls over the first time a campaign goes big. During a flash sale, a single popular link draws millions of distinct visitors, and every one of their ids has to be stored in that set to know it’s already been counted. A visitor id is maybe fifty bytes once you include the structure’s overhead; ten million uniques is half a gigabyte — for one link. Multiply by every link in a campaign and the cache holding these sets balloons past twelve gigabytes, runs out of RAM, and the tracking nodes crash. The exact answer is correct and unaffordable. This page is about the trade that makes it affordable: give up a tiny bit of accuracy, and the memory problem simply disappears.

A total needs one number; a unique count needs a memory

Stop and notice why the two questions have such wildly different costs, because it’s the crux of everything that follows. Counting the total is trivially cheap: hold a single counter and add one for every event. It doesn’t matter if you see a billion events — the counter is one number, a few bytes, forever. You never have to look back at what came before; each event just bumps the tally and is forgotten.

Counting uniques is a fundamentally different beast, because the whole job is to not count the same thing twice — and to know whether you’ve seen an id before, you have to have remembered every id you’ve seen. That memory is the cost. Do it exactly and you’re forced to keep the full set of distinct ids around, which means your memory grows in lockstep with the number of uniques: a thousand uniques is cheap, a hundred million is gigabytes. There’s no way around it if you insist on an exact answer — exact distinct counting provably needs memory proportional to the cardinality. That "provably" is the wall HyperLogLog goes around by refusing to be exact.

The longest run of luck tells you how many times you played

What follows feels like a magic trick, and — like any good trick — it’s completely honest once you see how it’s done. The claim is outrageous: I’m going to estimate how many different people clicked a link, to within a percent or two, without keeping a single visitor id. No set, no list, nothing. Just the memory of the most striking coincidence I happened to notice. Let’s build it up one small step at a time, because the idea is genuinely simple — it just needs to be earned, not swallowed.

Forget ids for a minute and play a tiny game with me, with a coin. Flip it over and over, and count how many heads you get in a row before the first tails. Most of the time it’s a dull little number — zero, one, maybe two. A streak of five heads before a tails is already a bit lucky: roughly a 1-in-32 run. Ten heads in a row before a tails? That’s about 1-in-1,000 — you’d be honestly surprised to see it. Your gut already knows the rule: the longer the streak, the rarer it is, and every extra head cuts the odds in half.

Now flip the question around — this is the whole trick. Suppose you didn’t watch me play, and at the end of the day I simply tell you: "the longest streak I hit was ten heads in a row." You can work backwards. A ten-head streak is a 1-in-1,000 event, so for one to have actually turned up, I must have made about a thousand attempts. I never told you how many times I flipped — you deduced it, from the single rarest thing that happened. That’s the key sentence to hold onto: the most extreme coincidence you witness is a receipt for how many times you tried.

And look at the shape of that reasoning, because it’s the only "maths" in the whole idea, and it’s just doubling. A best streak of 1 → you probably flipped about 2 times. A best streak of 4 → each step doubles the rarity (2, 4, 8, 16), so about 16 times. A best streak of 10 → about 1,000. A best streak of 20 → about 1,000,000. The recipe never changes: take the longest streak, and the number of tries is 2 doubled that many times — two, times two, times two, and so on. A tiny number (the streak) tells you a huge number (the count). That’s the engine; everything else is just feeding it.

"Fine," you say, "but a visitor isn’t a coin — how do I flip a coin for someone’s id?" That’s exactly the job of a hash function. A hash takes anything at all — visitor-8f3a, an email, a phone id — and blends it into a fixed string of bits that looks utterly random, like 00010110…. Two properties are all we need. The same id always hashes to the same bits (so a repeat visitor makes the identical string every time), and two different ids produce completely unrelated, random-looking strings. So every bit of a hash behaves like its own fair coin flip — which means the run of leading zeros at the front of a hashed id is our "heads before the first tails" streak, generated automatically, a free coin-game for every visitor.

Put the two halves together and you have HyperLogLog in its simplest form. Hash every visitor id. For each one, glance at its leading-zero run — its rare-streak score — and then throw the id (and the hash) away. Keep exactly one number: the biggest leading-zero run you have ever seen. When Marketing asks "how many unique visitors?", you answer with the doubling recipe — 2, doubled that-many times. A longest run of 10 zeros somewhere in the stream? About a thousand distinct visitors. You just reconstructed a count of a thousand from a single two-digit number, having stored not one id. Add visitors below and watch the longest run climb — and the estimate climb with it:

The interactive version of this example is available when JavaScript loads.

The memory stays flat no matter how big the count gets

Look at what HyperLogLog actually stores and the win jumps out: not the ids, not the hashes, just a handful of small numbers — the longest-run records (we’ll see in the next section why it keeps many of them). That’s a fixed amount of space. Whether a link had a thousand unique visitors or a billion, the sketch is the same size — a flat ~12 KB in a standard configuration. Contrast that with the exact set, whose memory marches upward with every new unique until it eats all your RAM. Drag the number of uniques and watch the exact set climb toward an out-of-memory crash while the HLL sits, unbothered, at a few kilobytes:

The interactive version of this example is available when JavaScript loads.

Many little estimators, averaged, tame the wobble

You saw the weakness in the interactive: a single longest-run estimator is jumpy. It can only ever guess powers of two, and one unlucky early hash — a visitor who happens to start with a long zero-run — can throw the whole estimate off by 2× or 4×. One coincidence is a shaky thing to bet on. The fix is the oldest trick in statistics: don’t take one measurement, take many and average them. HyperLogLog doesn’t keep one longest-run record — it keeps hundreds or thousands of them, running in parallel.

So how do you get many estimators out of a single stream of clicks? Here is the move, and it’s worth slowing down for. Picture that one noisy estimator as a single person, flipping coins all afternoon and reporting only their longest streak of heads. Now imagine instead you split the afternoon’s flips among a thousand people, each doing a small share and each reporting their own longest streak. Any one of them might get freakishly lucky — a long streak, so an overestimate — or unusually dull — a short one, an underestimate. But a thousand rough guesses, averaged together, land somewhere tight and reliable, because the flukes cancel each other out. That’s the entire idea. All HyperLogLog needs is a fair way to split the ids among its "people."

That splitting is exactly what the first few bits of the hash are for. Before HLL even looks at the leading-zero run, it reads (say) the first 14 bits of a hash and treats them as a room number — an address from 0 to 16,383 that says which bucket this id belongs to. HLL calls these buckets registers. Because the bits are random-looking, ids scatter evenly across all 16,384 rooms; and because the same id always hashes the same way, a repeat visitor always walks into the same room. Each register then does precisely what our single estimator did, but only over the slice of ids dealt to it: it watches the remaining bits of those hashes and quietly remembers the longest leading-zero run it has seen. One noisy estimator has quietly become sixteen thousand independent ones, sitting side by side.

The last step is to fold those 16,384 little records back into a single count — and here HLL is careful in a way worth understanding. You might reach for a plain, everyday average, but it would betray you: each register’s record stands for an estimate of 2 raised to that run, a lopsided, exponential quantity, so a single register that happened to catch a monster run would report a gigantic number that stampedes over all the others and wrecks the average. So HyperLogLog reaches for the harmonic mean instead — a flavour of average that leans toward the smaller values and flatly refuses to let one lucky outlier dominate — and then nudges the result with a small correction factor the inventors worked out to cancel a slight built-in bias. Run the registers through that, and the wobble of any single one washes out into a steady, trustworthy number.

And through all of it the memory stays flat, because that’s the point. Each register is a tiny number — just the longest run it has seen, which fits in about 6 bits. Sixteen thousand of them is ~12 KB, and that ~12 KB is the whole sketch whether the link drew twelve unique visitors or twelve billion. Drag the precision and watch accuracy and memory move together — while the cardinality it can count stays irrelevant to the size:

The interactive version of this example is available when JavaScript loads.

Two sketches merge into one — and that changes everything

Here is the property that makes HyperLogLog beloved in large systems, not merely tolerated. Two sketches can be merged into a single sketch of the combined set — the union — exactly, with no extra loss beyond the usual error. And the merge is almost insultingly simple: since every register holds a longest run, the merged register is just the larger of the two originals. Take the max of each register pair, and you have a sketch of everything both of them saw. That’s it.

Two enormous payoffs fall out. First, distributed counting. Ten servers each handle a slice of Hatch’s traffic; each keeps its own little sketch of the visitors it saw. To get the global unique count, you don’t ship millions of raw ids to one place — you ship the ten tiny 12 KB sketches and merge them. Second, rolling up over time. Keep an hourly sketch per link; want today’s uniques, or this week’s? Merge the hourly sketches into one and count that. The flat little sketch is not just cheap to store — it’s cheap to combine.

See exactly how wrong the sum goes as two shards overlap — and how the merge stays right:

The interactive version of this example is available when JavaScript loads.

When approximate isn’t good enough

HyperLogLog trades ~1% accuracy for flat memory — a brilliant bargain for a dashboard, and the wrong one in a handful of cases. Keep counting exactly (with a set) when:

  • Money or compliance rides on the number. You can’t bill a customer for "approximately 1,000,000 API calls," and an auditor won’t accept "within a percent." Exact counts where exactness is the point.
  • The cardinality is small. A few thousand uniques fit in a plain set that’s cheap, exact, and simple — and HyperLogLog’s relative error is actually worst at tiny counts. Don’t reach for a sketch to count something a Set handles trivially. (Good HLL implementations even fall back to exact counting for small N automatically.)
  • You need the members, not just the count. HyperLogLog can tell you how many distinct visitors, but never which ones — it threw the ids away. If you need to list them, ban them, or re-target them, keep a set or an index; the sketch is a counter, not a directory.

Where you’ll actually meet it

  • Redis — PFADD / PFCOUNT / PFMERGE, a ~12 KB sketch per key (the PF honours Philippe Flajolet, HyperLogLog’s co-inventor). The everyday way teams keep unique counts per link, per page, per user.
  • Data warehouses — APPROX_COUNT_DISTINCT in BigQuery, Snowflake, Redshift, and Presto/Trino is HyperLogLog under the hood — orders of magnitude faster and cheaper than an exact COUNT(DISTINCT) over billions of rows.
  • Stream processors — Flink and Spark ship HLL aggregators for windowed unique counts, which is precisely how you’d put "unique visitors per minute" onto the stream-aggregation dashboard.
  • The origin — HyperLogLog comes from Flajolet, Fusy, Gandouet and Meunier (2007), refining the earlier Flajolet–Martin and LogLog algorithms. The leading-zeros trick has been counting the uncountable for decades.

Counting Hatch’s uniques, for real

In Redis it’s three commands; in a warehouse it’s one function. The entire unique-visitor feature, end to end:

  • Add a click’s visitor to the link’s sketch. PFADD hll:uniques:mega-drop v-91c3 — idempotent, so the same visitor added again changes nothing (duplicates are free, exactly as §3 promised).
  • Read the estimate. PFCOUNT hll:uniques:mega-drop — returns the approximate unique count from a 12 KB key, in microseconds.
  • Roll a day up from hourly sketches — MERGE, never add. PFMERGE hll:day:mega-drop hll:h09 hll:h10 hll:h11, then PFCOUNT hll:day:mega-drop — the union, correctly deduped across the hours.
  • Or, in the warehouse, one line. SELECT link_id, APPROX_COUNT_DISTINCT(visitor_id) FROM clicks GROUP BY link_id — HyperLogLog doing the work, no set in sight.

Pitfalls

  • Adding unique counts instead of merging sketches. The cardinal sin — sums double-count anyone in the overlap. Merge the sketches (union), then count.
  • Using HyperLogLog when you need an exact number. Billing, audits, tiny cardinalities — reach for a set.
  • Expecting to list the members. HLL counts; it can’t tell you who. Keep a set or index if you need the identities.
  • Merging sketches built with different precision or a different hash. They must match to combine correctly.
  • Treating the estimate as exact in downstream math. It’s ~1% off; don’t build precise calculations on top of it.
  • Forgetting the small-N regime. At low cardinalities plain counting is better; good libraries switch to it automatically, but know the estimate is coarsest when the count is small.

Best practices

  • HyperLogLog for large-scale approximate counts; a set for small or exact ones — match the tool to whether precision and size matter.
  • Keep a sketch per entity and per time bucket, then MERGE for roll-ups — never add counts across buckets or shards.
  • Use the same hash and precision everywhere you’ll merge — mismatched sketches don’t combine correctly.
  • Pick precision for your accuracy need; ~12 KB / ~0.8% is a fine default — tune only for unusually tight accuracy or extreme memory limits.
  • Reach for the built-in — Redis PF*, warehouse APPROX_COUNT_DISTINCT, or your stream engine’s HLL aggregator — rather than hand-rolling the algorithm.
  • Keep a separate set of members only if you genuinely need the identities — the sketch alone can never list them.

Rapid-fire cheat-sheet (intern → principal)

"How would you count unique visitors at scale?"
HyperLogLog: hash each id, track the longest leading-zero runs across many registers, and estimate the count from them — about 1% error at a fixed ~12 KB, versus an exact set whose memory grows without bound and eventually OOMs.
"Why is counting uniques harder than counting totals?"
A total is stateless per event — one counter, add one, forget it. A unique count must remember who you’ve already seen to avoid double-counting, so exact counting provably needs memory proportional to the number of distinct items.
"Give me the intuition for HyperLogLog."
Hashing turns each id into random-looking bits, like coin flips. A long run of leading zeros is rare, so the longest run you’ve ever seen estimates how many distinct ids you hashed (about 2 to that power). Duplicates hash to the same bits, so they can’t inflate it — which is why it counts uniques, not events.
"Accuracy vs memory?" (senior)
It keeps m registers and averages them; error ≈ 1.04/√m, so quadrupling registers halves the error. Memory ≈ m × 6 bits and is flat in the cardinality. Redis uses 16,384 registers → ~12 KB → ~0.81%.
"How do you get a global count across shards, or a weekly count from daily ones?" (the gotcha)
Merge the sketches — take the max of each register, which gives the union — then count. You must NOT add the individual counts: anyone appearing in more than one shard or day would be counted multiple times. Sum of uniques ≠ uniques of the union.
"When would you NOT use it?"
When you need an exact number (billing, audit), when the cardinality is small (a set is cheap and exact), or when you need the actual members — HyperLogLog only ever gives a count, never the identities.

The takeaway

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.