Bloom Filters and Probabilistic Data Structures
Tiny, fast structures that answer 'have I seen this?' or 'how many?' approximately, trading a small, known error for huge memory savings.
What is it?
Some questions are expensive to answer exactly at scale. "Is this username taken?", "How many unique visitors did we have today?", "Which search terms are trending right now?" An exact answer means storing every item, which can take gigabytes.
Probabilistic data structures give an answer that is almost right, with an error rate you choose up front, using a tiny fraction of the memory. The main ones:
- Bloom filter: "Is X in the set?" Answers definitely not or probably yes. It never gives a false negative, but can give a false positive. - Counting Bloom filter: a Bloom filter that also supports deletion. - HyperLogLog (HLL): "How many distinct items have I seen?" Counts billions of unique values in about 12 KB with roughly 1% error. - Count-Min Sketch: "How often has X appeared?" Gives a frequency estimate that can be too high but never too low.
The key idea for a senior engineer: these structures move a cost (disk reads, network calls, memory) from "always" to "rarely", and the error is one-sided and bounded, so you can design around it.
Explain like I'm 10
A Bloom filter is like a bouncer with a short list of features instead of photos: 'tall, red hat, glasses'. If you don't match, you definitely aren't on the list. If you do match, you're probably on it, but someone else in a red hat and glasses could slip through, so the bouncer double-checks the real list only for matches.
Examples
A minimal Bloom filter in TypeScript
class BloomFilter {
private bits: Uint8Array;
constructor(private sizeInBits: number, private hashCount: number) {
this.bits = new Uint8Array(Math.ceil(sizeInBits / 8));
}
// Double hashing: derive k positions from two base hashes (Kirsch-Mitzenmacher).
private positions(item: string): number[] {
const hashA = fnv1a(item);
const hashB = fnv1a(item + "#salt") | 1; // odd, so steps cover the table
const result: number[] = [];
for (let i = 0; i < this.hashCount; i++) {
result.push(Math.abs((hashA + i * hashB) % this.sizeInBits));
}
return result;
}
add(item: string): void {
for (const position of this.positions(item)) {
this.bits[position >> 3] |= 1 << (position & 7);
}
}
mightContain(item: string): boolean {
return this.positions(item).every(
(position) => (this.bits[position >> 3] & (1 << (position & 7))) !== 0,
);
}
}
function fnv1a(text: string): number {
let hash = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
hash ^= text.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}Adding sets k bits. Checking reads the same k bits: if any is 0 the item was never added; if all are 1 it probably was.
Sizing a Bloom filter
// n = expected items, p = target false-positive rate
function bloomSize(n: number, p: number) {
const bits = Math.ceil((-n * Math.log(p)) / (Math.LN2 * Math.LN2));
const hashes = Math.round((bits / n) * Math.LN2);
return { bits, megabytes: bits / 8 / 1024 / 1024, hashes };
}
bloomSize(100_000_000, 0.01);
// => ~958.5 million bits (~114 MB), 7 hash functions
// About 9.6 bits per item for 1%, ~14.4 bits for 0.1%.Each 10x drop in false-positive rate costs about 4.8 more bits per item. Storing 100M 32-byte keys exactly would take over 3 GB.
HyperLogLog and Count-Min Sketch in Redis
# Unique visitors per day: ~12 KB per key, ~0.81% standard error
PFADD visitors:2026-11-24 user:42 user:99 user:42
PFCOUNT visitors:2026-11-24 # => 2
PFMERGE visitors:week visitors:2026-11-24 visitors:2026-11-23
# Count-Min Sketch (RedisBloom module): top search terms
CMS.INITBYPROB searches 0.001 0.01 # error 0.1% of total, 99% confidence
CMS.INCRBY searches "pizza" 1
CMS.QUERY searches "pizza"HLL sketches merge losslessly, so you can count per day and union into weeks without re-reading raw data.
How it works
Bloom filter. A bit array of size m and k hash functions. To add an item, hash it k times and set those k bits. To query, check the same k bits. A 0 anywhere proves absence. All 1s could be a coincidence: other items may have set those bits. After inserting n items:
- False-positive rate: p ≈ (1 − e^(−kn/m))^k - Best number of hashes: k = (m/n) · ln 2 - Bits needed for a target p: m = −n · ln p / (ln 2)², about 1.44 · log2(1/p) bits per item.
You can't delete from a plain Bloom filter: clearing a bit might erase another item that shares it. If you insert more than n items, p climbs fast, so size for peak, or use a scalable Bloom filter that adds new layers as it fills.
Counting Bloom filter. Replace each bit with a small counter (often 4 bits). Add increments k counters; delete decrements them. It costs ~4x the memory and counters can overflow. Deleting an item that was never added corrupts the filter, so only delete what you know you inserted. Cuckoo filters are a common alternative that support deletion with less overhead.
HyperLogLog. Hash each item to a uniform bit string. A run of r leading zeros is roughly a 1-in-2^r event, so the longest run you've seen hints at how many distinct items exist. One estimate is noisy, so HLL splits the hash into m registers (using the first bits to pick a register), keeps the max run per register, and combines them with a harmonic mean. Standard error is about 1.04 / √m. Redis uses 16,384 registers (~12 KB), giving ~0.81%. Two HLLs merge by taking the max of each register, which makes them ideal for distributed counting.
Count-Min Sketch. A grid of d rows × w columns of counters, one hash function per row. To increment X, add 1 to one counter in each row. To estimate X, take the minimum across rows. Collisions only add, so the estimate is never too low. With w = ⌈e/ε⌉ and d = ⌈ln(1/δ)⌉, the overestimate is at most ε × (total count) with probability 1 − δ. Pair it with a small heap to track top-k heavy hitters.
Bloom filter, m = 16 bits, k = 3
add("cat") -> h1=2, h2=7, h3=11
add("dog") -> h1=4, h2=7, h3=14
index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bits: 0 0 1 0 1 0 0 1 0 0 0 1 0 0 1 0
query("cow") -> 2, 4, 14 all 1 -> "probably yes" (false positive!)
query("eel") -> 2, 5, 11 bit 5 = 0 -> "definitely no"Why does it exist?
At scale, the expensive part is usually not computing but looking: a disk seek, a network call, a full scan. If most lookups are for things that don't exist, a small in-memory filter that rules them out saves almost all of that work. Likewise, exact distinct counts and frequency tables grow with the data, while sketches stay a fixed size and can be merged across machines.
When to use it
- LSM-tree databases (Cassandra, RocksDB, HBase, LevelDB) keep a Bloom filter per SSTable so reads skip files that can't hold the key. - CDNs and caches: Akamai described using a Bloom filter to avoid caching "one-hit wonders", only storing an object on its second request. - Pre-checks before expensive lookups: username availability, "already crawled this URL?", "has this user seen this recommendation?", malicious URL lists. - Analytics: HLL for unique users / IPs / devices per time bucket; Count-Min Sketch for heavy hitters, trending topics, or per-key rate estimates in network devices. - Distributed joins: send a Bloom filter of one side's keys to filter the other side before shuffling.
When not to use it
- When you need an exact answer (billing, balances, permissions). Use a real set, a database index, or an exact count. - When the set is small. A hash set of a few thousand items is simple and exact. - When false positives are dangerous and there's no cheap exact check behind the filter. A Bloom filter is a fast "no", not a proof of "yes". - When you must list or delete members. Bloom filters and HLL can't enumerate what's inside. Use a counting/cuckoo filter or the real data.
Common mistakes
Treating a Bloom filter 'yes' as authoritative instead of confirming against the real store.
Sizing for today's item count, then inserting 5x more. The false-positive rate rises sharply once the filter is overfilled.
Deleting from a plain Bloom filter by clearing bits, which creates false negatives for other items.
Using correlated or weak hash functions, which makes the real error rate much worse than the formula predicts.
Expecting Count-Min Sketch to be accurate for rare items. Its error is relative to the total count, so low-frequency estimates are mostly noise.
Practice exercises
- Easy:
Explain why a Bloom filter can return false positives but never false negatives.
- Medium:
You expect 50 million keys and want a 0.1% false-positive rate. Compute the number of bits and hash functions, and the memory in MB.
- Hard:
Design daily, weekly and monthly unique-visitor counts for 500M events/day across 200 servers without storing raw user IDs centrally. Explain how merging works and what the error is.
Interview questions
What does a Bloom filter guarantee?
No false negatives: if it says an item is absent, it is absent. A 'present' answer may be a false positive with a tunable probability.
How do you choose the size and number of hash functions?
For n items and target rate p: m = −n·ln p / (ln 2)² bits and k = (m/n)·ln 2 hashes. That is about 9.6 bits per item for 1% and 7 hashes.
Why can't you delete from a standard Bloom filter?
Bits are shared between items. Clearing one item's bits can clear bits another item relies on, creating false negatives. Use a counting Bloom filter or a cuckoo filter if you need deletes.
How do LSM-tree databases use Bloom filters?
Each immutable SSTable has a filter over its keys. A point read checks filters first and only reads SSTables that might contain the key, cutting disk I/O for missing keys dramatically.
How does HyperLogLog estimate cardinality?
It hashes items, uses some bits to choose a register, and records the longest run of leading zeros per register. Long runs are rare, so they indicate many distinct items. A harmonic mean across registers gives the estimate, with error about 1.04/√m.
Why is HyperLogLog good for distributed systems?
Sketches are small and fixed-size, and two sketches merge by taking the per-register max. Each node counts locally; you union results without double counting and without moving raw data.
What does a Count-Min Sketch overestimate, and why?
Frequencies. Hash collisions add other items' counts into a cell, never subtract, so each row's counter is at least the true count. Taking the minimum across rows limits the overestimate to about ε times the total.
Your Bloom filter's false-positive rate in production is 8% instead of the designed 1%. What happened?
Most likely it is overfilled (more items than it was sized for) or the hash functions are poor or correlated. Check the actual insert count against n and the fill ratio of set bits; resize or move to a scalable filter.
How would you find the top 100 trending hashtags in a high-volume stream with limited memory?
Use a Count-Min Sketch per time window for frequency estimates plus a min-heap of size 100 for current candidates. Update the heap when an item's estimate beats the smallest. Rotate or decay windows for 'trending'. Accept small overestimates for popular items.
When would you pick a cuckoo filter over a Bloom filter?
When you need deletion, or a very low false-positive rate where cuckoo filters can use less space. Bloom filters remain simpler, insert never fails, and they handle unions with a bitwise OR.