Bloom filters in system design interviews
A Bloom filter is a compact bit array that answers "have I seen this item?" with either "definitely not" or "probably yes". It never gives a false negative, it gives false positives at a rate you choose when sizing it, and it needs about 9.6 bits per item for a 1% false positive rate no matter how large the items are. In system design it sits in front of something expensive, such as a disk read, a database lookup or a network call, so most of the calls that would have found nothing are skipped.
By Evin JohnPublished 8 min read
1. What a Bloom filter is
Burton Bloom described the structure in 1970 as a way to test set membership in far less memory than storing the set. It holds no items at all, only a row of bits that starts as all zeros. That is the whole trick and the whole limitation: because the items are not stored, the filter cannot list them, cannot remove one safely and can be fooled when other items happen to have set the same bits.
A useful way to say it in an interview: a Bloom filter is a fast, lossy "no" detector. When it says no, you skip the expensive work with certainty. When it says maybe, you do the expensive work and accept that it sometimes finds nothing.
2. Why it comes up in interviews
Bloom filters appear wherever a design asks "have we seen this before?" at a scale where an exact set would not fit in memory. A web crawler checking whether a URL was already fetched is the classic. Interviewers use it to test whether you know the one-sided error, can size the filter from a target error rate and understand what happens when the filter fills up or an item needs to be removed. Naming it is easy; explaining why it never returns a false negative is what earns credit.
3. How adding and checking work
- Start emptyAllocate m bits, all set to 0, and pick k independent hash functions that each map an item to a position from 0 to m - 1.
- Add an itemHash it k times and set the bit at each resulting position to 1. Bits already set stay set.
- Check an itemHash it the same k ways. If any of those bits is 0, the item was never added: an add would have set it. If all are 1, the item was probably added.
- Accept the false positiveAll k bits can be 1 because other items set them. The fuller the array, the more often that happens.
- Adds
- cat: bits 1, 5, 9
- dog: bits 3, 5, 10
- Bit array (12 bits)
- Set: 1, 3, 5, 9, 10
- Clear: everything else
- Checks
- cow: bit 2 is 0, definitely absent
- owl: bits 1, 3, 10 all set, probably present (false positive)
Implementations do not need k truly separate hash functions. A common shortcut computes two hashes, h1 and h2, and derives the rest as h1 + i x h2 for i from 0 to k - 1, which analysis has shown keeps the error rate close to the ideal.
4. Sizing it
With n items, m bits and k hashes, the false positive rate is approximately p = (1 - e^(-kn/m))^k. Solving for the best settings gives the two formulas worth memorizing:
bits needed: m = -n x ln(p) / (ln 2)^2
best hash count: k = (m / n) x ln 2 (about -log2(p))
target p bits per item hashes
10% 4.8 3
1% 9.6 7
0.1% 14.4 10
Each tenfold drop in false positives costs about 4.8 more bits per item.
Example (assumed): 1 billion URLs at 1%
m = 1e9 x 9.6 bits = 9.6 billion bits = about 1.2 GB
the same set as raw 50-byte URLs would be about 50 GBThe size depends on the number of items and the error rate, not on how big each item is, which is why Bloom filters shine for long keys such as URLs. The filter also has a capacity in a real sense: the formula assumes n items. Filling it past n raises the error quickly. A filter built for 100,000 items at 1% holds at roughly 1% at 100,000 items, but by the formula it reaches about 16% at 200,000. Size for the count you expect at the end of the filter's life, not today's.
import hashlib, math
class BloomFilter:
def __init__(self, n, p):
self.m = math.ceil(-n * math.log(p) / math.log(2) ** 2) # bits
self.k = max(1, round(self.m / n * math.log(2))) # hash functions
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
d = hashlib.sha256(item.encode()).digest()
h1 = int.from_bytes(d[:8], "big")
h2 = int.from_bytes(d[8:16], "big") | 1 # double hashing
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def might_contain(self, item):
return all(self.bits[pos // 8] >> (pos % 8) & 1 for pos in self._positions(item))
bf = BloomFilter(n=100_000, p=0.01) # 958,506 bits, 7 hashes, 9.59 bits per item
for i in range(100_000):
bf.add(f"user:{i}")
assert all(bf.might_contain(f"user:{i}") for i in range(100_000)) # never a false negative
fp = sum(bf.might_contain(f"other:{i}") for i in range(100_000))
print(fp / 100_000) # 0.01019 on our run, close to the 1% target5. Deleting, growing and sharing
| Variant | What it adds | Cost |
|---|---|---|
| Counting Bloom filter | Each position is a small counter instead of a bit, so removing an item decrements its counters | Several times the memory (often 4 bits per position); a counter that overflows breaks deletes |
| Cuckoo filter | Stores short fingerprints in a hash table; supports deletion and is often smaller than a Bloom filter at low error rates | Inserts can fail when the table is nearly full; deleting an item never added can remove another's fingerprint |
| Scalable Bloom filter | Adds a new, larger filter when the current one fills, with tighter error targets for each so the total stays bounded | Lookups check every layer |
| Partitioned or blocked filter | Keeps an item's k bits inside one cache line or block | Slightly higher error for the same memory, in exchange for faster lookups |
Two filters with the same size and hash functions can be merged with a bitwise OR, which gives a filter for the union. That makes them easy to build per shard and combine, or to ship to clients as a compact summary of a set.
6. When to use one, and when not to
- Use it when most lookups are for absent items and each miss is expensive: a disk read, a remote call, a database query.
- Use it when an exact set does not fit in memory but a small false positive rate is tolerable.
- Skip it when a false positive causes harm you cannot recover from. If "probably seen" means a user is wrongly blocked or a payment is wrongly rejected, confirm against the source of truth or use an exact set.
- Skip it when the set is small. A hash set of a few thousand keys costs little and has no errors.
- Skip it when you need to list, count or delete members. It can do none of those.
7. How it shows up in common prompts
| Setting | What it filters | Why it fits |
|---|---|---|
| Web crawler | URLs already fetched or queued | Billions of long URLs; a rare false positive only skips one page |
| LSM-tree storage engines (the kind behind Cassandra, RocksDB and HBase) | Keys in each on-disk sorted file | A lookup skips files whose filter says the key is absent, saving disk reads |
| Caching at a CDN or app tier | Objects requested only once so far | Caching only on the second request keeps one-hit wonders from evicting popular items |
| URL shortener | Short codes already taken | A quick check before generating a code; a false positive just means trying another code |
| Sign-up and feeds | Usernames taken, posts a user has already seen | A fast first check, confirmed against the database when it says maybe |
8. Interview questions on Bloom filters
| Question | What to cover |
|---|---|
| Why can't a Bloom filter return a false negative? | Adding an item sets all of its bits, and bits are never cleared, so its check always finds them set |
| What causes false positives? | Other items setting the same k positions; the rate climbs as the array fills |
| How big must it be for 10 million items at 1%? | About 9.6 bits each, so roughly 96 million bits, around 12 MB, with 7 hashes |
| Why not just use a hash set? | A hash set stores every key; the filter stores about 10 bits per key regardless of key size |
| How do you delete from it? | You cannot with a plain filter; use a counting or cuckoo filter, or rebuild periodically |
| What happens when you insert more items than planned? | The false positive rate rises sharply; rebuild larger or use a scalable filter |
| Where would you put one in this design? | In front of the expensive lookup that usually finds nothing |
| What if a false positive is unacceptable? | Treat "maybe" as a prompt to check the source of truth, never as the answer |
9. Mistakes to avoid
- Getting the error direction backwards. False positives are possible; false negatives are not.
- Sizing for today's count. The error rate depends on the final number of items.
- Removing items by clearing bits. Those bits may belong to other items too, which creates false negatives.
- Using a slow cryptographic hash k times in a hot path. Fast non-cryptographic hashes and double hashing are the norm (the example above uses SHA-256 only for portability).
- Letting "probably" make a final decision where being wrong hurts a user.
10. How to talk about it in the interview
- Say what expensive operation the filter saves and how often lookups are for absent items.
- Give the size from the formula with your assumed n and p, in bytes.
- State the error behavior plainly: no false negatives, a chosen false positive rate, and what a false positive costs here.
- Mention how the filter is rebuilt or grown as the set changes.
Fictional example
- Interviewer
- The news feed should not show an article a reader has already seen. Readers see thousands of articles a month. How do you check that cheaply?
- Candidate
- I would keep two Bloom filters per reader, one for this month and one for last month, and check both. At around 3,000 articles a month in each and a 1% error rate, that is about 29,000 bits, under 4 KB per filter, small enough to load with their session.
- Interviewer
- What does a false positive do here?
- Candidate
- It hides an article the reader never saw. Checking two filters at 1% each means roughly two in a hundred unseen articles get wrongly skipped. For a feed that is acceptable. For something important, like a breaking alert, I would skip the filter. At the start of each month I drop the older filter and start a fresh one, so old entries age out without ever deleting from a filter.
Practicing the sizing questions with Natively
Bloom filter questions mix a concept with quick arithmetic, and the arithmetic is where nerves show. Say your sizing out loud in a mock round while Natively transcribes it on your laptop; you can ask it to check a number you just said or to suggest what an interviewer would ask next. If the formula is on a whiteboard photo or a slide, a screenshot lets it read and explain what is there. The saved transcript and notes make it easy to see later whether you stated the error direction correctly every time.
Questions people ask
What is a Bloom filter used for?
It is a compact structure that tells you whether an item is definitely not in a set or probably in it. Systems put one in front of an expensive lookup, such as a disk read or a database query, so that most lookups for absent items are skipped. Web crawlers, storage engines and caches are common examples.
Can a Bloom filter have false negatives?
No. Adding an item sets all of its bit positions and bits are never cleared, so checking that item always finds them set. It can have false positives, when other items have set the same positions, at a rate determined by its size and how full it is.
How do you calculate the size of a Bloom filter?
Use m = -n ln(p) / (ln 2)^2 bits for n items and false positive rate p, and k = (m / n) ln 2 hash functions. For a 1% rate that is about 9.6 bits and 7 hashes per item, so 10 million items need roughly 12 MB.
How do you delete an item from a Bloom filter?
A standard Bloom filter does not support deletion, because clearing an item's bits could clear bits other items rely on and create false negatives. A counting Bloom filter, which uses small counters instead of bits, or a cuckoo filter supports removal. Another option is to rebuild the filter periodically.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
