← Data structures

HyperLogLog

Hashing and probabilistic sketches

An array of small counters (registers) that each remember the longest run of leading zero bits seen in the hashes routed to them, from which the number of distinct items can be estimated to within about 1%. It exists because counting unique visitors exactly means storing every visitor id, and a HyperLogLog does it in 12 KB no matter how many visitors there are.

What it costs

OperationCostNote
Add itemO(1): 1 hash, 1 register read, 1 maxRoute by the first p bits of the hash; store max(register, leading zeros of the rest + 1).
Count estimateO(m): harmonic mean over m registersm = 2^p = 16,384 at p = 14; Redis caches the result until the next add.
Merge two HLLsO(m): element-wise maxExact union: merging daily sketches gives the monthly unique count with no extra error.
Remove item / intersectNot supportedIntersection can be approximated via inclusion-exclusion but the error compounds.

Memory: 2^p registers of 6 bits each: p = 14 gives 16,384 × 6 bits ≈ 12 KB for about 0.81% standard error, whether the true count is 1,000 or 1 billion. Redis stores small sets sparsely in a few hundred bytes.

Route by the first bits, record the longest zero run

The hash’s first 14 bits choose a register; the count of leading zeros in the rest, plus one, is stored if larger than what is there. The estimate is a harmonic mean over all 16,384 registers.

How it works

  1. Hash each item to a 64-bit value with a hash whose bits are uniformly random (MurmurHash64). Everything below works on the hash; the item itself is discarded.
  2. Use the first p bits (p = 14) as a register index, picking one of 2^p = 16,384 registers.
  3. In the remaining 50 bits, count the leading zeros and add 1. Call that ρ. If the hash bits are random, half of all items have ρ = 1, a quarter have ρ = 2, and so on; seeing ρ = 20 is a one-in-a-million event that suggests about a million distinct items passed through that register.
  4. Store max(register[index], ρ). The register only ever increases, and adding the same item twice computes the same hash and the same ρ, so duplicates change nothing. That is why it counts distinct items.
  5. To estimate, combine all registers with a harmonic mean (which damps the effect of one unlucky register with a huge ρ), multiply by m^2 and a correction constant α ≈ 0.72, and apply small-range and large-range corrections. The standard error is 1.04 / sqrt(m), so 16,384 registers give 0.81%.

Why 16,384 registers and not one

  • One register is a coin-flip estimate: a single lucky hash with 30 leading zeros would say "a billion items" after one insert. Averaging thousands of independent registers smooths the luck out; the error falls with the square root of their number.
  • Six bits per register is enough to hold ρ up to 63, which covers 2^64 items. The whole structure is a fixed 12 KB regardless of cardinality, which is the entire point.

Worked example

Unique visitors per short link

  • 345M clicks per day across 2M active aliases. The product wants unique visitors per alias per day and per month.
  • Exact: store (alias, day, visitor_hash) rows: 345M × 24 bytes ≈ 8 GB per day, 240 GB per month, and a monthly unique count per alias is a DISTINCT over 30 days of rows.
  • HyperLogLog: one 12 KB HLL per alias per day. A click on alias aB3xZ9 by visitor v8821: MurmurHash64("v8821") = 0x3A7F…; the first 14 bits give register 14,975; the remaining 50 bits start with 3 zeros so ρ = 4; register 14,975 becomes max(2, 4) = 4. One PFADD, about 1 µs.
  • Same visitor clicks again an hour later: same hash, same register, same ρ, register unchanged. Counted once.
  • 2M aliases × 12 KB = 24 GB per day if every HLL is dense, but most aliases have a handful of visitors and Redis keeps those sparse at a few hundred bytes. Real footprint is around 800 MB per day.
  • Monthly uniques: PFMERGE the 30 daily HLLs for the alias (element-wise max over 16,384 registers, microseconds) and PFCOUNT. A link with 1,000,000 true uniques reports somewhere between 992,000 and 1,008,000 at one standard error. Overall daily uniques across all aliases: PFMERGE every alias’s HLL into one.

When it is the wrong choice

  • The count must be exact: billing, compliance, anything a customer will dispute. Use an exact set or a database DISTINCT, and reserve the sketch for dashboards and ranking.
  • Cardinalities are tiny (under a few hundred): a plain set is smaller and exact. Redis handles this automatically with a sparse encoding, but on your own prefer the set.
  • You need the intersection of two sets (visitors who saw both A and B): HyperLogLog only unions well. Inclusion-exclusion on two sketches compounds the error badly for small intersections; use MinHash or exact sets.
  • You need to remove items or ask "is X in the set": registers hold maxima, not members. That is a Bloom filter’s job.

Interviewer follow-ups

Answer out loud before you open each one.

How does counting leading zeros tell you how many items there were?

If hash bits are random, the chance of a hash starting with k zeros is 1 in 2^k. Seeing a run of 20 zeros is a one-in-a-million event, so you have probably seen about a million distinct hashes. One register is a very noisy version of that guess; averaging 16,384 registers makes it accurate to about 1%.

Why does adding the same item twice not change the count?

The same item produces the same hash, which routes to the same register with the same zero-run length. The register stores a maximum, and max(x, x) is x. Duplicates are free, which is exactly the property a distinct count needs.

Why can you merge two HyperLogLogs without losing accuracy?

A register holds the longest run seen among items routed to it. The union of two streams routed to the same register has a longest run equal to the max of the two. Taking the element-wise max therefore yields exactly the sketch you would have built from the combined stream, with the same 0.81% error.

How do you count uniques per hour, per day and per month without three pipelines?

Keep one HyperLogLog per alias per hour. Daily is the merge of 24 hourly sketches, monthly the merge of 720, each merge a microsecond-scale element-wise max. One write path, any time window at read time.

Where it shows up

Building blocks
Count big things with small memory · Compute over events as they arrive · Process large data offline · Measure what users feel · Rank instead of sorting by time
Problems
URL Shortener (TinyURL / bit.ly) · Video Streaming Platform (YouTube / Netflix) · News Feed (Twitter / X timeline)