Bloom Filters
A tiny probabilistic structure that answers 'is this maybe present?' fast, so you can skip expensive lookups.
Bloom filters in 30 seconds
- A Bloom filter is a bit array plus a few hash functions that answers 'have I probably seen this?' very cheaply.
- Two answers only: definitely no or maybe yes — false positives are possible, false negatives never.
- The payoff: a 'definitely no' lets you skip an expensive disk read or network call entirely.
- A 'maybe yes' still needs the real lookup to confirm — the filter just filters out the certain misses.
- No deletion from a basic filter; use a counting variant (counters not bits) if you must remove items.
- Shows up in LSM-tree databases, caches, web crawlers, and dedup — anywhere membership testing must be cheap.
The nightclub stamp on your hand
Picture a huge nightclub with a strict re-entry rule. Instead of keeping a guest list of thousands of names at the door, the bouncer stamps a few different invisible-ink marks on your hand when you first enter. On the way back in, he shines a UV light: if any of your expected marks is missing, you were definitely never inside — turned away instantly. If all the marks glow, you probably came in before, so he waves you through. Once in a blue moon a stranger's hand happens to carry the same smudges and slips in — a rare false alarm — but the bouncer never wrongly rejects someone who really was inside.
That's a Bloom filter exactly: a handful of 'stamps' (hash functions) marking a shared surface (a bit array). 'A mark is missing' is a rock-solid no; 'all marks present' is only a probably. It trades a sliver of accuracy for the ability to answer in a flash without storing the whole guest list.
The problem it solves
Often the expensive thing is discovering that something isn't there. Checking whether a key exists in a huge on-disk store, or whether a URL has been crawled before, can mean a slow lookup that comes back empty. A Bloom filter answers one question extremely cheaply: 'have I probably seen this before?' It can say definitely no or maybe yes — and that 'definitely no' lets you skip the expensive check entirely.
The gap a hash set can't fill
The obvious tool for 'have I seen this?' is a hash set — and for small collections, that's the right answer. But a hash set must store every item it has seen. Track a billion crawled URLs and you're holding a billion strings in memory, which is gigabytes. A Bloom filter answers the same membership question in a fixed, tiny amount of memory — often a few bits per item — no matter how long the items are, because it never stores the items themselves, only the marks they leave. You give up exact answers; you gain the ability to fit the check in RAM at all.
| Exact set (hash set) | Bloom filter | |
|---|---|---|
| Memory | Grows with item count and size | Fixed, tiny (a few bits per item) |
| Answers | Always exact | 'Definitely no' or 'maybe yes' |
| False positives | Never | Yes, tunable (e.g. 1%) |
| False negatives | Never | Never |
| Deletion | Easy | Not in the basic version |
The core idea, plainly
A Bloom filter is a bit array plus a few hash functions. To add an item, you hash it several ways and set the bits at those positions to 1. To test an item, you hash it the same ways and check those bits: if any is 0, the item was definitely never added; if all are 1, it was probably added. It can produce false positives (saying 'maybe' when the answer is no) but never false negatives.
class BloomFilter:
def __init__(self, size, k):
self.bits = [0] * size # the bit array
self.size, self.k = size, k # k = number of hash functions
def add(self, item):
for i in range(self.k):
self.bits[hash_i(item, i) % self.size] = 1 # set k bits
def maybe_contains(self, item):
for i in range(self.k):
if self.bits[hash_i(item, i) % self.size] == 0:
return False # any 0 bit => DEFINITELY absent
return True # all 1s => MAYBE presentWhy 'maybe' happens — the shared-bit collision
The false positive isn't a bug; it's the price of sharing. Because the array is small and many items hash into it, two different items can set overlapping bits. So an item you never added might find all its bits already turned on — set by other items that collectively covered the same positions. The filter can't tell 'these bits were set for you' from 'these bits happen to all be on', so it honestly says 'maybe'. Crucially, the reverse can't happen: if you did add an item, its bits are definitely on, so the filter can never wrongly say 'no'.
bf = BloomFilter(size=10, k=2)
bf.add("cat") # say this sets bits 2 and 7
bf.add("dog") # say this sets bits 4 and 2
# bits now on: {2, 4, 7}
bf.maybe_contains("fox") # suppose 'fox' hashes to bits 4 and 7
# -> both 4 and 7 are already on (set by dog and cat)
# -> returns True ("maybe") even though 'fox' was NEVER added. FALSE POSITIVE.
bf.maybe_contains("owl") # suppose 'owl' hashes to bits 3 and 7
# -> bit 3 is OFF -> returns False -> DEFINITELY absent. Always trustworthy.Why the asymmetry is the whole point
The 'no false negatives' guarantee is what makes it useful. If the filter says an item is absent, you can trust it and skip the real lookup — saving a disk read or network call. If it says 'maybe present', you do the real lookup to confirm. So a Bloom filter never makes you miss real data; at worst it occasionally makes you do a lookup that turns out empty. You tune the size and number of hashes to keep that false-positive rate low.
def read(key):
if not filter.maybe_contains(key):
return None # DEFINITELY absent -> skip the disk read
# 'maybe present' -> we must confirm with the real lookup,
# which occasionally comes back empty (a false positive).
return disk.get(key)
def write(key, value):
disk.put(key, value)
filter.add(key) # keep the filter in sync on every writeTuning it: size, hashes, and the error rate
The false-positive rate isn't fixed — you dial it in with two knobs. Size (m): a bigger bit array means fewer collisions, so fewer false positives, at the cost of more memory. Number of hashes (k): too few and items barely spread out; too many and you flood the array with 1s, which increases collisions. There's a sweet spot for k given your array size and how many items you expect. The good news: you usually just tell a library 'I'll store ~n items and want a ~1% error rate' and it computes m and k for you.
import math
def optimal_params(n, p):
# m = number of bits, k = number of hash functions
m = math.ceil(-(n * math.log(p)) / (math.log(2) ** 2))
k = max(1, round((m / n) * math.log(2)))
return m, k
m, k = optimal_params(n=1_000_000, p=0.01) # 1M items, 1% false positives
print(m, "bits", "~=", m // 8 // 1024, "KB") # ~1.2 MB for a MILLION items
print(k, "hash functions") # about 7
# A million-item exact set would cost tens of MB; the filter fits in ~1 MB.Where they show up
- Databases (LSM trees) — skip reading an on-disk file that definitely doesn't contain a key.
- Caches — avoid a slow backend lookup for a key that was never stored.
- Web crawlers — quickly check 'have we already seen this URL?' without storing every URL.
- CDNs and dedup — cheaply test membership in a massive set without holding it all in memory.
The LSM-tree case is the classic one. A write-optimized store (Cassandra, RocksDB, LevelDB) keeps data in many sorted files on disk. Without help, a read for a missing key would have to peek into every file to be sure. Each file carries its own little Bloom filter, so the engine asks the filter first and skips the files that definitely can't hold the key — turning a read that touches many files into one that usually touches at most a few.
The gap a basic filter can't fill: deletion
class CountingBloomFilter:
def __init__(self, size, k):
self.counts = [0] * size # small counters, not single bits
self.size, self.k = size, k
def add(self, item):
for i in range(self.k):
self.counts[hash_i(item, i) % self.size] += 1 # bump
def remove(self, item):
for i in range(self.k):
self.counts[hash_i(item, i) % self.size] -= 1 # now safe to undo
def maybe_contains(self, item):
return all(self.counts[hash_i(item, i) % self.size] > 0
for i in range(self.k))
# Removing decrements instead of blindly clearing, so one item's removal
# can't knock out a bit another item still needs. Cost: ~4x the memory.Choosing: when a Bloom filter fits
| You need... | Use | Why |
|---|---|---|
| Exact membership, small set | A hash set | Perfect answers, memory isn't a concern |
| Cheap 'definitely absent' at huge scale | Bloom filter | Tiny fixed memory; false positives are acceptable |
| Membership and deletion at scale | Counting Bloom filter | Supports remove() at ~4x the space |
| Approximate counts, not just membership | Count-Min sketch / HyperLogLog | Different sketches for frequency and cardinality |
A Bloom filter is a small idea with outsized reach: it's the go-to pattern for trading a sliver of accuracy for a huge saving on expensive work, and it quietly speeds up databases, caches, and crawlers you use every day.
Why it matters
- The 'definitely no' answer removes the single most wasteful operation there is — a lookup that comes back empty.
- It does this in tiny, fixed memory, so it scales to billions of items without holding them all.
- It's a clean example of probabilistic thinking: accept bounded error to win order-of-magnitude speed.
If ignored
- Every absent-key request pays full price for a disk read or network call that returns nothing.
- Write-heavy stores read far more on-disk files than they need to on every miss.
- Dedup and crawler pipelines either store every key in memory or re-do work they've already done.
Where it fits
- Sits in front of a slow lookup, as a fast gate that rejects certain misses.
- Lives inside LSM-tree storage engines, cache layers, and dedup pipelines.
- A performance optimization, never the source of truth — it only ever says 'skip' or 'go check'.
Related topics
- Indexing: LSM-tree indexes use Bloom filters to skip files that can't hold a key
- Caching: a filter avoids a slow backend call for a key that was never stored
- Database types: write-heavy stores lean on this trick to keep reads fast
- Latency vs throughput: the accuracy-for-speed bargain, named at the concept level
Interview lens
Questions it unlocks
- How do you avoid expensive lookups for keys that don't exist?
- How would a web crawler cheaply track seen URLs at scale?
- What's the catch with a Bloom filter?
60-second answer
A Bloom filter is a small bit array with several hash functions that answers membership as 'definitely no' or 'maybe yes', never a false negative. That lets me skip expensive lookups whenever it says absent, and only do the real check on a 'maybe'. I'd use it in front of LSM-tree files, caches, and crawler seen-sets to save disk reads or network calls. I'd size it from the expected item count and a target false-positive rate — roughly ten bits per item for 1% — and note the trade-offs: tunable false positives and no deletion without a counting variant.
Common traps
- Thinking it can give false negatives — it can't, only false positives.
- Trying to delete items from a standard (non-counting) Bloom filter.
- Forgetting a 'maybe' still requires the real lookup to confirm.