Bloom filters
A tiny row of bits that answers “have I seen this before?” in an instant. It is never wrong when it says no, and only sometimes wrong when it says yes.
In 30 seconds
A Bloom filter remembers a set of items without storing them. It keeps a row of bits and a few hash functions; adding an item switches on the bits its hashes point to.
To check an item, look at its bits. Any 0 means it was definitely never added. All 1s means it probably was, but other items may have set those bits: a false positive.
More bits per item make mistakes rarer. Databases and caches use it to skip slow lookups for things that are not there.
Bloom filters, step by step
The hash outputs here are invented to keep the example small. Real filters use fast hashes such as MurmurHash over millions of bits, and the error formula is an approximation.
- Step 1: A row of bits, three hashes. A Bloom filter is a row of bits, all 0 at first, plus a few hash functions that each turn a word into a position. To add “cat”, run it through all three and switch those three bits on. The word itself is never stored.
- Step 2: Add a second item. Adding “dog” sets bits 3, 6 and 13. Bit 6 was already on from “cat”, so it simply stays on. Items share bits, which is how a filter stays so small, and also why it can be fooled later.
- Step 3: Query: definitely not. To ask “have you seen cow?”, hash it the same way and look at its three bits. Bit 8 is 0, and adding cow would have set it, so cow was never added. A “no” is always right: there are no false negatives.
- Step 4: Query: a false positive. “fox” was never added, but its three bits happen to be on already: one from cat, two from dog. The filter can only say “probably yes”, and here that is wrong. A “yes” means maybe; this is the false positive.
- Step 5: Why you cannot delete. Suppose we remove “cat” by switching its bits off. Bit 6 was shared, so a query for “dog” now finds a 0 and gets a wrong “no”. A plain Bloom filter therefore never deletes; variants that keep a small counter per slot can.
- Step 6: Tuning the size. The error rate depends on how many bits you allow per item (m/n) and on k. More bits mean fewer accidental matches. Roughly 10 bits per item with 7 hashes gives about 1% false positives, whether the items are short words or long URLs.
- Step 7: Where it earns its keep. Many databases keep a filter in memory for each file on disk. A lookup asks the filter first, and a “no” saves a slow disk read; a “maybe” is checked for real, so a false positive only costs time. Web caches use the same test to avoid storing pages requested only once.
Try it yourself
Learn this first
Learn next
- Hash indexesOne hash, one bucket, one row: fast exact lookups that cannot do ranges. Beginner
- Caching layersCopies kept in the browser, CDN, app and database, and when they go stale. Beginner
- Distributed cachingOne cache spread over several nodes: who holds which key, and what can go wrong. Intermediate
Spotted a mistake on this page?