Summary#
At very large scale, exact answers to some questions become too expensive. "Have we seen this URL before?" across 10 billion URLs, "how many distinct users visited today?" across billions of events, or "which 100 search terms are most popular right now?" across a stream of 100,000 queries per second would each need gigabytes of memory or a full scan to answer exactly. Probabilistic data structures answer such questions approximately, with a bounded and tunable error, in a tiny fraction of the space. A Bloom filter answers set membership: "definitely not present" or "probably present", using about 10 bits per item for a 1% false-positive rate, whatever the item's size. Counting Bloom, cuckoo and quotient filters add deletion and other features. A count-min sketch estimates how often each item occurs, never undercounting. HyperLogLog counts distinct items: 12 KB in Redis estimates cardinalities into the billions with about 0.81% standard error. Top-k algorithms such as Space-Saving find the heavy hitters in a stream with a fixed number of counters, and quantile sketches such as t-digest and DDSketch estimate p99 latency without storing every measurement. Two related deterministic structures complete the toolbox: Merkle trees find differences between large replicas by exchanging a few hashes, and skip lists give sorted, concurrent in-memory indexes. Use these structures when exact answers are unaffordable and the error is acceptable; reaching for one when a hash set would do is over-engineering.
Why It Exists#
Some questions are cheap to answer on small data and become very expensive as data grows:
- Membership: a web crawler must not fetch the same URL twice. A hash set of 10 billion URLs, at an average of 80 bytes per URL plus overhead, needs over a terabyte of memory. Even storing 16-byte hashes needs 160 GB.
- Counting distinct items: an analytics system reports daily unique visitors per page. Exact counting means keeping a set of visitor IDs for every page, for every day, and set unions across pages and days are expensive.
- Frequency: a search engine wants the most frequent queries in the last hour. Exact counting means one counter per distinct query, and most queries are rare, so memory grows with the long tail.
- Quantiles: a monitoring system reports the 99th-percentile latency of every service every minute. Exact percentiles require storing and sorting every measurement.
- Comparing replicas: two database replicas each hold a billion keys. Finding the handful that differ by sending every key would move gigabytes.
In each case, an approximate answer is good enough. A crawler that skips 1 in 1,000 new URLs by mistake loses little. A unique-visitor count that is off by 1% is still useful. The 100 most popular queries do not need exact counts. And the structures that give these approximations are not only small, they are also fast, often a few memory accesses per operation, and mergeable: sketches built on different servers can be combined into one, which makes them natural for distributed systems.
They have a cost: a probability of error, which you choose when you size the structure. Understanding exactly what kind of error each structure makes, false positives only, overestimates only, or relative error, is the key to using them correctly. Using one when a simple hash table or a database index would do is a design smell, so the first question is always whether the exact approach is really too expensive.
How It Works#
Bloom filter#
A Bloom filter, invented by Burton Bloom ("Space/Time Trade-offs in Hash Coding with Allowable Errors", Communications of the ACM, 1970), represents a set using:
- A bit array of m bits, all initially 0.
- k independent hash functions, each mapping an item to a position from 0 to m minus 1.
Insert: hash the item with each of the k functions, and set those k bits to 1.
Query: hash the item the same way, and check the k bits. If any is 0, the item was definitely never inserted, since inserting it would have set all of them. If all are 1, the item is probably in the set: either it was inserted, or other items happened to set all k of those bits. That second case is a false positive.
So a Bloom filter has no false negatives and a tunable false-positive rate. It stores no items, only bits, so its size does not depend on how large the items are: a 2 KB URL and an 8-byte integer cost the same.
A small example. Take m equal to 16 bits and k equal to 3. Insert "cat", which hashes to positions 2, 7 and 11, and "dog", which hashes to 4, 7 and 13. Bits 2, 4, 7, 11 and 13 are now set. Query "cow", which hashes to 2, 9 and 13: bit 9 is 0, so "cow" is definitely absent. Query "fox", which hashes to 4, 11 and 13: all are set, so the filter says "probably present", a false positive, since only "cat" and "dog" were inserted.
The false-positive rate. After inserting n items into m bits with k hash functions, the probability that a given bit is still 0 is about e to the power minus kn/m. A false positive needs all k probed bits to be 1, so the false-positive probability is approximately:
p ≈ (1 − e^(−kn/m))^k
For a fixed ratio of bits per item, m/n, the best number of hash functions is k equal to (m/n) times ln 2, about 0.69 times the bits per item, at which point about half the bits are set. With that optimum, the bits needed per item for a target rate p is about 1.44 times log2 of 1/p:
| Target false-positive rate | Bits per item | Optimal hash functions | Memory for 1 billion items |
|---|---|---|---|
| 10% | 4.8 | 3 | 600 MB |
| 1% | 9.6 | 7 | 1.2 GB |
| 0.1% | 14.4 | 10 | 1.8 GB |
| 0.01% | 19.2 | 13 | 2.4 GB |
Each tenfold reduction in false positives costs about 4.8 more bits per item. For comparison, a hash set of 1 billion 16-byte hashes needs at least 16 GB.
Operations Bloom filters cannot do.
- Delete: clearing an item's bits could clear bits shared with other items, creating false negatives. Counting Bloom filters and cuckoo filters fix this.
- List or count the items: the filter stores no items. The number of set bits gives a rough estimate of n, but nothing more.
- Grow: the false-positive rate rises steadily as more items are inserted than the filter was sized for. You must size it for the expected number of items, or use a scalable variant.
Union and intersection. Two Bloom filters with the same size and hash functions can be unioned with a bitwise OR of their arrays: the result is exactly the filter you would get by inserting both sets. A bitwise AND approximates the intersection, but with a higher false-positive rate than a filter built directly from the intersection.
Bloom filter, in depth#
Deriving the formula. One hash function sets a particular bit with probability 1/m, so the bit stays 0 with probability 1 minus 1/m. After kn hash operations, from n items times k functions, it is still 0 with probability (1 − 1/m) to the power kn, which for large m is about e to the power minus kn/m. A query for an absent item checks k positions, each set with probability 1 minus that, so all k are set with probability (1 − e^(−kn/m)) to the power k. This treats bits as independent, which they are not quite, but the approximation is very close for practical sizes. Minimising over k gives k equal to (m/n) ln 2, and substituting back gives p equal to roughly 0.6185 to the power m/n, which rearranges to the bits-per-item formula above.
A worked sizing. A crawler expects 10 billion URLs and accepts 0.1% false positives, so 1 in 1,000 new URLs is wrongly skipped. Bits per item: 14.4, so m is 144 billion bits, 18 GB. Hash functions: 10. That fits in memory on one large machine, or is split across several by URL hash. A hash set of 8-byte URL hashes would need at least 80 GB plus overhead, and 8-byte hashes would themselves collide, by the birthday bound, once the set is in the billions.
Getting k hash functions cheaply. Computing 10 independent cryptographic hashes per operation would be slow. Adam Kirsch and Michael Mitzenmacher showed ("Less Hashing, Same Performance: Building a Better Bloom Filter", ESA 2006) that two hash values suffice: positions g_i = h1 + i × h2 mod m, for i from 0 to k − 1, give the same asymptotic false-positive rate as k independent hashes. Implementations compute one fast 128-bit non-cryptographic hash, such as MurmurHash3 or xxHash, and split it into h1 and h2. Guava's BloomFilter and many other libraries use this trick.
Cache-friendly, blocked Bloom filters. A standard Bloom filter touches k random cache lines per query: 7 cache misses for a 1% filter that does not fit in CPU cache, each perhaps 100 ns. A blocked Bloom filter first hashes the item to one 64-byte block, a single cache line, and then sets k bits within that block. One cache miss per query instead of seven, at the cost of a slightly higher false-positive rate for the same memory, since blocks fill unevenly. RocksDB's newer Bloom filter format and many analytical databases use this layout.
Partitioned Bloom filters. Splitting the m bits into k equal slices, with each hash function setting a bit in its own slice, gives each hash function a fair share of the array, and makes the analysis exact. It also simplifies parallel implementations.
Scalable Bloom filters. When the number of items is not known in advance, a scalable Bloom filter (Paulo Sérgio Almeida, Carlos Baquero, Nuno Preguiça and David Hutchison, Information Processing Letters, 2007) starts with a small filter and, when it is full, adds a new, larger filter with a tighter false-positive rate. Queries check every filter. Because the error rates form a geometric series, such as 0.5%, 0.25%, 0.125% and so on, the total stays under the target. RedisBloom's BF.RESERVE with an expansion factor works this way.
False positives compound across checks. A system that checks a filter for every item in a large batch should expect p times the batch size false positives. A 1% filter checked for 100,000 profiles flags about 1,000 that were never inserted. Whether that matters depends on what a false positive costs.
Choosing what a false positive means. Design so that the filter's error is harmless or recoverable:
- Use the filter to skip expensive work when the answer is "definitely not": an LSM-tree skips SSTables that cannot contain the key, a cache skips the backend lookup for keys that cannot exist. A false positive just costs the work that would have been done anyway.
- Confirm positives with an exact lookup when a wrong "probably present" would be harmful, such as rejecting a username as taken.
- Accept the loss when a false positive merely drops a little value, as when a crawler skips a URL it has not seen, or a dating app never shows one profile that the user had not actually swiped on.
Counting Bloom and cuckoo filter#
Counting Bloom filters. Replace each bit with a small counter, typically 4 bits. Insert increments the k counters, delete decrements them, and a query checks that all k are non-zero. Li Fan, Pei Cao, Jussara Almeida and Andrei Broder introduced the idea for sharing cache summaries between web proxies ("Summary Cache: A Scalable Wide-Area Web Cache Sharing Protocol", SIGCOMM 1998), where proxies needed to remove URLs evicted from their caches. Their analysis showed that 4-bit counters overflow with negligible probability when the filter is sized for its load.
The cost is four times the memory of a plain Bloom filter for the same false-positive rate, and deletion is only safe for items that were really inserted: deleting an item that was never added, which a false positive might suggest, decrements counters belonging to other items and creates false negatives. Counting Bloom filters are useful when deletes are rare and verified, such as removing entries from a cache summary when they are evicted.
Cuckoo filters. Bin Fan, David Andersen, Michael Kaminsky and Michael Mitzenmacher ("Cuckoo Filter: Practically Better Than Bloom", CoNEXT 2014) proposed a filter that supports deletion with less space than a Bloom filter at low false-positive rates. Instead of setting bits, it stores a short fingerprint of each item, say 8 to 16 bits, in a hash table of buckets, each holding up to 4 fingerprints.
- Two candidate buckets: an item x with fingerprint f can live in bucket i1 = hash(x) or bucket i2 = i1 XOR hash(f). The XOR trick, partial-key cuckoo hashing, means that from either bucket and the fingerprint alone, you can compute the other bucket, without the original item.
- Insert: put f in i1 or i2 if either has a free slot. If both are full, evict a random fingerprint from one of them, move it to its other bucket, and repeat, up to a limit such as 500 moves. This is cuckoo hashing, named after the bird that pushes other eggs out of the nest.
- Query: check whether f appears in i1 or i2. That is two bucket reads, usually two cache lines.
- Delete: remove one copy of f from i1 or i2.
A false positive happens when a different item with the same fingerprint lives in one of the two buckets. With 4 slots per bucket and f-bit fingerprints, the rate is at most about 8 divided by 2 to the power f: 8-bit fingerprints give about 3%, 12-bit about 0.2%, 16-bit about 0.01%. Cuckoo filters with 4-slot buckets can be filled to about 95% before inserts start failing, so they use about (log2(1/p) + 3) divided by 0.95 bits per item. The paper shows this beats a space-optimised Bloom filter when the target false-positive rate is below about 3%.
Caveats of cuckoo filters.
- Inserts can fail when the table is nearly full. You must size it, or rebuild larger, and handle a failed insert.
- Duplicates are limited: inserting the same item more than 8 times (2 buckets times 4 slots) fills both buckets and fails, so applications must avoid duplicate inserts or count them separately.
- Delete only what you inserted: deleting an item that was never inserted, but happens to share a fingerprint, removes another item's fingerprint and creates a false negative.
Counting Bloom and cuckoo filter, in depth#
Comparing the membership filters.
| Filter | Bits per item at 1% | Bits per item at 0.1% | Delete | Lookup cost | Notes |
|---|---|---|---|---|---|
| Bloom | 9.6 | 14.4 | No | k random bits, up to k cache misses | Simplest; unions by OR |
| Blocked Bloom | About 10 to 11 | About 15 to 16 | No | One cache line | Fastest in practice |
| Counting Bloom (4-bit) | About 38 | About 58 | Yes, if item was inserted | k counters | Four times the memory |
| Cuckoo (4-way, 95% load) | About 10.2 | About 13.6 | Yes, if item was inserted | Two buckets | Inserts can fail when full |
| Quotient filter | About 10 to 13 | About 13 to 17 | Yes | Sequential scan of a short run | Mergeable, resizable |
| XOR filter | About 8.2 | About 12.3 | No; static | Three accesses | Built once from a fixed set |
XOR and ribbon filters for static sets. When the set is known in advance and never changes, such as the keys of an immutable SSTable, a static filter can be smaller still. The XOR filter (Thomas Mueller Graf and Daniel Lemire, "Xor Filters: Faster and Smaller Than Bloom and Cuckoo Filters", ACM Journal of Experimental Algorithmics, 2020) stores fingerprints so that the XOR of three table entries chosen by hashing equals the item's fingerprint, using about 1.23 times log2(1/p) bits per item, close to the theoretical minimum of log2(1/p). Ribbon filters (Peter Dillinger and Stefan Walzer, 2021) solve a similar linear system with better construction speed and space, and RocksDB offers a Ribbon filter as an alternative to its Bloom filter, saving roughly 30% of filter memory at the cost of slower construction.
The theoretical floor. Any structure that answers membership with false-positive rate p must use at least log2(1/p) bits per item. A Bloom filter uses 1.44 times that, about 44% more than the minimum. Cuckoo, quotient, XOR and ribbon filters get closer, which is why they win at low error rates, but Bloom filters remain popular for their simplicity, their unions, and their graceful behaviour when overfilled: they degrade, while cuckoo filters refuse inserts.
Deletion and stale data. Many systems avoid deletion altogether by rebuilding filters periodically. A filter for "URLs crawled this week" is rebuilt every week from the database; a per-SSTable filter is built once, when the SSTable is written, and discarded when compaction removes the SSTable. Rebuilding is simpler and safer than counting or cuckoo deletion when the source of truth is available.
Quotient filter#
A quotient filter (Michael Bender, Martin Farach-Colton and colleagues, "Don't Thrash: How to Cache Your Hash on Flash", VLDB 2012) is a compact hash table of fingerprints that is designed to be mergeable, resizable and friendly to disks and SSDs, because lookups scan contiguous memory.
How it stores fingerprints. Hash each item to a p-bit fingerprint. Split it into a quotient, the high q bits, and a remainder, the low r bits. The table has 2 to the power q slots, each storing an r-bit remainder plus three metadata bits. The quotient says which slot the remainder "belongs" to, its canonical slot. If that slot is taken, the remainder is stored in the next free slot to the right, using linear probing, and remainders that share a quotient are kept together, sorted, in a run. The three bits, often called is_occupied, is_continuation and is_shifted, record whether some item has this slot as its canonical slot, whether this entry continues a run, and whether it was shifted from its canonical slot. Together they let a lookup find the run for any quotient by scanning a short stretch of slots.
Operations.
- Lookup: compute quotient and remainder, locate the run for that quotient, and scan it for the remainder.
- Insert: find the run, insert the remainder in sorted position, and shift later entries right by one.
- Delete: remove the remainder and shift entries left.
- Merge: since entries are stored in order of their full fingerprint, two quotient filters can be merged like sorted lists, in one sequential pass, without rehashing the original items.
- Resize: double the table by moving one bit from each remainder into the quotient, again without the original items.
False positives happen when two items share the same p-bit fingerprint, with probability about n divided by 2 to the power p. Space is about r + 3 bits per slot, and the table works well up to about 75% to 90% occupancy, after which runs get long and lookups slow down.
Counting quotient filters. Prashant Pandey, Michael Bender, Rob Johnson and Rob Patro extended the design ("A General-Purpose Counting Filter: Making Every Bit Count", SIGMOD 2017) to store counts compactly within runs, giving a filter that also estimates frequencies, used in genomics for counting short DNA substrings.
Where quotient filters fit. They shine when filters must be merged, as in LSM-style structures that compact filters along with data, when filters live on SSD rather than in memory, because each lookup reads one contiguous region, and when the set grows beyond its initial size. For a simple in-memory membership test, a Bloom or cuckoo filter is usually easier.
Quotient filter, in depth#
Why sequential scans matter on flash. A Bloom filter that does not fit in memory needs k random reads per lookup, which on an SSD means k separate page reads of 4 KB each. A quotient filter's run is almost always within one page, so a lookup is a single page read. This was the original motivation in the "Don't Thrash" paper, which also described cascade filters, a hierarchy of quotient filters merged in the style of an LSM tree to support very fast inserts on flash.
Run length and load. With linear probing, the expected length of the cluster a lookup must scan grows quickly as the table fills: at 50% load it is short, around two slots, while at 90% it is tens of slots. That is why quotient filters are typically run at about 75% load, giving up some space to keep lookups fast. Later designs, such as the rank-and-select quotient filter in the 2017 paper, replace the three metadata bits with bit vectors indexed by rank and select operations, which allows much higher load factors with fast lookups.
Mergeability in distributed systems. Mergeable filters let independent nodes build filters over their own data and combine them without access to the raw items: a coordinator can merge the filters from 100 shards into one global filter. Bloom filters merge by OR only when they have identical parameters, and the result has the combined load, while quotient filters merge into a larger filter whose false-positive rate is governed by the fingerprint length.
Count-min sketch#
A count-min sketch (Graham Cormode and S. Muthukrishnan, "An Improved Data Stream Summary: The Count-Min Sketch and its Applications", Journal of Algorithms, 2005) estimates how many times each item has occurred in a stream, using a small, fixed amount of memory, no matter how many distinct items there are.
Structure. A two-dimensional array of counters with d rows and w columns, all starting at 0, and d independent hash functions, one per row, each mapping an item to a column.
- Update (item x occurred c times, usually 1): for each row i, add c to the counter at column hash_i(x).
- Query (how often has x occurred?): look at the d counters x maps to, one per row, and return the minimum.
Why the minimum works. Every counter x touches has been incremented by every occurrence of x, so each is at least the true count. Each counter may also include occurrences of other items that collided with x in that row, so each overestimates. Taking the minimum across rows picks the counter with the fewest collisions. A count-min sketch therefore never underestimates, and overestimates by a bounded amount with high probability.
The guarantee. With w = ⌈e/ε⌉ columns and d = ⌈ln(1/δ)⌉ rows, the estimate for any item is at most its true count plus ε times N, where N is the total of all counts, with probability at least 1 − δ. The error is relative to the total stream size, not to the item's own count, which is the key to understanding when a count-min sketch is useful:
- For frequent items, whose counts are large compared with εN, the estimate is accurate in relative terms.
- For rare items, the estimate can be dominated by collisions: an item seen 3 times in a stream of 100 million, with ε = 0.0001, may be estimated at up to 10,003.
A worked sizing. To estimate counts within 0.01% of the stream total (ε = 0.0001) with 99.9% confidence (δ = 0.001): w = 27,183 and d = 7, about 190,000 counters, or 760 KB with 4-byte counters. That is the same whether the stream has a thousand distinct items or a billion. A looser sketch, ε = 0.001 and d = 5, needs about 54 KB.
Properties that make it practical.
- Mergeable: two sketches with the same dimensions and hash functions are merged by adding their arrays cell by cell. Each server sketches its own traffic, and a coordinator adds them.
- Linear: decrements work too, so it can count insertions minus deletions, as long as final counts are not negative.
- Fast: d hash computations and d memory accesses per update and query, typically under a microsecond.
Conservative update. A common refinement increments only the counters that are currently at the minimum for the item, raising them to the new estimate, instead of incrementing all d. Counters that were already higher because of collisions are left alone, which reduces overestimation substantially in practice. It breaks linearity, so conservative sketches cannot handle deletions or be merged by simple addition with the same guarantees.
Count-min sketch, in depth#
Proof intuition for the bound. Fix an item x and a row. Every other item lands in x's column with probability 1/w, so the expected amount of other items' counts added to x's counter is at most N/w, which is ε N divided by e. By Markov's inequality, the chance that this row's excess exceeds εN is at most 1/e. Rows use independent hashes, so the chance that all d rows exceed εN is at most e to the power minus d, which equals δ. The minimum is within εN unless every row is bad.
Count sketch, its cousin. The count sketch of Moses Charikar, Kevin Chen and Martin Farach-Colton ("Finding Frequent Items in Data Streams", ICALP 2002) adds a second hash per row that chooses +1 or −1, so collisions cancel out on average, and takes the median across rows instead of the minimum. Its estimates are unbiased, with error proportional to the square root of the sum of squared counts rather than to N, which is much better for skewed streams, at the cost of possibly underestimating. Count-min is simpler and gives one-sided error; count sketch is better when you need unbiased estimates.
Heavy-tailed data helps. Real streams, such as search queries, URLs and IP addresses, are highly skewed, roughly following Zipf's law. Most of N is concentrated in a few heavy items, so the sketch is accurate where it matters, for the heavy hitters, and inaccurate only for rare items, whose counts you usually do not need precisely.
Count-min in caching. Cache admission policies need to know how often a key has been requested recently, for every key, including those not in the cache. TinyLFU (Gil Einziger, Roy Friedman and Ben Manes, "TinyLFU: A Highly Efficient Cache Admission Policy", ACM Transactions on Storage, 2017) keeps a count-min sketch with small 4-bit counters as the frequency estimator: a new key is admitted to the cache only if its estimated frequency exceeds that of the key it would evict. To make the counts reflect recent popularity, all counters are periodically halved, an ageing step. The Java caching library Caffeine uses W-TinyLFU, a variant with a small window cache in front, and the frequency sketch costs only a few bytes per cache entry. See Cache Eviction and Invalidation.
Time windows. A sketch counts everything since it was created. For "counts in the last hour", keep one sketch per minute and sum the last 60 when querying, dropping old ones, or use exponential ageing as TinyLFU does. Sliding windows over sketches are cheap because sketches add.
HyperLogLog#
HyperLogLog (Philippe Flajolet, Éric Fusy, Olivier Gandouet and Frédéric Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm", 2007) estimates the number of distinct items, the cardinality, in a stream, using a few kilobytes regardless of whether the answer is a thousand or a billion.
The intuition. Hash every item to a uniformly random-looking bit string. Half of all hashes start with a 1, a quarter start with 01, an eighth with 001, and so on: a hash starts with r − 1 zeros followed by a 1 with probability 2 to the power minus r. If, among all the items you have seen, the longest run of leading zeros is 20, you have probably seen around 2 to the power 20, about a million, distinct items, because a run that long is a one-in-a-million event. Repeated items hash identically, so they do not change the answer: only distinct items count.
A single maximum is a very noisy estimate: one lucky hash could make you think you have seen 2 to the power 30 items. HyperLogLog reduces the noise by stochastic averaging:
- Use the first b bits of each hash to choose one of m = 2 to the power b registers.
- In that register, keep the maximum position of the first 1 bit in the remaining bits of the hash.
- To estimate, combine the registers with a harmonic mean, which is much less sensitive to outlying large values than an arithmetic mean, multiply by m and a bias-correction constant α_m, about 0.7213 for large m: estimate = α_m × m² divided by the sum over registers of 2 to the power minus register.
Accuracy. The standard error is about 1.04 divided by the square root of m. With m = 16,384 registers (b = 14), it is about 0.81%. With 1,024 registers, about 3.25%. Each register only needs to hold a number up to about 64, so 6 bits suffice.
Redis's implementation. PFADD, PFCOUNT and PFMERGE implement HyperLogLog with 16,384 6-bit registers, 12 KB per key, giving about 0.81% standard error for counts up to 2 to the power 64. Small HyperLogLogs use a sparse encoding that takes far less than 12 KB until the count grows, and Redis switches to the dense 12 KB form automatically. The PF prefix honours Philippe Flajolet, who died in 2011.
Merging, the superpower. The union of two HyperLogLogs is computed by taking the maximum of each register pair. That makes distributed and time-based counting easy: keep one HyperLogLog per page per hour, and the unique visitors for a day is the merge of 24 of them; the unique visitors across a site is the merge of every page's sketch. Exact distinct counts could never be combined this way without keeping the underlying sets.
Small and large ranges. For small cardinalities, many registers are still 0 and the raw estimate is biased, so HyperLogLog switches to linear counting: estimate m times ln(m divided by the number of zero registers). Google's HyperLogLog++ (Stefan Heule, Marc Nunkesser and Alexander Hall, "HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm", EDBT 2013) improved this with a 64-bit hash, so there is no need for a large-range correction, empirical bias correction for the middle range, and a sparse representation for small sets. BigQuery's APPROX_COUNT_DISTINCT and HLL functions, and Elasticsearch's cardinality aggregation, are based on HyperLogLog++.
HyperLogLog, in depth#
Why the harmonic mean? Each register's value R gives a rough estimate of 2 to the power R for the number of distinct items routed to it. Those estimates are heavily right-skewed: one register with an unusually long zero run contributes a huge 2 to the power R. The arithmetic mean would be dominated by such outliers. The harmonic mean, m divided by the sum of 2 to the power minus R, weights small values more and suppresses the outliers, and Flajolet and colleagues showed it gives error close to the theoretical optimum for this amount of memory. The predecessor, LogLog (Marianne Durand and Philippe Flajolet, ESA 2003), used the arithmetic mean of register values and had a standard error of about 1.30 divided by the square root of m; HyperLogLog's harmonic mean improved that to 1.04 divided by the square root of m. Both build on probabilistic counting by Flajolet and G. Nigel Martin ("Probabilistic Counting Algorithms for Data Base Applications", Journal of Computer and System Sciences, 1985).
A worked accuracy example. A site has 40 million unique monthly visitors, counted with Redis HyperLogLog. The standard error of 0.81% means the estimate is within about ±324,000 roughly 68% of the time, and within about ±650,000, two standard errors, roughly 95% of the time. For a dashboard, that is fine. For billing advertisers by unique reach, it may not be, and the contract may require exact counts from a batch job.
Intersections are hard. HyperLogLogs merge for unions, but there is no direct intersection. "Users who visited both page A and page B" can be estimated by inclusion-exclusion, |A| + |B| − |A ∪ B|, but the error is relative to the union, so when the intersection is small compared with the sets, the estimate can be meaningless, even negative. For intersections, use MinHash or theta sketches, such as those in Apache DataSketches, which estimate set similarity and intersections with controllable error.
Security uses. Counting distinct values quickly is useful for detecting attacks: the number of distinct source IP addresses hitting an endpoint per minute (a sudden jump suggests a distributed attack), the number of distinct destination ports a single source touches (a port scan), or the number of distinct accounts a single IP tries to log into (credential stuffing). Keeping one HyperLogLog per source or per endpoint per minute costs kilobytes each and can run at line rate.
Sizing caches with HyperLogLog. To size a cache, you want to know how many distinct keys are requested in a period, the working set. A HyperLogLog over request keys per hour gives that number cheaply: if 30 million distinct keys are requested per hour, averaging 2 KB each, an hourly working set needs about 60 GB of cache. Counting distinct keys over different windows, 1 minute, 1 hour and 1 day, shows how hit rate would change with cache size.
Analytics and metrics. Daily and monthly active users, distinct search queries, unique devices per campaign and distinct error signatures are all standard HyperLogLog uses. Analytical databases expose them as approx_distinct in Presto and Trino, uniq and its variants in ClickHouse, approx_count_distinct in Spark, and HLL extensions for PostgreSQL. They often let you store the sketch itself in a table, so you can merge daily sketches into weekly and monthly counts later without re-reading raw events.
Top-k heavy hitters#
The top-k or heavy hitters problem asks for the k most frequent items in a stream, such as the 100 most searched queries, the most viewed videos, or the IP addresses sending the most requests, without keeping a counter for every distinct item.
Approach 1: count-min sketch plus a heap. Maintain a count-min sketch of all items, plus a min-heap of the current top k candidates with their estimated counts. On each event, update the sketch, read the item's estimate, and if it exceeds the smallest count in the heap, insert or update the item in the heap, evicting the smallest. Memory: the sketch plus k entries. Because the sketch overestimates, rare items occasionally sneak into the heap with inflated counts, but true heavy hitters are always found, since their estimates are at least their real counts.
Approach 2: Misra-Gries. Jayadev Misra and David Gries ("Finding Repeated Elements", Science of Computer Programming, 1982) gave a deterministic algorithm with k − 1 counters:
- If the item has a counter, increment it.
- Otherwise, if there is a free counter, assign it with count 1.
- Otherwise, decrement every counter by 1, and drop counters that reach 0.
Every item that occurs more than N/k times is guaranteed to be among the counters at the end, and each count underestimates the true count by at most N/k. A second pass, or an exact counter for the survivors, gives exact counts if needed.
Approach 3: Space-Saving. Ahmed Metwally, Divyakant Agrawal and Amr El Abbadi ("Efficient Computation of Frequent and Top-k Elements in Data Streams", ICDT 2005) proposed a variant that is the usual choice in practice:
- Keep m counters, each with an item, a count and an error bound.
- If the item is monitored, increment its count.
- Otherwise, replace the item with the smallest count: the new item takes over that counter, with count equal to the old minimum plus 1, and records the old minimum as its maximum possible overcount.
Space-Saving never underestimates, its overestimate for any item is at most N/m, and with a suitable data structure, the "stream-summary", each update takes constant time. With m equal to a few times k, the top k list is accurate for skewed streams.
Approach 4: Lossy counting. Gurmeet Singh Manku and Rajeev Motwani ("Approximate Frequency Counts over Data Streams", VLDB 2002) split the stream into buckets of width 1/ε and prune counters whose count plus error is below the current bucket number, guaranteeing all items above a support threshold are reported, with counts accurate to within εN.
Distributed top-k. Each server computes a local top-k summary, and an aggregator merges them. A subtle problem: an item that is number 101 on every one of 100 servers may be number 1 globally, yet appear in no local top 100. Fixes:
- Keep more than k locally, such as 10k, which makes such misses unlikely in skewed data.
- Merge sketches rather than lists: count-min sketches add exactly, and Space-Saving summaries can be merged with bounded error.
- Partition by item: route each item to one aggregator by hashing it, so each item's full count lives in one place, then combine the per-aggregator top-k lists exactly. This is the design behind most real-time top-k systems, typically built on Kafka partitions and a stream processor such as Flink. See Design a Top-K System and Batch and Stream Processing.
Top-k heavy hitters, in depth#
A worked example. A video platform receives 1 million view events per second and wants the top 100 videos in the last hour, updated every minute. There are 500 million distinct videos, but views are highly skewed. Exact counting in a hash map per worker would need an entry per video seen, tens of millions per minute. Instead:
- Partition events by video ID across 32 workers, about 31,000 events per second each.
- Each worker keeps a Space-Saving summary with 10,000 counters per minute, about 400 KB, and emits its top 1,000 at the end of each minute.
- Because partitioning by video ID means each video lives on exactly one worker, merging the 32 lists of 1,000 gives the exact top 1,000 of the minute, up to Space-Saving's bounded error.
- An hourly view merges the last 60 minute summaries, keeping a few thousand candidates.
Total memory is a few tens of megabytes, compared with gigabytes for exact counters, and the top 100 are almost certainly correct because heavy hitters dominate.
Exactness when it matters. Approximate top-k is fine for a "trending" widget. For payouts, such as paying creators per view, run an exact batch job on the raw events stored in a data lake, and use the stream result only for display. This lambda-style split, fast and approximate alongside slow and exact, is common. See Design a Top-K System.
Hot keys in caches. Top-k detection is also how systems find hot keys: a cache client or proxy keeps a small Space-Saving summary of requested keys per second, and when a key's rate passes a threshold, it is replicated to several cache nodes or served from a local in-process cache. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
Approximate quantiles#
Monitoring needs percentiles: the median, p95, p99 and p99.9 of request latency. Averages hide the tail: a service whose average latency is 50 ms may have a p99 of 2 seconds. But an exact percentile needs every value sorted, and a service handling 50,000 requests per second produces 3 million measurements a minute per service. Quantile sketches estimate percentiles with bounded error in a small, mergeable summary.
Fixed-width buckets. The simplest approach is a histogram with fixed boundaries, such as 0 to 10 ms, 10 to 20 ms, and so on. Each measurement increments one bucket counter. A percentile is estimated by finding the bucket where the cumulative count crosses the target, and interpolating within it. Histograms are tiny and merge by adding counts, but the accuracy depends entirely on the bucket choice: with 10 ms buckets, a p99 between 10 and 20 ms is only known to within 10 ms, and if latencies range from 1 ms to 10 s, fixed-width buckets either waste thousands of buckets or are too coarse where it matters.
Exponential buckets. Make bucket boundaries grow geometrically, such as 1, 2, 4, 8, 16 ms and so on, or more finely, each 10% wider than the last. The relative error is then bounded: any value is known to within the width of its bucket, a fixed percentage. Prometheus histograms use configurable bucket boundaries, typically exponential, and newer native histograms use exponential buckets automatically. HdrHistogram, by Gil Tene, records values with a configurable number of significant digits across a huge range, using a bucket layout based on powers of two subdivided linearly, and is widely used for latency measurement.
DDSketch. Charles Masson, Jee Rim and Homin Lee at Datadog ("DDSketch: A Fast and Fully-Mergeable Quantile Sketch with Relative-Error Guarantees", VLDB 2019) formalised exponential bucketing: with bucket boundaries at powers of γ = (1 + α) / (1 − α), every quantile estimate is within relative error α, such as 1%, of the true value. It is fully mergeable, so per-host sketches combine exactly into per-service sketches, and bucket counts can be collapsed to bound memory.
Dynamic histograms: t-digest and KLL. Instead of fixed buckets, adapt the summary to the data:
- t-digest (Ted Dunning, with Otmar Ertl, "Computing Extremely Accurate Quantiles Using t-Digests", 2019) keeps clusters of nearby values, called centroids, each with a mean and a count. Clusters near the median may hold many points, while clusters near the tails hold few, so accuracy is highest at extreme quantiles like p99.9, where it matters most. A t-digest of a few hundred centroids, a few kilobytes, estimates tail quantiles within a fraction of a percent of rank.
- GK (Michael Greenwald and Sanjeev Khanna, "Space-Efficient Online Computation of Quantile Summaries", SIGMOD 2001) and KLL (Zohar Karnin, Kevin Lang and Edo Liberty, "Optimal Quantile Approximation in Streams", FOCS 2016) give guarantees on rank error: the value returned for p99 has a true rank within ε of 99%. KLL is space-optimal for this guarantee and is implemented in Apache DataSketches.
Rank error versus value error. A sketch with 1% rank error might return the p98 or the p100 value when you asked for p99, which in a long-tailed distribution could be a factor of two different in milliseconds. A sketch with 1% relative value error, such as DDSketch, returns a value within 1% of the true p99 latency. For latency monitoring, relative value error is usually the more useful guarantee.
Never average percentiles. The p99 of a service is not the average of its hosts' p99s, and the hourly p99 is not the average of the minute p99s. Correct aggregation requires merging the underlying histograms or sketches, then computing the percentile. This is the main reason to store sketches rather than precomputed percentiles. See Observability: Logs, Metrics and Traces.
Approximate quantiles, in depth#
Where quantile sketches are used.
- Performance monitoring: per-endpoint latency percentiles every 10 seconds across thousands of hosts, merged per service, region and version. Datadog uses DDSketch for its distributions, and Prometheus histograms are aggregated across instances with
histogram_quantileover summed bucket counts. - Service level objectives: an SLO such as "99% of requests complete within 300 ms over 30 days" is checked by counting requests above and below the threshold, which a histogram with a bucket boundary at 300 ms answers exactly. Choose bucket boundaries at your SLO thresholds.
- A/B testing and analytics: comparing median and p90 page-load time between experiment groups, or median order value per segment, over billions of events. Sketches computed per day and per segment merge into any combination later.
- Load balancing and autoscaling: a load balancer that tracks recent latency percentiles per backend can route away from slow instances, and autoscalers can scale on p95 latency rather than CPU. These need cheap, continuously updated sketches, often with decay so old measurements fade.
Choosing between them.
| Approach | Error guarantee | Mergeable | Memory | Best for |
|---|---|---|---|---|
| Fixed-width histogram | Bucket width, absolute | Yes, exactly | Tiny | Known narrow ranges; SLO thresholds |
| Exponential histogram, HdrHistogram | Relative, by bucket growth | Yes, exactly | Small, a few KB | Latency over wide ranges |
| DDSketch | Relative value error α | Yes, exactly | Small; can collapse low buckets | Latency percentiles at scale |
| t-digest | Small rank error, best at tails | Yes, approximately | A few KB | Extreme quantiles in analytics |
| KLL | Rank error ε, proven optimal | Yes | Small | General quantiles with guarantees |
Merkle trees#
A Merkle tree, or hash tree, named after Ralph Merkle (who described it in his 1979 work on digital signatures, published as "A Digital Signature Based on a Conventional Encryption Function", CRYPTO 1987), summarises a large data set in a tree of hashes. Unlike the structures above, it is exact: it uses cryptographic hashes, whose collisions are practically impossible, to detect differences or prove membership.
Structure.
- Split the data into blocks, or key ranges, and hash each one: these are the leaves.
- Each internal node is the hash of its children's hashes concatenated.
- The single hash at the top, the root, summarises everything. Any change to any block changes its leaf, every ancestor and the root.
Finding differences between replicas. Two replicas each build a Merkle tree over the same key ranges. They compare roots: if equal, the data is identical, and a single hash exchange proved it. If not, they compare the children, then descend only into subtrees whose hashes differ. With a tree of depth 20 over a million ranges, finding a handful of differing ranges takes on the order of a few hundred hash comparisons, instead of transferring every key. Amazon's Dynamo (Giuseppe DeCandia and colleagues, "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007) used Merkle trees for anti-entropy, background repair of replicas that diverged, and Cassandra's repair process builds Merkle trees over token ranges for the same purpose. See Quorums and Leaderless Replication.
Proving membership. To prove that a block belongs to a tree with a known root, send the block plus the hashes of the siblings along its path to the root, a Merkle proof of log2(n) hashes. The verifier recomputes the path and checks it reaches the root. This is how Bitcoin's lightweight clients verify that a transaction is in a block, using only the block header, and how Certificate Transparency logs (RFC 6962, 2013) prove that a TLS certificate was logged.
Other uses. Git identifies every file, directory and commit by the hash of its contents, forming a Merkle-like directed acyclic graph, so two repositories find what they need to exchange by comparing hashes. ZFS and Btrfs checksum blocks in a hash tree to detect silent disk corruption. IPFS addresses content by Merkle DAG hashes.
Merkle trees, in depth#
The cost of keeping trees current. Rebuilding a Merkle tree requires reading and hashing all the data in its range, which for a large Cassandra node can take hours, and is why repairs are scheduled carefully. Trees can instead be maintained incrementally, updating the leaf and its ancestors on every write, at a small cost per write: Dynamo-style systems that keep trees per key range do this. Tree granularity is a trade-off: more leaves mean finer repair, so less data is transferred per difference, but larger trees to build and exchange.
Range-based versus key-based leaves. If leaves cover fixed key ranges, both replicas must use identical ranges for the comparison to work, which is a problem when ranges are reassigned as nodes join or leave. Dynamo's paper notes that key ranges change on membership changes, requiring trees to be recomputed. Systems choose fixed virtual-node or token ranges to keep trees stable.
Merkle trees are not probabilistic, but sit with these structures because they solve the same kind of problem: summarising huge data in a small structure so that distributed nodes can compare, verify or synchronise without moving everything.
Skip lists briefly#
A skip list (William Pugh, "Skip Lists: A Probabilistic Alternative to Balanced Trees", Communications of the ACM, 1990) is a sorted linked list with express lanes. The bottom level links every element in order. Each element is also promoted to the next level up with probability p, typically one half or one quarter, and so on, so level 1 links about half the elements, level 2 a quarter, and so on.
Search starts at the top level of the head node, moves right while the next element is smaller than the target, then drops down a level, and repeats until it reaches the bottom. Because each level skips roughly 1/p elements of the level below, search, insert and delete take expected O(log n) time, the same as a balanced tree, but using randomness instead of rotations or rebalancing.
Why systems use them.
- Simplicity: insert is "search, then link the new node into each level it was promoted to". No rebalancing.
- Concurrency: lock-free skip lists are much easier to build than lock-free balanced trees, since an insert only changes a few local pointers. Java's
ConcurrentSkipListMapis one. - Range scans: the bottom level is a sorted linked list, so iterating a range is trivial.
Where they appear. Redis's sorted sets use a skip list, together with a hash table for lookups by member, with p equal to one quarter, giving ZRANGE and ZRANK in logarithmic time. LevelDB and RocksDB use a skip list as the default memtable, the in-memory sorted buffer of recent writes before they are flushed to an SSTable. See Storage Engines: B-Trees vs LSM Trees and Redis.
Search for 25 in the diagram: at level 2, move from head to 17, since the next is the end; drop to level 1 at 17, the next is 40, too big; drop to level 0 at 17, move to 25. Four steps instead of five, and the saving grows logarithmically with size.
Error vs memory trade-offs and sizing#
Every structure on this page trades memory for accuracy, and each kind of error behaves differently. Know which error you are buying.
| Structure | Question answered | Error type | Size rule of thumb | Mergeable |
|---|---|---|---|---|
| Bloom filter | Is x in the set? | False positives only | 1.44 × log2(1/p) bits per item; 9.6 bits at 1% | Yes, OR, same parameters |
| Cuckoo filter | Is x in the set? (with delete) | False positives only | (log2(1/p) + 3) / 0.95 bits per item | No simple merge |
| Quotient filter | Is x in the set? (with delete, merge, resize) | False positives only | About log2(1/p) + 3 bits per slot at 75 to 90% load | Yes, sequential merge |
| Count-min sketch | How often has x occurred? | Overestimate by at most εN, with probability 1 − δ | (e/ε) × ln(1/δ) counters | Yes, add cell by cell |
| HyperLogLog | How many distinct items? | Relative, about 1.04/√m standard error | m registers of 6 bits; 12 KB for 0.81% | Yes, max per register |
| Space-Saving | Which items are most frequent? | Overestimate by at most N/m | m counters, a few times k | Yes, with bounded error |
| DDSketch | What is the p99 value? | Relative value error α | Logarithmic in value range divided by α | Yes, exactly |
| t-digest, KLL | What is the p99 value? | Rank error | Hundreds of centroids or items | Yes |
How to size, step by step.
- Estimate the input: number of items n for filters, stream size N for counts, expected cardinality for HyperLogLog, value range for quantiles.
- Decide the error you can tolerate, in terms of the consequence: "1 in 1,000 new URLs skipped", "unique users within 1%", "top 100 queries correct", "p99 within 2%".
- Apply the formula, and add headroom: size filters for 1.5 to 2 times the expected items, since false positives grow quickly when a filter is overfilled.
- Multiply by the number of instances: one Bloom filter per user, one HyperLogLog per page per hour, or one sketch per service per minute. A small structure times millions of instances is a big memory bill.
- Check the alternative: compute what the exact solution would cost. If it is affordable, use it.
Overfilling a Bloom filter. A filter sized for 1 million items at 1% behaves like this as more are inserted:
| Items inserted | False-positive rate |
|---|---|
| 1 million (design load) | 1.0% |
| 1.5 million | 5.8% |
| 2 million | 15.7% |
| 4 million | 68% |
The error rises steeply, which is why filters must be sized for peak load, or rebuilt, or made scalable.
Per-key structures at scale. A dating app keeping a Bloom filter of each user's swipe history, for 50 million users with an average of 5,000 swipes at 1%, needs about 50 million × 5,000 × 9.6 bits, about 300 GB. That is a lot of cache memory, so filters might be built only for heavy users above a threshold, with small histories kept as exact lists. HyperLogLog per page per hour at 12 KB for 10 million pages is 120 GB per hour of data, so sparse representations, or keeping only daily sketches for long-tail pages, matter.
Error vs memory trade-offs and sizing, in depth#
Error compounds when structures are combined. A system that uses two filters in sequence, each with a 1% false-positive rate, has about a 2% chance of a false positive overall. A union of 30 daily HyperLogLogs has the same relative error as one, which is a strength, but an intersection estimate does not. A top-k system built on a count-min sketch inherits the sketch's overestimates. Work out the end-to-end error, not just the component error.
The cost of a false positive decides the target. In an LSM tree, a Bloom filter false positive costs one unnecessary disk read, perhaps 100 microseconds on an SSD, so a 1% rate is fine. In a malware URL checker that blocks pages, a false positive blocks a legitimate site, so the filter is used only to decide whether to make an exact server-side check, and the exact check makes the final decision. In a crawler, a false positive loses one page forever, which at 0.1% across 10 billion pages is 10 million pages, perhaps acceptable, perhaps not.
Memory hierarchy matters as much as size. A 1.2 GB Bloom filter fits in RAM but not in CPU cache, so each lookup costs several cache misses, about 100 ns each. A blocked Bloom filter, one cache miss per lookup, can be several times faster for the same false-positive budget. For filters on SSD, quotient filters' sequential layout wins. Speed per lookup, not only bits per item, often decides the structure.
When exact is cheaper than you think. A hash set of 10 million 8-byte IDs is roughly 100 to 200 MB depending on the implementation: fine on one server. Redis sets of a few thousand members per key are cheap. A database index lookup is a millisecond. Interviewers react badly to a Bloom filter where a hash set or an index lookup would do, so do the arithmetic first, and introduce probabilistic structures only when the numbers force you to.
Real uses#
Storage engines: skipping files. In an LSM-tree store such as Cassandra, RocksDB, LevelDB, HBase or ScyllaDB, data is spread across many immutable SSTables, and a read for one key might have to check each of them. Each SSTable carries a Bloom filter of its keys, built when the file is written. A read checks the filters first and opens only the SSTables whose filter says "maybe". With about 10 bits per key and a 1% false-positive rate, a lookup that would have touched 20 files typically touches one or two. Cassandra exposes this as bloom_filter_fp_chance, by default 0.01 for most compaction strategies. Time-series databases built on LSM trees use the same technique: a query for one host's series over a long range skips every file that cannot contain that series. See Storage Engines: B-Trees vs LSM Trees.
Web crawlers: URL and content deduplication. A crawler fetching billions of pages first checks each discovered URL against the set of URLs already crawled. A database lookup per URL works, with an index on the URL or its hash, and modern databases handle such indexes well. A Bloom filter avoids that lookup for the vast majority of new URLs, which are definitely not in the set. Content deduplication works the same way: hash the fetched page's content and check whether that hash has been seen, since different URLs, such as http://example.com and http://www.example.com, often serve identical pages. The false positives mean a small fraction of new pages are skipped, which is usually an acceptable price. In Redis, the RedisBloom module provides BF.ADD and BF.EXISTS; without it, a Bloom filter can be built on Redis bitmaps with SETBIT and GETBIT, or kept in the crawler's memory. See Design a Web Crawler.
Dating and recommendation feeds: never show it again. A dating app must not show a user profiles they have already swiped on. For most users, a recent-swipes list cached on the client, plus a filter against the swipe database when building the feed, is enough. For users with very long swipe histories, the exact "contains" check against tens of thousands of IDs gets slow, so a per-user Bloom filter of swiped profiles, cached alongside the feed builder, filters candidates quickly. False positives mean a few profiles the user never swiped on are never shown, which is invisible to the user. The filters must be updated on each swipe and rebuilt from the swipe store if the cache is lost, which is expensive at scale, so many designs reserve this for heavy users. Feed-recommendation systems use the same technique to avoid repeating articles or videos. See Design a Dating App.
Caches and CDNs: avoiding wasted work.
- Avoiding database lookups for keys that do not exist: a Bloom filter of all valid keys in front of the database stops requests for non-existent keys, a technique that defends against cache penetration, where attackers or bugs request random keys that always miss the cache and hit the database. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
- One-hit wonders: Bruce Maggs and Ramesh Sitaraman ("Algorithmic Nuggets in Content Delivery", ACM SIGCOMM Computer Communication Review, 2015) described how Akamai found that a large fraction of objects, around three quarters in their measurements, were requested only once, and caching them evicted useful content. A Bloom filter records objects seen once, and an object is cached only on its second request, which reduced disk writes substantially and improved hit rates.
- Admission by frequency: TinyLFU's count-min sketch, described above, admits a new item only if it is requested more often than the item it would evict.
- Cache summaries: proxies exchange Bloom filters of their cache contents so a proxy can ask a peer for an object only if the peer probably has it, the original use of counting Bloom filters.
Analytics: distinct counts at scale. Daily active users, unique visitors per page, distinct devices per campaign, and distinct search queries are standard HyperLogLog uses, through Redis PFADD and PFCOUNT, or the approximate distinct functions in BigQuery, Presto, Trino, Spark, ClickHouse, Druid and Elasticsearch. Storing sketches per hour or day allows merging into any window later.
Trending and abuse detection: heavy hitters. Trending hashtags and queries, top videos, the IP addresses or API keys sending the most traffic, and hot cache keys are found with count-min sketches plus heaps, or with Space-Saving. Rate limiters sometimes use count-min sketches to track request counts per client in fixed memory when the number of clients is huge. See Design a Rate Limiter.
Networking and security. Routers and intrusion detection systems use count-min sketches and HyperLogLogs to find heavy flows and count distinct sources in line-rate traffic. Early versions of Google Chrome's Safe Browsing used a Bloom filter of malicious URL prefixes on the client, so most URLs could be cleared locally, with a server check only when the filter matched; it was later replaced by a different compact prefix structure.
Replication and repair: Merkle trees. Dynamo-style stores, such as Cassandra and Riak, use Merkle trees for anti-entropy repair, and systems from Git to Certificate Transparency use them for verification.
Geospatial and other indexes. Some proximity systems use probabilistic and hierarchical structures together: geohash or S2 cells for the spatial lookup, and Bloom filters to skip cells or shards that cannot contain matching items. See Geospatial Indexing.
Real uses, in depth#
Bloom filters in distributed joins. In a distributed query, joining a huge table with a small, filtered one normally means shipping data between nodes. A Bloom join, or semi-join filter, builds a Bloom filter of the join keys from the small side and sends it to the nodes holding the big side, which drop rows whose key is definitely absent before shuffling. Spark, Impala, Presto and other engines use runtime filters of this kind, sometimes cutting shuffled data by orders of magnitude.
Bitcoin's lesson about privacy. Bitcoin's BIP 37 let lightweight clients send a Bloom filter of their addresses to full nodes, which returned only matching transactions. Researchers later showed that the filters leaked which addresses belonged to the client, since a filter tuned for few false positives reveals its contents to anyone who can test many candidates. Newer protocols reversed the direction: nodes publish compact filters per block, and clients download and check them locally. The lesson: a Bloom filter is not a privacy mechanism.
Choosing a structure in a design. Ask three questions: what is the exact question (membership, frequency, cardinality, ranking, quantile, difference); what is the cost of each kind of error; and must the structures merge across servers or time windows? The answers usually point to one structure, and the sizing formulas then tell you whether it fits.
When to Use It#
- Exact answers are too large or slow: billions of items, high-rate streams, or many instances of the structure, such as per user or per page.
- The error is bounded and acceptable, or can be corrected by an exact check on the rare positive.
- You need to merge summaries across servers, partitions or time windows: sketches merge, exact sets are expensive to combine.
- You want to skip expensive work when the answer is "definitely not": disk reads, database lookups, network calls.
- Streaming analytics where data passes once and cannot be stored: counts, distinct counts, heavy hitters and percentiles in real time.
- Comparing large replicas or proving membership without moving all the data: Merkle trees.
When NOT to Use It#
- When a hash set, database index or exact count is affordable: do the arithmetic first. Millions of items usually fit in memory exactly.
- When any error is unacceptable, such as billing, legal reporting, or deciding whether a username is taken, unless the structure only gates an exact check.
- When you need to list or retrieve the items: filters and sketches store no items.
- When deletions are frequent and unverified: Bloom filters cannot delete, and counting and cuckoo filters break if you delete items that were never inserted.
- For intersections of HyperLogLogs with small overlaps: use MinHash or theta sketches instead.
- As a privacy or security boundary: filters leak their contents to anyone who can query them.
How to Implement It#
- State the question precisely, and estimate the exact solution's cost. Only continue if it is unaffordable.
- Choose the structure by question type and error tolerance, using the table above.
- Size it with the formulas, plus headroom for growth, and multiply by the number of instances.
- Use a proven library or built-in: RedisBloom, Redis HyperLogLog, Guava, Apache DataSketches, or your database's approximate functions.
- Decide how errors are handled: confirm positives with an exact lookup, accept them, or surface the error bound in the UI.
- Plan for rebuilds and windows: rebuild filters from the source of truth, rotate per-minute or per-hour sketches, and merge them for longer windows.
- Persist or reconstruct: decide whether the structure is stored, such as in Redis with persistence, or rebuilt after a restart, and what happens while it is rebuilding.
- Monitor accuracy: periodically compare against exact answers on a sample, and watch fill levels for filters.
A minimal Bloom filter in TypeScript, sized from n and p and using double hashing:
import { createHash } from "crypto";
export class BloomFilter {
private bits: Uint8Array;
readonly m: number;
readonly k: number;
constructor(expectedItems: number, falsePositiveRate: number) {
this.m = Math.ceil((-expectedItems * Math.log(falsePositiveRate)) / Math.LN2 ** 2);
this.k = Math.max(1, Math.round((this.m / expectedItems) * Math.LN2));
this.bits = new Uint8Array(Math.ceil(this.m / 8));
}
private positions(item: string): number[] {
const d = createHash("sha256").update(item).digest(); // fast hashes such as xxHash also work
const h1 = d.readUInt32BE(0), h2 = (d.readUInt32BE(4) | 1) >>> 0;
return Array.from({ length: this.k }, (_, i) => (h1 + i * h2) % this.m);
}
add(item: string): void {
for (const p of this.positions(item)) this.bits[p >> 3] |= 1 << (p & 7);
}
mightContain(item: string): boolean {
return this.positions(item).every((p) => (this.bits[p >> 3] & (1 << (p & 7))) !== 0);
}
}For 1 million items at 1%, this allocates about 1.2 MB and uses 7 positions per item. Production code would use a faster non-cryptographic hash and 64-bit arithmetic for filters with more than about 4 billion bits.
| Technology | Fits when |
|---|---|
Redis PFADD, PFCOUNT, PFMERGE | Distinct counts per key, 12 KB each, mergeable |
RedisBloom (BF.*, CF.*, CMS.*, TOPK.*, TDIGEST.*) | Bloom, cuckoo, count-min, top-k and t-digest as shared server-side structures |
Redis bitmaps (SETBIT, GETBIT) | A simple Bloom filter without modules |
Guava BloomFilter, Rust and Go Bloom libraries | In-process filters in services |
| Apache DataSketches | HLL, theta sketches for intersections, KLL quantiles, frequent items, mergeable across systems |
| Caffeine (W-TinyLFU) | In-process caches with sketch-based admission |
| BigQuery, Trino, Spark, ClickHouse, Druid approximate functions | Approximate distinct counts and quantiles in analytics SQL |
| HdrHistogram, DDSketch, Prometheus histograms | Latency percentiles in monitoring |
| RocksDB, Cassandra filter settings | Bloom or Ribbon filters per SSTable, tuned by bits per key |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Exact hash set or index | No error; can list and delete items | Memory grows with items and their size; hard to merge | The data fits, or errors are unacceptable |
| Bloom filter | Simple; about 10 bits per item at 1%; unions by OR; degrades gracefully | No delete; cannot grow without a scalable variant; k cache misses | Membership checks that skip expensive work |
| Cuckoo filter | Deletes; smaller than Bloom below about 3%; two bucket reads | Inserts fail when full; limited duplicates; delete only inserted items | Membership with deletes and low error rates |
| Quotient filter | Deletes, merges and resizes; one sequential read | More complex; slows down above about 90% load | Filters on SSD, or filters that must merge |
| XOR or Ribbon filter | Closest to the space minimum | Static: built once from a fixed set | Immutable files, such as SSTables |
| Count-min sketch | Fixed memory; mergeable; never underestimates | Error relative to the whole stream; rare items inaccurate | Frequencies of heavy items; cache admission |
| HyperLogLog | 12 KB for billions; 0.81% error; merges by max | No intersections; cannot list items | Distinct counts per key, window or segment |
| Space-Saving or Misra-Gries | Bounded error; m counters; deterministic | Only finds items above N/m; counts are estimates | Top-k and heavy hitters |
| Quantile sketch | Percentiles in kilobytes; mergeable | Choice of rank or value error matters | Latency monitoring and SLOs |
| Merkle tree | Exact; finds differences with few hashes | Must be rebuilt or maintained per write | Replica repair and verifiable logs |
Common Pitfalls#
- Using a probabilistic structure where an exact one fits: a Bloom filter for 100,000 usernames, or a HyperLogLog for a few thousand users. Do the arithmetic first.
- Undersizing a Bloom filter: inserting twice the planned items takes a 1% filter to about 16% false positives.
- Treating "probably present" as "present" when a false positive is harmful, such as telling a user a username is taken. Confirm with an exact lookup.
- Deleting from a counting or cuckoo filter items that were never inserted, which creates false negatives for other items.
- Merging sketches built with different parameters or hash seeds, which silently produces garbage. Version the parameters with the data.
- Using weak or 32-bit hashes at billions of items: 32-bit hashes collide frequently past a few hundred million items, which caps HyperLogLog accuracy and inflates filter error.
- Averaging percentiles across hosts or time windows instead of merging histograms.
- Estimating small intersections with HyperLogLog inclusion-exclusion, which can return nonsense or negative numbers.
- Relying on count-min estimates for rare items, whose counts may be dominated by collisions.
- Forgetting rebuilds: a cache-held filter lost on restart means either a costly rebuild from the source of truth or a period with no filtering, and the plan for that period must exist.
- Exposing a filter to untrusted clients, which leaks the set and invites crafted inputs that collide.
- Using count-min with at-least-once delivery without deduplication: redelivered events inflate counts, unlike HyperLogLog and Bloom filters, where re-adding an item changes nothing.
Real-World Examples#
- Google Bigtable (Fay Chang and colleagues, "Bigtable: A Distributed Storage System for Structured Data", OSDI 2006) let clients enable Bloom filters per SSTable, so most lookups for absent rows or columns avoid disk reads. HBase, Cassandra, LevelDB and RocksDB follow the same design, and RocksDB added Ribbon filters as a smaller alternative.
- Akamai used a Bloom filter to cache web objects only on their second request, avoiding the one-hit wonders that made up a large share of objects, as described by Maggs and Sitaraman in 2015.
- Redis added HyperLogLog in 2014, with
PFADD,PFCOUNTandPFMERGEusing 12 KB per key at 0.81% standard error, named in honour of Philippe Flajolet. - Reddit described in a 2017 engineering post how it counts post views with HyperLogLog, using a stream of view events and Redis HyperLogLogs, with counts persisted to Cassandra, because exact per-post sets of viewers were too large.
- Google BigQuery and Elasticsearch implement approximate distinct counts with HyperLogLog++, and BigQuery exposes the sketches themselves so they can be stored and merged later.
- Datadog uses DDSketch for distribution metrics, so percentiles can be computed across any combination of hosts and tags by merging sketches.
- Caffeine, the Java caching library, uses W-TinyLFU with a count-min sketch of 4-bit counters for admission, and its hit rates are close to optimal on many published traces.
- Amazon Dynamo, Cassandra and Riak use Merkle trees for anti-entropy repair between replicas.
- Bitcoin blocks commit to their transactions with a Merkle root, so lightweight clients verify a transaction with a log-sized proof, and Certificate Transparency logs prove inclusion of TLS certificates the same way.
- Redis sorted sets, LevelDB and RocksDB memtables use skip lists for ordered in-memory data.
In the Interview#
Deep Dive: Deduplicating 10 billion URLs in a crawlerShow
Requirements. A crawler discovers about 50,000 new URLs per second across 16 crawler nodes and must not fetch a URL it has already fetched this crawl cycle. The total over a cycle is up to 10 billion URLs. It must also avoid storing pages whose content duplicates a page already stored.
Step 1: canonicalise first. Most duplicate URLs are trivially different strings: different case in the host name, default ports, trailing slashes, utm_ tracking parameters, session IDs, or parameters in a different order. Normalise each URL before any check, otherwise the best filter in the world still lets duplicates through. Hash the canonical URL with a 64-bit or 128-bit hash.
Step 2: shard the filter by URL hash. Route each URL to the crawler node that owns its hash range, the same node that will fetch it, which also keeps per-host politeness in one place if the routing uses the host name. Each node holds a Bloom filter for its share: 10 billion divided by 16 is 625 million URLs, at 0.1% that is 14.4 bits each, about 1.1 GB per node, with 10 hash positions per lookup. Blocked Bloom filters keep each lookup to one cache miss, so 3,000 lookups per second per node are trivial.
Step 3: decide what the filter means. The filter answers "was this URL seen this cycle?". A false positive skips a new URL: 0.1% of 10 billion is 10 million pages, which is acceptable for a general web crawl, and important URLs, such as those in sitemaps or seed lists, can bypass the filter and use an exact check against the URL database.
Step 4: survive failures. The filter lives in memory, so a node crash loses it. Options: snapshot the bit array to object storage every few minutes, which at 1.1 GB takes seconds, and replay URLs discovered since the snapshot from the frontier queue in Kafka; or rebuild from the URL store, which for 625 million URLs takes minutes of sequential reading. During recovery, the node can fall back to exact checks against the URL database at a lower crawl rate.
Step 5: handle recrawls. Pages must be recrawled on a schedule, so "seen" cannot mean "seen forever". Keep per-URL metadata, last fetch time and change frequency, in a database, which the scheduler uses to decide recrawls. The Bloom filter covers only the current cycle and is rebuilt or rotated per cycle, for example by keeping this week's and last week's filters and dropping the older one each week.
Step 6: deduplicate content. Exact duplicates are caught by hashing the page body and checking a second filter, or an exact table, of content hashes. Near-duplicates, pages that differ only in a timestamp, an ad or a counter, need a similarity hash. Gurmeet Singh Manku, Arvind Jain and Anish Das Sarma ("Detecting Near-Duplicates for Web Crawling", WWW 2007) described Google's use of Charikar's SimHash: a 64-bit fingerprint where similar documents have fingerprints differing in few bits, with documents within a Hamming distance of 3 treated as near-duplicates, across a corpus of about 8 billion pages. Finding fingerprints within distance 3 is done with several sorted tables of permuted fingerprints, so each check is a few lookups.
Why not Redis? A shared RedisBloom filter is fine at small scale and simplifies the crawler nodes, but every check becomes a network round trip, about 0.5 ms, and a single Redis instance holding 18 GB is a hot spot and a single point of failure. Co-locating each filter shard with the node that owns those URLs removes both problems. See Design a Web Crawler.
Deep Dive: HyperLogLog error, memory and hashingShow
Error scales with the square root of memory. The standard error is 1.04 divided by the square root of the number of registers m. Quadrupling memory halves the error:
| Registers m | Precision bits b | Memory at 6 bits per register | Standard error |
|---|---|---|---|
| 256 | 8 | 192 bytes | 6.5% |
| 1,024 | 10 | 768 bytes | 3.25% |
| 4,096 | 12 | 3 KB | 1.6% |
| 16,384 | 14 | 12 KB | 0.81% |
| 65,536 | 16 | 48 KB | 0.41% |
The error is a standard error: about 68% of estimates fall within one standard error, 95% within two, and 99.7% within three. A 12 KB sketch is within 2.4% essentially always. The error does not grow with the cardinality: a count of a billion has the same relative error as a count of a million.
Why 6-bit registers suffice. A register stores the position of the first 1 bit in the part of the hash not used to choose the register. With a 64-bit hash and 14 bits of register index, the remaining 50 bits can produce positions up to 51, which fits in 6 bits. A run of 50 zeros has probability 2 to the power minus 50, so registers never overflow in practice.
Why the hash width matters. HyperLogLog counts distinct hash values, not distinct items. With a 32-bit hash, distinct items start colliding noticeably as the count approaches a few hundred million, and the estimate flattens below the truth, which is why the original paper needed a large-range correction. HyperLogLog++ switched to a 64-bit hash, for which collisions are negligible below many billions. Use a good 64-bit hash, such as MurmurHash3 or xxHash, and the same hash everywhere sketches will be merged.
Merging keeps the error. The merged sketch is identical to the sketch you would build from the combined stream, so a weekly count merged from 7 daily sketches has the same 0.81% error as each daily one. This is the property that makes HyperLogLog so useful in pipelines. In contrast, the sum of daily unique counts overstates weekly uniques, since a user active on 5 days counts 5 times: only merging gives the correct union.
Precision is a per-sketch decision. Sketches with different precisions can be merged by first reducing the more precise one to the coarser precision, which some libraries do automatically, but the result has the coarser error. Choose one precision per metric and keep it.
Sparse mode for the long tail. Most keys in a per-page or per-user metric have small counts. Storing a dense 12 KB array for a page with 20 visitors would waste nearly all of it, so implementations start with a sparse list of (register, value) pairs, and switch to the dense array only when the sparse form would be larger. Redis does this automatically; with millions of mostly small keys, it is the difference between gigabytes and hundreds of gigabytes.
Deep Dive: Mergeable sketches in distributed pipelinesShow
Mergeability as a design property. Pankaj Agarwal, Graham Cormode, Zengfeng Huang, Jeff Phillips, Zhewei Wei and Ke Yi ("Mergeable Summaries", PODS 2012) formalised which summaries can be merged with no loss of accuracy guarantees: count-min sketches, HyperLogLogs, Misra-Gries and Space-Saving summaries, and some quantile summaries. Mergeability means the summary of the union of two data sets can be computed from the two summaries alone. It is what lets a summary be built in parallel and in pieces, and combined in any order.
A typical metrics pipeline.
Why store sketches rather than results. If the store keeps only "p99 per host per minute", there is no correct way to compute the p99 for a service over an hour. If it keeps the sketches, any query merges the relevant ones and computes the answer with the sketch's guarantee. The same applies to distinct counts: storing HyperLogLogs per segment and day lets an analyst ask for "unique users in campaign A or B over the last 30 days" without re-reading raw events.
Order does not matter. Merging is commutative and associative, so sketches can be combined in any order and grouping, by host first or by region first, in a tree of aggregators or a single one, with the same result. Late data is easy: a sketch from a host that reports 2 minutes late is simply merged into the window it belongs to.
Duplicates and delivery semantics. Bloom filters and HyperLogLogs are idempotent: adding the same item twice changes nothing, and merging the same sketch twice changes nothing, because OR and max are idempotent. So at-least-once delivery, with its occasional duplicates, is harmless for them. Count-min sketches, histograms and quantile sketches are additive: a duplicated event or a sketch merged twice is counted twice. Those pipelines need deduplication by event or batch ID, or exactly-once processing. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
Compatibility rules. Two sketches merge only if they use the same parameters: the same width, depth and hash seeds for count-min, the same precision and hash function for HyperLogLog, the same γ for DDSketch, and the same size and hash functions for Bloom filters. Store a version or parameter set with every serialised sketch, and refuse merges that do not match. Libraries such as Apache DataSketches define stable binary formats so that sketches built in Java can be merged in C++ or Python, and in query engines.
Adversarial inputs. If attackers can choose the items, and the hash functions are known, they can craft inputs that collide: forcing false positives in a filter, inflating a competitor's count-min estimate, or skewing a HyperLogLog. Use keyed hashes, such as SipHash with a secret seed, for structures fed by untrusted input, and never expose the structure itself.
Key Takeaways#
- Probabilistic data structures trade a small, tunable error for orders of magnitude less memory, and they are fast and usually mergeable.
- Bloom filters answer "definitely not" or "probably yes" with about 1.44 × log2(1/p) bits per item, 9.6 bits at 1%. Size them for peak load, because overfilling raises the error steeply.
- Use cuckoo or quotient filters when you need deletion, and XOR or Ribbon filters for static sets such as SSTables. Rebuilding filters from the source of truth is often simpler than deleting.
- Count-min sketches estimate frequencies, never undercount, and are accurate for heavy hitters. Their error is relative to the whole stream.
- HyperLogLog counts distinct items in 12 KB with 0.81% error at any scale, and unions merge exactly by register maxima. Intersections need MinHash or theta sketches.
- Top-k uses Space-Saving, Misra-Gries or count-min plus a heap. Partition by item ID so that merging per-partition results is exact.
- Quantile sketches give percentiles in kilobytes. Merge them, never average percentiles, and prefer relative-value-error sketches such as DDSketch for latency.
- Merkle trees exactly locate differences between replicas with a few hash comparisons. Skip lists give simple, concurrent sorted indexes.
- Decide what a false positive means before choosing a structure, and confirm positives exactly when an error would harm users.
- Always check the cost of the exact solution first: a probabilistic structure where a hash set would fit is over-engineering.