Bloom filters: a memory that can say 'definitely not'
In databases that skip pointless disk reads, and in browsers checking a website against a list of dangerous sites
What problem does it solve?
How do you check whether something is in a huge set using a tiny amount of memory?
The big idea
Keep a row of m bits, all 0. To add an item, hash it k different ways and set those k bits to 1. To check an item, look at its k bits: if any is 0, it was definitely never added. If all are 1, it was probably added, but other items might have set those bits by coincidence. Trading a small, controllable chance of 'false alarm' for huge memory savings is the whole trick, and you never get a false 'no'.
How it works, step by step
- 1. Make an array of m bits, all 0.
- 2. Add: compute k hashes of the item and set those k positions to 1.
- 3. Query: compute the same k hashes and look at those bits.
- 4. Any 0 means 'definitely not in the set'; all 1s mean 'probably in it', so check the slow, exact source.
The key formula
- the false-positive rate: the chance of a wrong 'probably yes'
- how many items have been added
- how many bits the filter has
- how many hash functions; the best choice is about (m/n)·ln 2
How fast is it?
Adding and checking take just k hash computations, no matter how big the set is. With 10 bits per item and k = 7, the false-positive rate is under 1%, and the filter never stores the items themselves.
Try it yourself
- Why can't you delete an item from a Bloom filter by switching its bits back to 0?
- Use the formula: how many bits per item do you need for a 1-in-1000 false-positive rate? (About 14.4.)
Fun fact
Burton Bloom invented them in 1970, when computer memory was precious. Google's Bigtable database (2006) uses Bloom filters to avoid reading disk files that don't contain the requested data, and early versions of Chrome's Safe Browsing kept a Bloom filter of dangerous sites on your computer.