Video in progress
How does a Bloom filter work, and how do you compute the size you need?
An array of m bits and k hash functions. On insert we set k bits to 1; on lookup, if all are 1 the answer is "probably present", and if any is 0 it's "definitely absent". For n elements and false positive rate p, m ≈ −n·ln p / (ln 2)² and k ≈ (m/n)·ln 2.
📖 Answer
There are no false negatives, but there are false positives. That asymmetry makes it a cheap filter in front of an expensive check: if it says "no", we don't go to disk or the DB.
A worked example: 10 million elements, 1% false positives.
- m ≈ 10⁷ × 4.6 / 0.48 ≈ 96 million bits ≈ 12 MB
- k ≈ 9.6 × 0.69 ≈ 7 hashes
Storing those 10 million keys in a HashSet<String> would take hundreds of MB.
You don't have to compute k independent hashes every time. Getting k of them from two hashes with the formula h1 + i·h2 (Kirsch–Mitzenmacher) is enough in practice:
boolean mightContain(byte[] key) {
long h = murmur3_128(key); // from a library, two 64-bit halves
int h1 = (int) h, h2 = (int) (h >>> 32);
for (int i = 1; i <= k; i++) {
int combined = h1 + i * h2;
if (combined < 0) combined = ~combined;
if (!bits.get(combined % m)) return false;
}
return true;
}
Rather than writing it by hand, I use Guava's BloomFilter.create(Funnels.stringFunnel(UTF_8), 10_000_000, 0.01) or Redis's RedisBloom module.
Limits you find out about later in prod:
- You can't delete. If you set a bit back to 0, other elements also "disappear". If you need deletion, use a counting Bloom filter or a Cuckoo filter.
- If more elements are added than planned, the false positive rate grows fast. With 2× too many elements, 1% goes up to about 15%. So I size it with headroom or rebuild the filter periodically.
- You can't grow it either: you build a new filter and refill it.
Where it shows up: Cassandra and RocksDB before reading an SSTable; protecting against cache penetration (an attack with IDs that don't exist in the database); "has this URL been seen" in a crawler.
Sign up to mark studied questions and save your progress.