Bloom Filters, HyperLogLog and Friends: Probabilistic Data Structures
The analytics team wants “unique visitors per article per day” for 2 million articles. The first version keeps a Redis set of visitor IDs per article per day. A popular article collects 3 million 16-byte IDs; at about 70 bytes per set member with overhead that is around 200 MB for one key. Even at an average of 10,000 visitors per article, 2 million articles x 10,000 x 70 bytes is 1.4 TB of RAM per day of data, and the weekly uniques report has to union seven of those sets for every article.
The second version replaces each set with a HyperLogLog. Each key is at most 12 KB, most are far smaller because they start in a sparse encoding, the weekly report is a merge of seven keys, and the answer is within about 1% of the truth. The whole dataset fits on one modest node.
Nobody looking at the dashboard can tell the difference between 3,012,447 and 3,000,000 uniques. That is the trade at the heart of this article: give up a small, bounded amount of accuracy and get orders of magnitude less memory and CPU.
What it is
A probabilistic data structure answers a question approximately, with an error you choose up front, in memory that is tiny and usually fixed regardless of how much data flows through it. The common ones each answer one question:
| Structure | Question | Error type | Typical size |
|---|---|---|---|
| Bloom filter | Have I seen this item? | False positives, never false negatives | About 10 bits per item for 1% |
| Cuckoo filter | Have I seen it? (with delete) | False positives | Similar to Bloom |
| HyperLogLog | How many distinct items? | About 0.81% standard error in Redis | 12 KB, fixed |
| Count-Min Sketch | How often has this item appeared? | Overestimates only | Tens to hundreds of KB |
| t-digest | What is the p99? | Small rank error, best at the tails | A few KB |
| MinHash | How similar are these two sets? | Statistical, shrinks with more hashes | A few hundred bytes per set |
All of them rely on hash functions that spread items uniformly, and most can be merged: two sketches built on different machines combine into one sketch of the union. That property is what makes them so useful in distributed systems.
How it works
Bloom filters
A Bloom filter is an array of m bits, all zero, and k independent hash functions. To insert an item, hash it k times and set those k bits to 1. To query, hash it the same way: if any of the k bits is 0, the item was definitely never inserted. If all are 1, it was probably inserted, or other items happened to set those same bits.
flowchart LR A["insert: user_42"] --> H1["h1 mod m = 3"] A --> H2["h2 mod m = 9"] A --> H3["h3 mod m = 14"] H1 --> BITS["Bit array<br/>bits 3, 9, 14 set to 1"] H2 --> BITS H3 --> BITS Q["query: user_77"] --> Q1["h1 = 3, bit is 1"] Q --> Q2["h2 = 6, bit is 0"] Q1 --> BITS Q2 --> NO["A bit is 0<br/>definitely not present"] style BITS fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style NO fill:#E1F5EE,stroke:#0F6E56,color:#085041
With n items inserted, the false positive rate is approximately:
p = (1 - e^(-k * n / m))^k
optimal k = (m / n) * ln 2
bits per item = m / n = -ln(p) / (ln 2)^2 = 1.44 * log2(1 / p)
The bits-per-item figure depends only on the target error, not on item size. A 2 KB URL and an 8-byte integer cost the same.
Bloom filters have three limits. You cannot delete (clearing a bit may remove other items). You cannot list the items. And once you insert more than the n you sized for, the false positive rate climbs fast: at 2x the design load the 1% filter above is near 16%. Scalable Bloom filters handle growth by adding new, larger filters as each fills.
Counting Bloom and cuckoo filters
A counting Bloom filter replaces each bit with a small counter (typically 4 bits). Insert increments, delete decrements. It supports deletion at 4x the memory.
A cuckoo filter stores a short fingerprint of each item (say 8 to 12 bits) in one of two candidate buckets, computed so that either bucket can be derived from the other and the fingerprint. Lookup checks two buckets; delete removes the fingerprint. When both buckets are full, insertion kicks an existing fingerprint to its alternate bucket, cuckoo-style. The original paper (Fan et al., 2014) shows cuckoo filters use less space than Bloom filters when the target false positive rate is below about 3%, and lookups touch at most two memory locations. The catches: inserts can fail when the table is around 95% full, and deleting an item that was never inserted can remove someone else’s fingerprint.
HyperLogLog
Intuition first. Hash every item to a uniformly random 64-bit number. Half of all hashes start with a 0 bit, a quarter with 00, one in 2^20 with twenty zeros. If the longest run of leading zeros you have ever seen is 20, you have probably seen around 2^20 distinct items. Duplicates do not change anything, because the same item always produces the same hash.
One counter like that is far too noisy, so HyperLogLog splits the stream into many buckets and averages:
- Hash the item to 64 bits.
- Use the first 14 bits to pick one of 2^14 = 16,384 registers.
- In the remaining bits, count leading zeros plus one.
- Store the maximum value ever seen in that register.
- To estimate, take the harmonic mean of 2 raised to each register value, scale by the number of registers and a bias constant, with corrections for very small and very large counts.
flowchart LR I["item: visitor_9f3a"] --> H["64-bit hash"] H --> IDX["first 14 bits<br/>register 5021"] H --> REST["remaining 50 bits<br/>0001011..."] REST --> LZ["leading zeros + 1 = 4"] IDX --> R["register 5021 =<br/>max of old value, 4"] LZ --> R R --> E["estimate = harmonic mean<br/>over 16,384 registers"] style IDX fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style R fill:#FAEEDA,stroke:#854F0B,color:#633806 style E fill:#E1F5EE,stroke:#0F6E56,color:#085041
The standard error is 1.04 / sqrt(m). With m = 16,384 registers that is 1.04 / 128 = 0.81%. Each register needs 6 bits (enough to store a run of up to 63), so 16,384 x 6 = 98,304 bits = 12 KB. That is exactly what Redis uses: a dense HyperLogLog is 12 KB and counts up to 2^64 items with 0.81% standard error. Small counts use a sparse encoding that takes far less.
Merging is the superpower. The union of two HyperLogLogs is the register-by-register maximum, and it is lossless: merging seven daily sketches gives exactly the sketch you would have built from the whole week. In Redis that is PFADD to add, PFCOUNT to estimate, PFMERGE to union. Intersections are not native; inclusion-exclusion (A + B minus the union) works but the error is relative to the union, so small intersections of big sets are unreliable.
Count-Min Sketch
Count-Min Sketch answers “how many times have I seen x” for a stream with millions of distinct keys. It is a grid of d rows by w counters, with one hash function per row. To add an item, increment one counter in every row. To estimate its count, read its counter in every row and take the minimum.
flowchart TB X["add: worldcup"] --> R1["row 1, h1 = col 812<br/>counter + 1"] X --> R2["row 2, h2 = col 77<br/>counter + 1"] X --> R3["row 3, h3 = col 2045<br/>counter + 1"] R1 --> M["estimate = min of the 3 counters"] R2 --> M R3 --> M M --> T["never below the true count<br/>collisions only add"] style M fill:#EEEDFE,stroke:#534AB7,color:#3C3489 style T fill:#FAEEDA,stroke:#854F0B,color:#633806
Collisions only ever add to a counter, so the estimate never undercounts, and taking the minimum picks the row with the least collision noise. With total stream count N, choosing w = ceil(e / epsilon) and d = ceil(ln(1 / delta)) guarantees the estimate exceeds the true count by at most epsilon x N with probability at least 1 minus delta.
The same structure is how you find hot keys in a cache or a shard without counting every key exactly.
t-digest for percentiles
You cannot average percentiles, and exact percentiles need every value. A t-digest keeps the distribution as a sorted list of centroids (a mean and a count). Centroids near the middle of the distribution may absorb many points; centroids near the tails (p1, p99, p99.9) are kept tiny, so extreme percentiles stay accurate. A typical compression setting keeps a few hundred centroids, a few KB per digest. Digests from different hosts merge into a fleet-wide digest, which is how a metrics system reports a true fleet p99 rather than the meaningless average of per-host p99s (see time-series databases). Elasticsearch’s percentiles aggregation uses t-digest by default.
MinHash, briefly
MinHash estimates the Jaccard similarity of two sets (size of intersection over size of union). For each of k hash functions, keep the minimum hash value over the set’s elements. The probability that two sets share the same minimum for a given hash equals their Jaccard similarity, so the fraction of matching minimums across 128 hashes estimates it with a standard error around 1 / sqrt(128), about 0.09. Combined with locality-sensitive hashing (banding signatures into buckets), it finds near-duplicate documents in billions without comparing every pair. Web crawlers and training-data deduplication pipelines use this.
Where it breaks
Exceeding the design capacity. A Bloom filter sized for 10 million items silently degrades as you add 30 million. Monitor fill ratio (fraction of bits set) and rebuild or chain filters before it passes about 50%.
Using a false positive as a fact. “The Bloom filter says this username is taken” will wrongly reject 1% of free names. Use the filter as a fast negative check and confirm positives against the source of truth.
Small counts and small intersections. HyperLogLog’s error is relative: 0.81% of 50 million is 405,000. Intersections computed with inclusion-exclusion inherit the error of the union. “Users who visited both A and B” for a small overlap can come out negative.
Count-Min on the long tail. The error bound is relative to the total stream, not to the item. Rare items get inflated counts. Use it for heavy hitters, not for billing.
Hash quality and shared seeds. All of these assume uniform, independent hashes. A weak hash or reusing one hash with trivially related seeds clusters bits and raises error. Use a well-tested function (MurmurHash3, xxHash) and derive k hashes from two with double hashing. Sketches only merge if they were built with the same parameters and hash function.
Adversarial input. If attackers know your hash function, they can craft items that all hit the same bits or registers. Use keyed or seeded hashes on untrusted input.
Things that need exactness. Money, inventory, permissions and deduplication of payments are not places to accept a 1% error. See idempotency for exact dedup.
Real-world systems (Nov 2026)
LSM storage engines. RocksDB, Cassandra and other LSM-tree stores keep a Bloom filter per SSTable, so a point read skips every file that definitely does not contain the key. RocksDB’s commonly used setting of 10 bits per key gives about 1% false positives. Without filters, a read for a missing key would touch every level.
CDN cache admission. Most objects on a large CDN are requested once and never again. Maggs and Sitaraman’s 2015 paper on Akamai’s network reports that about three quarters of objects were “one-hit wonders” and describes a cache-on-second-hit rule using Bloom filters: an object is cached only if the filter has already seen it. That keeps one-off objects from evicting popular ones (see CDN and edge caching). The Caffeine Java cache’s TinyLFU admission policy uses a compact Count-Min-style frequency sketch for the same purpose, covered with eviction in cache eviction policies.
Unique counts. Redis HyperLogLog (PFADD, PFCOUNT, PFMERGE) is the standard tool for unique visitors and distinct users. BigQuery’s APPROX_COUNT_DISTINCT and the HLL functions in many warehouses use the HyperLogLog++ variant.
Redis 8. Redis Open Source 8 (2025, available under AGPLv3 among other licences) ships Bloom filter, cuckoo filter, Count-Min Sketch, Top-K and t-digest types built in, where they previously needed the RedisBloom module. Valkey keeps HyperLogLog in core and offers Bloom filters through its own module.
Percentiles. Elasticsearch and OpenSearch percentile aggregations use t-digest. Prometheus native histograms take a related approach with exponential buckets that also merge across instances.
How to apply it
Reach for a probabilistic structure when all of these are true:
- The exact answer needs memory proportional to the number of distinct items, and that number is large or unbounded.
- A bounded error is acceptable for the use (dashboards, trending, cache admission, skipping work).
- Either a wrong “yes” can be confirmed cheaply, or the error is relative and small compared to the values that matter.
Quick picker:
| You want to | Use | Remember |
|---|---|---|
| Skip lookups for keys that do not exist | Bloom filter | Size for peak n; about 10 bits per item for 1% |
| Same, but items get deleted | Cuckoo or counting Bloom | Cuckoo inserts can fail near full |
| Count distinct users or events | HyperLogLog | Merge for unions; avoid small intersections |
| Find the top K or hot keys | Count-Min plus a heap | Overestimates; good only for heavy hitters |
| Report p99 across a fleet | t-digest or native histograms | Never average percentiles |
| Find near-duplicate documents | MinHash plus LSH | More hashes, less error |
Interview questions
Q1: How many bits and hash functions does a Bloom filter need for 1 billion items at a 0.1% false positive rate?
Bits per item is -ln(p) / (ln 2)^2 = 6.908 / 0.4805, about 14.4 bits. Total is 1,000,000,000 x 14.4 = 14.4 billion bits, about 1.8 GB. The optimal hash count is 14.4 x ln 2, about 10. The answer does not depend on item size. If 1.8 GB is too much for one node, partition the filter by key hash across nodes; each shard is just a smaller Bloom filter for its share of keys. If items can be deleted, a cuckoo filter at a similar size supports deletion.
Q2: How does HyperLogLog count distinct items in 12 KB, and how do you get weekly uniques from daily counts?
Each item is hashed; 14 bits of the hash pick one of 16,384 registers and the register keeps the longest run of leading zeros (plus one) seen in the rest of the hash. Long runs are exponentially rare, so the maximum run indicates how many distinct hashes have been seen, and duplicates hash identically so they never change the result. Averaging across 16,384 registers with a harmonic mean gives a standard error of 1.04 / sqrt(16,384) = 0.81%. Each register needs 6 bits, so 16,384 x 6 bits = 12 KB. Weekly uniques come from merging the seven daily sketches, taking the maximum of each register, which is exactly the sketch of the whole week. Adding the daily counts would double count returning visitors.
Q3: Design trending hashtags over the last hour at 1 billion events per hour.
Exact counts per hashtag need a map that grows with every distinct tag, including millions of one-off tags. Instead, each stream processor keeps a Count-Min Sketch per one-minute window, for example width 27,183 and depth 7 (about 760 KB), giving overestimates of at most 0.01% of the window’s events with 99.9% confidence, plus a min-heap of the top few hundred candidates. Sketches with the same dimensions and hashes merge by adding counters, so a sliding hour is the sum of the last 60 minute sketches, and partitions from different processors merge the same way. Trending usually means growth relative to a baseline, so compare each candidate’s current-hour estimate with the previous day’s. Because the error is relative to the total stream, the estimates are only trustworthy for heavy hitters, which is exactly what trending needs. The windowing itself is a stream processing problem.
✅ Key takeaways
- Probabilistic structures trade a small, bounded error for memory that is tiny and often fixed, and most of them merge across machines.
- Bloom filters never give false negatives. Bits per item = 1.44 x log2(1/p): about 9.6 bits and 7 hashes for 1%, 14.4 bits and 10 hashes for 0.1%.
- HyperLogLog counts distinct items with 0.81% standard error in 12 KB (Redis). Unions merge losslessly; intersections are unreliable.
- Count-Min Sketch overestimates by at most epsilon times the stream size, so use it for heavy hitters and top-K, not for the long tail.
- t-digest gives mergeable, tail-accurate percentiles; MinHash estimates set similarity for near-duplicate detection. Never use approximations where exactness is a correctness requirement.
🧠 Check your understanding
0 / 4-
1A Bloom filter says a key is NOT present. What do you know?
If any of the k bits is 0, the key was never inserted, because inserting it would have set all k bits. Bloom filters have false positives only, so the tempting answer that both directions are probabilistic is wrong.
-
2You need a Bloom filter for 50 million items at a 1% false positive rate. Roughly how large is it?
About 9.6 bits per item at 1%, so 50 million x 9.6 = 480 million bits, about 60 MB. Item size is the trap: the filter stores only bits set by hashes, so a long URL costs the same as an integer.
-
3You have a Redis HyperLogLog per day of visitors. How do you get unique visitors for the week?
Merging takes the max of each register, which gives exactly the sketch of the whole week. Summing daily counts is tempting but counts a visitor who came on 3 days three times.
-
4A Count-Min Sketch with error bound 100,000 on a 1 billion event stream reports 120,000 for a hashtag. What can you conclude?
Count-Min only overestimates, and by at most epsilon times N with probability 1 minus delta, so the true count is at most 120,000 and at least 20,000. Option C reverses the direction of the error, a common mix-up.
Where to go next
- Cache patterns: the next phase starts with caching, where admission filters and frequency sketches show up again.
- Storage engines: B-tree vs LSM: why per-SSTable Bloom filters make LSM point reads fast.
- Cache stampedes and hot keys: detecting hot keys with frequency sketches and what to do once you find them.
- Time-series databases: where mergeable percentiles and distinct counts meet metrics storage.
Finished this lesson?
Mark it complete to track your progress across the roadmap.