Bloom filter
A fixed-size array of bits plus k hash functions: inserting an item sets k bits, and a lookup that finds any of its k bits unset knows the item was never inserted. It exists because "have I seen this key?" over billions of keys would need gigabytes as a set, and the filter answers it in a few bits per item if you accept a small chance of a false "maybe".
What it costs
| Operation | Cost | Note |
|---|---|---|
| Insert | O(k): k hashes, k bits set | k is typically 5–10. Two base hashes combined as h1 + i·h2 produce all k cheaply. |
| Lookup | O(k): k hashes, k bits read | Any unset bit → definitely absent. All set → probably present, with false-positive rate p. |
| Delete | Not supported | Clearing a bit might clear it for another item. Use a counting Bloom filter or a cuckoo filter if deletes are needed. |
| Union of two filters | O(m): bitwise OR | Only if both filters have the same size and hashes. Lets each shard build its own and merge. |
Memory: About 9.6 bits per item for a 1% false-positive rate, 14.4 bits for 0.1%, regardless of item size. 100M items at 1% is 120 MB; the same items as a set of 16-byte hashes would be 1.6 GB plus overhead.
k hashes set k bits; any zero bit means absent
Inserting "aB3xZ9" sets bits 2, 9 and 14. Testing "q7Lm2Pz" reads bits 5, 9 and 20: bit 5 is zero, so it was never inserted. Testing "zz9" reads 2, 9, 14, all set by other items: a false positive.
How it works
- Choose the expected number of items n and the false-positive rate p you can live with. The optimal bit-array size is m = −n·ln(p) / (ln 2)^2 and the optimal number of hashes is k = (m/n)·ln 2. For n = 1M and p = 1%: m ≈ 9.6M bits (1.2 MB), k = 7.
- Allocate m bits, all zero.
- To insert an item, hash it k ways (in practice: compute two 64-bit hashes h1 and h2 and use h1 + i·h2 mod m for i = 0…k−1) and set each of those k bit positions to 1.
- To test an item, compute the same k positions and read them. If any bit is 0, the item was definitely never inserted, because inserting it would have set that bit. If all k bits are 1, the item was probably inserted, but the bits could all have been set by other items: that is a false positive.
- The false-positive rate grows as the array fills. Once the number of inserted items passes n, the rate climbs past p; the filter does not break, it just lies more often. Size for the maximum you expect, or use a scalable Bloom filter that adds a new, larger filter when the current one fills.
Why no false negatives, ever
- Bits are only ever set, never cleared, so an inserted item’s k bits stay set for the life of the filter. A lookup for it always sees all k bits set. The only error is in the other direction.
- That asymmetry is what makes it safe as a pre-check: a "no" skips the expensive lookup with certainty; a "maybe" falls through to the real store, which gives the exact answer.
Worked example
A filter in front of the URL store to reject unknown aliases
- 6 billion aliases exist, but 2% of redirect requests are for aliases that do not (typos, expired links, scanners). Each of those currently costs a cache miss plus a database read that finds nothing.
- Size for n = 6B aliases at p = 1%: m = 57.6 billion bits = 7.2 GB, k = 7. Too big for one process, so shard it by the first character of the alias into 62 filters of 116 MB each, or accept p = 5% (4.5 GB, k = 4). The exact set of aliases as 7-byte strings would be 42 GB before overhead.
- Request for alias "q7Lm2Pz": compute 7 bit positions from two hashes (about 40 ns), read 7 bits. Bit 3 is 0, so the alias definitely does not exist: return 404 without touching Redis or the database. Of the 2% unknown requests, 99% are rejected here; the remaining 1% of 2% (0.02% of all traffic) fall through to the database and get an exact "not found".
- Request for alias "aB3xZ9", which exists: all 7 bits are 1 (they must be, since it was inserted). Fall through to the normal cache-aside path. No false negatives means no real link is ever wrongly refused.
- A new alias is created: set its 7 bits in the filter on every redirect server (publish the alias on a topic). Deleting a link does not clear bits; the filter says "maybe" and the database returns 410, which is correct.
When it is the wrong choice
- You need to delete items: a plain Bloom filter cannot clear bits safely. Use a counting Bloom filter (4-bit counters instead of bits, 4× the memory) or a cuckoo filter, which supports delete and is often smaller.
- A false positive is expensive or dangerous (billing, security decisions): the filter can only be a pre-check in front of an exact store, never the final answer.
- The item count is unknown and could be 100× your estimate: the false-positive rate will climb toward 100%. Use a scalable Bloom filter or size for the worst case.
- You need to list what is inside: a Bloom filter stores bits, not items, and cannot enumerate them.
Interviewer follow-ups
Answer out loud before you open each one.
Why can a Bloom filter never give a false negative?
Inserting an item sets its k bits, and bits are never cleared. Any later lookup for that item computes the same k positions and finds them all set. The only way a lookup says "absent" is a zero bit, and a zero bit proves no inserted item ever mapped there.
How do you choose the size and number of hashes?
From the expected items n and acceptable false-positive rate p: bits m = −n·ln(p)/(ln 2)^2 and hashes k = (m/n)·ln 2. For 1% that is about 9.6 bits and 7 hashes per item; for 0.1% about 14.4 bits and 10 hashes. Too few hashes under-use the bits; too many fill the array faster.
Where does an LSM tree use Bloom filters?
One per SSTable. A point read checks each level’s filter before opening the file, so a key that lives in level 3 skips the files in levels 0 to 2 with no disk read. Without filters a miss would read every level, which is the read amplification LSM trees are criticised for.
What happens when you insert more items than the filter was sized for?
Nothing breaks, but the array fills up and the false-positive rate rises: at twice the planned items a 1% filter gives roughly 7%, and a nearly full array says "maybe" to everything. Monitor the fraction of set bits and rebuild or scale when it passes about 50%.
Where it shows up
- Building blocks
- Count big things with small memory · Write-optimised vs read-optimised storage · Drop duplicate events · Know your read amplification · Cache the hot reads · Catch spam and abuse
- Problems
- URL Shortener (TinyURL / bit.ly) · Distributed Key-Value Cache (Redis / Memcached-like) · Video Streaming Platform (YouTube / Netflix)