Probabilistic data structures answer questions about huge data sets in a tiny, fixed amount of memory by accepting a small, tunable error. A Bloom filter answers "have I seen this?" with no false negatives, a Count-Min Sketch answers "how often?" without ever undercounting, and HyperLogLog answers "how many distinct?" within about 1% using 12 KB. They sit inside databases, caches, CDNs and analytics pipelines everywhere.
Think of it like
A wall of light switches
Each guest who enters a party flips on the same few switches, chosen by their name. To check whether someone came, look at their switches: if any is off, they definitely never came. If all are on, they probably did, though other guests might have turned those switches on between them. You never need the guest list itself, only the wall.
Why trade accuracy for memory
Exact set of 100M URLs
~8 GB
about 80 bytes per URL, before hash-table overhead
Bloom filter, 1% false positives
~120 MB
9.6 bits per item, whatever the item size
Distinct count of billions
12 KB
Redis HyperLogLog, about 0.81% error
Frequency of every item
~54 KB
Count-Min with ε = 0.1%, δ = 1%
The exact answers need memory proportional to the data. These sketches need memory proportional only to the accuracy you ask for. When the question is a gatekeeper ("is it worth a disk read?") or a dashboard number ("about 3.2M unique visitors"), that trade is almost always worth it.
Bloom filters
How it works
- 1
Start empty
Allocate a bit array of
mbits, all 0, and choosekindependent hash functions that map an item to positions in[0, m). - 2
Add
Hash the item with all
kfunctions and set thosekbits to 1. - 3
Query
Hash the item and check the same
kbits. - 4
Any bit is 0
The item was definitely never added. Adding it would have set that bit.
- 5
All bits are 1
The item is probably present. The bits might all have been set by other items: a false positive.
False-positive rate
Sizing example
| Target false-positive rate | Bits per item | Optimal k | Memory for 10M items |
|---|---|---|---|
| 10% | 4.79 | 3 | ~6.0 MB |
| 1% | 9.59 | 7 | ~12.0 MB |
| 0.1% | 14.38 | 10 | ~18.0 MB |
| 0.01% | 19.17 | 13 | ~24.0 MB |
Deletions: counting Bloom filters
You can't delete from a plain Bloom filter: clearing an item's bits might clear bits shared with other items and create false negatives. A counting Bloom filter replaces each bit with a small counter (4 bits is typical): add increments, remove decrements, and a position counts as set while its counter is above zero. It costs about 4× the memory, and you must only remove items that were actually added.
Cuckoo filters
A cuckoo filter (Fan et al., 2014) stores a short fingerprint of each item in one of two candidate buckets of a cuckoo hash table, where the second bucket is derived from the first and the fingerprint (i2 = i1 XOR hash(fp)). It supports deletion, looks at only two buckets per query, and uses less space than a Bloom filter for false-positive rates below roughly 3%. Inserts can fail once the table is very full (about 95% with 4-slot buckets).
Bloom filter
- Smallest and simplest
- No deletions
- k memory probes per query
- Union of two filters is a bitwise OR
Counting Bloom filter
- Deletions supported
- About 4× the memory of a Bloom filter
- Counters can overflow in rare cases
- Removing a never-added item corrupts it
Cuckoo filter
- Deletions supported
- Better space than Bloom below ~3% false positives
- Two bucket lookups per query
- Inserts can fail when nearly full
A Bloom filter in front of a database
A classic production use is stopping cache penetration: requests for keys that don't exist miss the cache every time and hammer the database. A Bloom filter of all valid keys rejects them in memory. The same idea makes LSM-tree storage engines fast: each SSTable has a Bloom filter, so a point lookup skips files that can't contain the key.
Count-Min Sketch
A Count-Min Sketch estimates how many times each item appeared in a stream. It is a d × w grid of counters with one hash function per row. Adding an item increments one counter in each row; the estimate is the minimum of those d counters. Collisions only ever add to a counter, so every row overestimates, and the minimum is the least polluted.
Example: ε = 0.001 and δ = 0.01 give w = 2,719 and d = 5, so 13,595 counters (about 54 KB with 4-byte counters), no matter how many distinct items the stream contains. To find heavy hitters (trending hashtags, top IPs during a DDoS), pair the sketch with a min-heap of the top-k candidates. The conservative update variant, which only raises counters that are below the new estimate, reduces overcounting further.
HyperLogLog
HyperLogLog (Flajolet et al., 2007) counts distinct items. Intuition: hash every item to a uniform random bit string. A hash that starts with k zeros appears with probability 2^−k, so if the longest run of leading zeros you've seen is ρ, you've probably seen around 2^ρ distinct items. One such estimate is very noisy, so HLL splits the stream into m buckets using the first bits of the hash, tracks the maximum leading-zero run per bucket, and combines them with a bias-corrected harmonic mean.
| Registers (m) | Memory at 6 bits each | Standard error |
|---|---|---|
| 2¹⁰ = 1,024 | 768 B | 3.25% |
| 2¹² = 4,096 | 3 KB | 1.63% |
| 2¹⁴ = 16,384 | 12 KB | 0.81% (Redis) |
| 2¹⁶ = 65,536 | 48 KB | 0.41% |
# 12 KB per key at most, ~0.81% standard error
PFADD visitors:2026-11-03 user:17 user:42 user:17
PFCOUNT visitors:2026-11-03 # -> 2
PFMERGE visitors:week visitors:2026-11-01 visitors:2026-11-02 visitors:2026-11-03
PFCOUNT visitors:week
# Bloom filters ship with Redis Stack / Redis 8 (RedisBloom)
BF.RESERVE seen-urls 0.01 10000000 # 1% error, sized for 10M items
BF.ADD seen-urls https://example.com/a
BF.EXISTS seen-urls https://example.com/b # -> 0: definitely not seenWhere they're used
| Use case | Structure | Why it helps |
|---|---|---|
| LSM-tree point lookups (Cassandra, RocksDB, HBase, LevelDB) | Bloom filter per SSTable | Skip disk reads for files that can't contain the key |
| Cache penetration protection | Bloom filter of valid keys | Reject nonexistent keys before the cache and database |
| CDN one-hit wonders (Akamai) | Bloom filter of recently requested URLs | Only cache an object on its second request, saving disk for popular content |
| Web crawler "already seen?" | Bloom filter | Billions of URLs in memory; see Design a Web Crawler |
Unique visitors, COUNT(DISTINCT) at scale | HyperLogLog | Fixed memory, mergeable across shards and days (BigQuery APPROX_COUNT_DISTINCT, Trino approx_distinct) |
| Heavy hitters, trending topics, DDoS sources | Count-Min Sketch + heap | Streaming frequencies in kilobytes |
| Distributed joins | Bloom filter of join keys | Filter rows before shuffling them across the network |
Implementation
Sized from the expected item count and target false-positive rate, using double hashing to derive k positions from one SHA-256 digest.
import hashlib
import math
class BloomFilter:
def __init__(self, expected_items: int, fp_rate: float):
# m = -n ln p / (ln 2)^2 bits; k = (m / n) ln 2 hash functions
self.m = math.ceil(-expected_items * math.log(fp_rate) / (math.log(2) ** 2))
self.k = max(1, round(self.m / expected_items * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item: str):
digest = hashlib.sha256(item.encode()).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1 # odd, so steps never collapse
for i in range(self.k):
yield (h1 + i * h2) % self.m # Kirsch-Mitzenmacher double hashing
def add(self, item: str) -> None:
for pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def might_contain(self, item: str) -> bool:
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
bf = BloomFilter(expected_items=1_000_000, fp_rate=0.01) # ~1.2 MB, k = 7
bf.add("alice@example.com")
print(bf.might_contain("alice@example.com")) # True (never a false negative)
print(bf.might_contain("bob@example.com")) # False, except ~1% of the timeKey takeaways
- Bloom filters answer membership with no false negatives; size them with m = −n ln p / (ln 2)² and k = (m/n) ln 2.
- About 9.6 bits per item gives 1% false positives; every extra 4.8 bits per item is another 10× improvement.
- Plain Bloom filters can't delete; counting Bloom filters and cuckoo filters can.
- Count-Min Sketch estimates frequencies and only ever overestimates, by at most εN with probability 1 − δ.
- HyperLogLog counts distinct items with about 1.04/√m error; Redis uses 12 KB for 0.81%, and HLLs merge by register-wise max.
Common pitfalls
- Inserting far more items than the filter was sized for, which silently inflates the false-positive rate.
- Deleting from a plain Bloom filter by clearing bits, which creates false negatives.
- Treating a Bloom filter "maybe" as a definite yes (for example, rejecting a username as taken without checking the database).
- Using weak or correlated hash functions, which raises the real error well above the formula.
- Forgetting to add new keys to a cache-penetration filter, so freshly created records are rejected.
Interview tips
- State the error direction for each structure: Bloom (false positives only), Count-Min (overestimates only), HLL (symmetric relative error).
- Do a quick sizing calculation out loud; it shows you understand the formulas, not just the names.
- Mention concrete systems: Bloom filters in Cassandra/RocksDB SSTables, HyperLogLog in Redis and BigQuery.
Real-world applications
- Storage engines skipping SSTables that can't contain a key.
- Caches and APIs blocking lookups for nonexistent keys.
- Analytics: unique visitors, distinct users per feature, approximate COUNT DISTINCT.
- Stream processing: heavy hitters, trending topics, network anomaly detection.
Test yourself
A Bloom filter reports that an item is "possibly present". What do you know?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.