Cardinality and Frequency Sketches - Complete Deep Dive
Prerequisites: Bloom Filters, Back of the Envelope Used in: Trending Topics, Metrics Monitoring, Ad System
What is a Sketch?
A sketch is a fixed-size summary of a data stream that answers a question approximately, with a stated error bound, in memory that never grows with the input. Feed it a thousand items or a trillion and the sketch occupies the same few kilobytes. You give up exactness; in return you get a counter you can keep in RAM, ship over the network, and combine with other counters.
Real-world analogy: You are standing at a stadium gate trying to answer two questions about the crowd. “How many different people came today” and “which three fans showed up most often.” The exact way is to write down every name on a list and count it afterwards — accurate, but by the end you are carrying a filing cabinet. The sketch way is to keep a small scorecard with a fixed number of boxes that you mark as people walk by. At the end the scorecard tells you “about 84,000 distinct people, give or take two percent.” It fits in your pocket, it took the same space whether 800 or 800,000 came through, and two colleagues at other gates can combine their scorecards with yours without anyone being counted twice.
Counting Distinct Things Exactly Is Expensive
Start with why anyone would accept an approximate answer at all. To count distinct items exactly, you must remember every item you have seen — to know whether the next user ID is new, you have to check it against all previous IDs. That means a set, and a set grows linearly with cardinality.
💡 Cardinality = the number of distinct values in a collection. A stream of a billion page views from five million people has a cardinality of five million.
Counting 100 million distinct user IDs exactly
8-byte integer IDs, in a hash set with typical overhead
= 100,000,000 x roughly 24 bytes
= ~2.4 GB of RAM, for ONE counter
The same count with a HyperLogLog
= 12 KB, with about 1 percent typical error
Now multiply by reality. You do not want one counter — you want distinct users per hour, per country, per device type, per campaign, which is tens of thousands of counters, all live. At 2.4 GB each that is a data centre. At 12 KB each it is a few hundred megabytes and fits on one machine. The same argument applies to frequencies. Counting how many times each key appeared needs a hash map from key to count, and the keys are the expensive part. For a stream of URLs or search terms the key set is unbounded and adversarial — someone can always send you new ones — so an exact map is a memory leak with a scheduler.
Sketches trade a known, bounded error for constant memory. The engineering question is never “is it exact” — it is “is the error smaller than the decision I am making with this number.” For “is this hashtag trending,” two percent is irrelevant. For “how much do we invoice this customer,” any error is unacceptable.
HyperLogLog - Counting Distinct Items
HyperLogLog, usually written HLL, estimates cardinality. The core idea is one of the prettier tricks in computing, and you can explain it without a single formula.
Hash every incoming item into a uniformly random-looking bit string. Because the bits are random, the pattern of a hash tells you something about how many hashes you must have drawn:
- About half of all random hashes start with a
0. - About a quarter start with
00. - About an eighth start with
000. - About one in 2^k starts with k zeros.
So run the logic backwards. If the longest run of leading zeros you have ever seen is k, you have probably drawn about 2^k distinct hashes. Seen a hash starting with ten zeros? A one-in-a-thousand event, so you have probably processed roughly a thousand distinct items. That is the whole intuition, and notice what it costs to store: a single small number, the longest run so far. Hashing is also what makes this a distinct count rather than a total count — the same user ID always hashes to the same bits, so seeing it a million times changes nothing.
Registers, because one number is far too noisy
One leading-zero count is a terrible estimator. Get unlucky once — a single early hash with twenty leading zeros — and your estimate is off by a factor of a thousand forever. The fix is to run many independent copies and average them. Use the first few bits of each hash to choose a register — one of m small counters — and use the remaining bits for the leading-zero count in that register only. Each register sees roughly 1/m of the stream and keeps its own maximum. Averaging across registers cancels the noise, and error shrinks with the square root of the register count: four times as many registers halves the error.
💡 HyperLogLog averages its registers using a harmonic mean rather than a plain average, because the harmonic mean is far less distorted by one freakishly large register. That detail plus a small correction factor is the entire difference between the 1980s LogLog and the 2007 HyperLogLog.
The numbers you should remember
| Registers | Memory | Typical error | Error at 95 percent confidence |
|---|---|---|---|
| 1,024 | ~0.75 KB | ~3.2% | ~6.5% |
| 4,096 | ~3 KB | ~1.6% | ~3.2% |
| 16,384 | ~12 KB | ~0.8% | ~1.6% |
| 65,536 | ~48 KB | ~0.4% | ~0.8% |
The 16,384-register row is the one worth memorising, because it is what Redis uses: 12 KB, standard error around 0.8 percent, so real-world answers land within roughly 1.5 to 2 percent almost all of the time. Twelve kilobytes to count any cardinality from zero to well past a billion. Say that number in an interview and the rest of the design follows.
Why HyperLogLogs Merge and Why That Matters
This is the property that makes HLL an architectural tool rather than a memory optimisation. Each register holds a maximum, so to union two sketches you take the register-wise maximum of the two — register 0 becomes the larger of the two register 0s, and so on. The result is bit-for-bit identical to the sketch you would have built by feeding both streams into one sketch from the start.
flowchart LR
S1["Shard 1 sketch<br/>12 KB"] --> U["Register wise maximum"]
S2["Shard 2 sketch<br/>12 KB"] --> U
S3["Shard 3 sketch<br/>12 KB"] --> U
U --> R["One 12 KB sketch<br/>for the union<br/>no double counting"]
Three consequences, and all three show up in real architectures:
- Shards become independent. Each of 200 shards counts its own distinct users with no coordination. At read time you merge 200 sketches. A user who appeared on three shards is counted once, because the same ID hashes to the same register everywhere. Try that with exact counts and you need the raw ID sets.
- Time buckets compose. Store one sketch per minute. Distinct users for an hour is the merge of 60 sketches; for a day, the merge of 1,440. You never recompute from raw events, and the same stored minutes answer every window anyone asks for later.
- Dimensions compose. Store a sketch per country. Distinct users in the EU is the merge of those countries’ sketches. Exact counting cannot do this — you cannot add per-country distinct counts, because travellers get counted twice.
The limits, stated plainly: merging is union only. There is no exact intersection and no subtraction. You can estimate an intersection through the inclusion-exclusion identity — count A, count B, count their union, then infer the overlap — but the errors of three estimates compound, and when the intersection is small relative to the sets it can swamp the answer entirely. If you need “users in A but not B” accurately, a sketch is the wrong tool.
Count-Min Sketch - Counting Frequencies
HLL answers “how many different.” Count-Min Sketch, usually CMS, answers a different question: “roughly how many times did this specific key appear.”
The structure is a two-dimensional array of plain integer counters — d rows, w columns — plus d independent hash functions, one per row.
To add a key: hash it with all d functions. Each hash picks one column in its own row. Increment all d of those counters. To query a key: hash it the same d ways, read those d counters, and return the smallest one.
flowchart LR
K["Key trending-hashtag"] --> H1["hash for row 1"]
K --> H2["hash for row 2"]
K --> H3["hash for row 3"]
H1 --> R1["Row 1 counter<br/>reads 9"]
H2 --> R2["Row 2 counter<br/>reads 14"]
H3 --> R3["Row 3 counter<br/>reads 9"]
R1 --> MIN["Return the minimum<br/>which is 9"]
R2 --> MIN
R3 --> MIN
Notice what is absent: the keys themselves are never stored. The sketch holds d times w integers and nothing else, so memory is fixed by the array dimensions, completely independent of how many distinct keys the stream contains. That is what defeats an unbounded key space.
Why Taking the Minimum Works
Different keys collide — two keys can hash to the same column in a row, and then they share a counter. A shared counter reads higher than either key’s true count, never lower, because collisions only ever add increments.
That gives Count-Min a one-sided error:
| Guarantee | Holds? | Why |
|---|---|---|
| Never undercounts | Always | Every add incremented every one of this key’s d counters |
| May overcount | Sometimes | Another key may have incremented a shared counter |
So each of the d counters is an upper bound on the truth, inflated by whatever collided with it. The smallest of them is the tightest upper bound — the row where this key got luckiest. And because the d hash functions are independent, a key must be unlucky in all d rows at once to be badly wrong, which is exponentially unlikely in d. This is why taking the minimum cancels collisions: each extra row is another independent chance to measure the key cleanly, and the minimum automatically picks the cleanest. Taking an average would mix the clean measurement back in with the polluted ones and throw the guarantee away.
Sizing a Count-Min Sketch
Width controls how wrong a key can be. Depth controls how often you exceed that bound. The overcount is bounded relative to the total number of adds in the stream, not relative to the key’s own count — which is why CMS is excellent for frequent keys and poor for rare ones.
| Width x depth | Counters | Memory at 4 bytes | Overcount stays within |
|---|---|---|---|
| 1,024 x 4 | 4,096 | 16 KB | ~0.27% of total stream count |
| 2,048 x 5 | 10,240 | 40 KB | ~0.13% of total stream count |
| 8,192 x 5 | 40,960 | 160 KB | ~0.03% of total stream count |
| 65,536 x 5 | 327,680 | 1.3 MB | ~0.004% of total stream count |
Read the second row concretely. In a stream of 100 million events, a 40 KB sketch answers any key’s frequency with overcounting bounded to about 130,000. For a hashtag used 4 million times that is noise. For a hashtag used twice the answer is useless — it might report 130,000. Count-Min tells you about the heavy keys and nothing trustworthy about the tail. Two useful variants: Count-Min with conservative update increments only the counters that are currently at the minimum, which measurably tightens the error for free. Count-Sketch adds random signs so the error is two-sided but unbiased, which is better when you intend to do arithmetic on the estimates.
Heavy Hitters and Top-K
Neither sketch can list anything. HLL cannot name a single user it counted; CMS cannot tell you which keys are large, only how large a key you name is. To get “the top 10 trending terms” you must pair the sketch with something that remembers candidates.
Sketch plus a small heap. Keep a min-heap of exactly k entries, each a key and its estimated count. On every add: update the sketch, query the new estimate, and if that estimate beats the smallest entry in the heap, insert this key and evict the smallest.
def add(key):
cms.increment(key)
est = cms.estimate(key)
if key in heap:
heap.update(key, est)
elif len(heap) < k or est > heap.minimum():
heap.push(key, est) # evicts the smallest if now over k
Memory is the sketch plus k keys — a top-100 over an unbounded term space costs kilobytes. The weakness is that a key must at some point estimate into the top k to be admitted at all, so a key that builds up slowly while the heap is full of early spikes can be missed.
Space-Saving is the alternative. Keep a fixed table of exactly m counters, each holding a key, a count, and a recorded error. On seeing a key:
- Already in the table — increment its count.
- Not in the table and the table is full — evict the key with the smallest count, put the new key in its slot, and set its count to that evicted count plus one, recording the evicted count as the new entry’s possible overestimate.
That eviction rule looks like cheating and is the clever part. A genuinely frequent key arriving late inherits the floor count, so it is not punished for showing up after the table filled, and it then climbs on its own increments. Space-Saving guarantees it finds every key whose true frequency exceeds a threshold set by the table size, and each entry carries its own error bar. For strict top-k it is generally the better choice; CMS wins when you also need frequency answers for arbitrary keys you never tracked.
Sketches Versus Bloom Filters
These are constantly confused because all three are small, hash-based, and approximate. They answer three different questions.
| Structure | Question it answers | Error shape |
|---|---|---|
| Bloom filter | Have I seen this exact item before? | May say yes wrongly, never says no wrongly |
| HyperLogLog | How many different items have I seen? | Count off by a small percentage, either direction |
| Count-Min Sketch | How many times did I see this item? | Count may be too high, never too low |
A Bloom filter is about membership, not counting. It cannot usefully tell you its own cardinality — you can roughly infer one from the fraction of bits set, but it degrades badly once the filter saturates and it is not what the structure is for. Run the comparison the other way and a HyperLogLog cannot answer membership: it can tell you about 4.2 million people visited and cannot tell you whether you were one of them, because the register your hash would have touched already holds a maximum that someone else’s hash could have set.
They compose well. A common pipeline puts a Bloom filter in front to drop keys that have never been seen, a Count-Min Sketch to rank the ones that survive, and a HyperLogLog to report the distinct total — three structures, three questions, a few hundred kilobytes total.
When NOT to Use a Sketch
The error bound is the whole contract. If anyone downstream needs the number to be defensible, a sketch is the wrong answer regardless of how tempting the memory saving is.
❌ Do not use a sketch when:
- It is money. Billing, invoicing, ad spend, payouts, revenue reporting. “About 2 percent off” is a dispute with a customer, and “approximately” does not survive a finance review.
- You must audit or reconcile it. If the number has to be re-derivable from raw events, or tied back to another system during Reconciliation, you need the raw events. A sketch is lossy by construction — you cannot ask it which items produced the count.
- The cardinality is small. A set of 10,000 IDs is a few hundred kilobytes, exact, and supports membership, iteration, and deletion. Below roughly a few tens of thousands of distinct values an exact set is both cheaper and strictly better. Sketches win at millions, not thousands.
- You need the items back. No sketch stores its inputs. If the next question is “which users,” you need a store.
- You need the rare tail. Count-Min’s error is measured against the total stream, so infrequent keys are indistinguishable from collision noise.
- You need exact set operations. Intersections and differences across sketches are estimates built on estimates.
✅ Do use a sketch when the number drives a ranking, a dashboard, an alert threshold, or a capacity decision; when you need thousands of counters live at once sliced by time and dimension; when the key space is unbounded or attacker-controlled; or when the answer must be composable across shards, regions, or time buckets.
The pattern that satisfies both sides: sketch the fast path, batch the exact path. Serve the real-time dashboard from sketches; recompute the exact figure nightly from the event log for anything that must be reconciled or invoiced. That is the same split described in Batch vs Stream, and the reconciliation job doubles as a check on your sketch’s error.
Real Support in Real Systems
You almost never implement these — they ship inside things you already run. Redis has HyperLogLog as a first-class type, which is why most people meet it here:
PFADD visitors:2026-10-28 user:1001 user:1002 user:1001
PFCOUNT visitors:2026-10-28
PFMERGE visitors:week visitors:2026-10-22 visitors:2026-10-23
PFCOUNT visitors:week
PFADD is O(1) and idempotent for a repeated member. PFCOUNT reads the estimate. PFMERGE is the register-wise maximum, and it is the command that turns per-minute keys into any time window on demand. Count-Min and Top-K live in the RedisBloom module as CMS.INCRBY, CMS.QUERY, and TOPK.ADD.
Analytical SQL engines expose the same primitives, including the intermediate sketch so you can store and merge it yourself:
-- Presto and Trino
SELECT approx_distinct(user_id) FROM page_views;
-- BigQuery, storing a per-day sketch so later queries can merge it
SELECT day, HLL_COUNT.INIT(user_id) AS sketch FROM page_views GROUP BY day;
SELECT HLL_COUNT.MERGE(sketch) FROM daily_sketches;
Spark has approx_count_distinct, and the whole family — including quantile and frequency sketches — is standardised in Apache DataSketches, which several engines use underneath. Stream processors keep sketches as operator state. A Flink or Kafka Streams job maintains one sketch per key per window, and because sketches merge, the windowing machinery can roll minutes into hours without touching raw events. Combined with Columnar Analytics for the historical side, this is how a system answers “distinct users for any slice of any time range” in milliseconds without storing a user ID set per slice.
Common Interview Questions
Q1: Explain the HyperLogLog intuition without any maths.
Hash every item so the bits look random. In random bit strings, a run of k leading zeros happens about once in 2^k draws. So if the longest run you have ever seen is ten zeros, you have probably drawn about a thousand distinct hashes — you can read the count backwards off the rarest pattern you observed. Storing that takes one small number. Because a single observation is wildly noisy, split the stream across thousands of registers using the first bits of the hash, track the maximum run per register, and average them. With 16,384 registers that is 12 KB and lands within about 1 to 2 percent of the truth at any cardinality.
Q2: Why does the merge property matter so much architecturally?
Because it makes distinct counts composable, which exact distinct counts are not. Unioning two HLLs is the register-wise maximum, and the result is identical to one sketch built from both streams, so a user seen on three shards is counted once. That buys you three things at once: shards count independently with zero coordination, per-minute sketches roll up into any time window, and per-dimension sketches roll up into any grouping. Without it, every new time range or grouping means a fresh pass over raw events. The limit is that merging is union only — intersection and subtraction are estimates on estimates.
Q3: Why does Count-Min take the minimum of its counters rather than the average?
Collisions only ever add increments, so every counter for a key reads at least the key’s true count and possibly more. Each counter is therefore an upper bound, and the minimum is the tightest one — the row where this key collided least. Averaging would fold the polluted rows back in and destroy the guarantee. The error is one-sided by construction: Count-Min can overcount, never undercount. And since the hash functions are independent, a key has to be unlucky in every row simultaneously to be badly wrong, which gets exponentially unlikely as you add rows.
Q4: What is the difference between a Bloom filter and a HyperLogLog?
They answer different questions. A Bloom filter does membership — “have I seen this specific item” — with no false negatives and occasional false positives. A HyperLogLog does cardinality — “how many different items” — with a small percentage error in either direction. An HLL cannot tell you whether a particular user was counted, because its registers hold maxima that any item could have set. A Bloom filter cannot tell you its own cardinality usefully, especially once it saturates. They are complementary, and real pipelines often run both plus a Count-Min: the filter drops unseen keys, the sketch ranks the survivors, the HLL reports the distinct total.
Q5: Your product manager wants to bill advertisers on unique reach and the dashboard already uses HyperLogLog. What do you say?
That the dashboard number cannot be the invoice number. A 1 percent error on ten million impressions is a hundred thousand impressions of disputed spend, the sketch cannot show which users produced the count, and nothing in it is re-derivable during an audit — so no finance or legal review will accept it. The answer is two paths over the same events: keep the sketch for the real-time dashboard, where approximate and instant is exactly right, and run a nightly exact job over the raw event log for billing. The exact job is also your error monitor, because comparing it to the sketch tells you empirically how accurate the fast path has been.
Navigation
| ← Bloom Filters | Message Queues → |
| All Concepts | HLD Designs |