A wall of lamps by the door
Picture a huge party. The full guest book is kept in the cellar, and walking down there takes ages. People keep asking the doorkeeper "did Zed come tonight?"
So the doorkeeper keeps a small wall of numbered lamps by the door. With one quick look at it, they can give one of two answers: "Zed surely never came", or "Zed maybe came, let me check the book".
"Surely not" is always right, and it saves the walk to the cellar. "Maybe" sometimes turns out wrong, and then the walk was wasted. This wall of lamps is called a Bloom filter.
Definitely not, or maybe
A Bloom filter (Burton Bloom, 1970) is a space-efficient probabilistic data structure for set membership. It
answers mightContain(x) with:
- false: x was definitely never added. This answer is always correct.
- true: x was probably added. It may be a false positive.
There are no false negatives: an element that was added always tests as present.
Why accept "maybe"? Because the filter doesn't store the elements at all, only a few bits per element (about 10 bits for a 1% false positive rate, whatever the element's size). That makes it small enough to keep in memory in front of something slow, like a disk, a network call or a database, and skip the slow lookup whenever the answer is "definitely not".
Switching lamps on
The doorkeeper has three fixed counting recipes. Each recipe turns any name into a lamp number, and always gives the same number for the same name. One might count the letters, another add up their places in the alphabet.
When Ana arrives, the three recipes give lamps 1, 4 and 6, so the doorkeeper switches those three on. When Ben arrives, his recipes give 2, 4 and 7. Lamp 4 is already on, and it just stays on.
Lamps are only ever switched on, never off. The wall doesn't write down names at all, which is why it stays so small.
Adding: k hash functions over m bits
A Bloom filter is a bit array of m bits, all 0 at the start, plus k independent hash functions, each mapping an element to a position from 0 to m - 1.
To add an element, compute its k positions and set those bits to 1. Bits that are already 1 stay 1, so elements share bits freely. Adding is O(k), no matter how many elements the filter holds.
In practice you don't need k truly separate hash functions. Implementations usually compute one or two good hashes
and derive all k positions from them (double hashing: position i is h1 + i * h2 mod m). Guava, for example, takes
the two halves of a 128-bit Murmur3 hash.
Asking: did they come?
Someone asks about Zed. The doorkeeper runs Zed's name through the three recipes and gets lamps 0, 4 and 6. Lamp 0 is off. If Zed had come, he would have switched it on, so Zed surely never came. No trip to the cellar.
Then someone asks about Cal. Cal's lamps are 1, 2 and 7, and all three are on, so the answer is "maybe". But Cal never came! Ana and Ben switched those lamps on between them. That wrong "maybe" is a false positive. It costs a wasted walk to the cellar, but it never makes the doorkeeper say "surely not" about a guest who really came.
Checking, and false positives
To check an element, compute the same k positions and read the bits:
- If any bit is 0, the element was never added, because adding it would have set that bit. Answer: definitely not.
- If all k bits are 1, answer: maybe. Other elements may have set every one of those bits between them.
That second case is a false positive. False negatives can't happen as long as bits are never cleared, which is exactly why a plain Bloom filter doesn't support deletion (see below).
A Bloom filter can only say "maybe" for an element, never "yes". When a correct answer matters, a "maybe" must be confirmed against the real data. The filter's job is to make the common "no" case cheap.
How many lamps, how many recipes
Every guest switches on a few more lamps. With too many guests for the wall, nearly every lamp is on, and then nearly every question gets "maybe", which is no help at all.
So the doorkeeper plans ahead. If they expect a thousand guests, they build a wall with about ten lamps per guest, and then a wrong "maybe" happens only about once in a hundred questions. More lamps per guest means fewer wrong answers. The number of recipes matters too: too few and each guest's lamps are easy to match by accident, too many and the wall fills up too fast.
Sizing: m, n, k and the false positive rate
After inserting n elements into m bits with k hash functions, the false positive probability is approximately
p โ (1 - e^(-k*n/m))^k
- For given m and n, the best number of hash functions is
k = (m/n) * ln 2, which leaves about half the bits set. - With that k, you need about
1.44 * log2(1/p)bits per element: about 9.6 bits for 1%, about 14.4 for 0.1%. Each 10x reduction in p costs about 4.8 more bits per element. - The size depends on n and p, never on how big the elements are: a filter over URLs costs the same as one over integers.
The filter can't grow in place. Insert far more than the expected n and the bits saturate: the false positive rate climbs towards 100%. Libraries therefore ask for the expected number of insertions up front. If the set grows, rebuild a bigger filter, or use a scalable variant that chains new filters as old ones fill.
When the lamps mislead
Lamps can let the doorkeeper down in a few ways.
- Too many guests. The wall was built for a thousand, and three thousand arrive. Nearly every lamp is on, so nearly every answer is "maybe" and the doorkeeper is back to walking to the cellar all night. The fix is to build a bigger wall from the guest book.
- A guest who never got a lamp. If a late guest is written in the book but nobody switches on their lamps, the wall says "surely not" about someone who really came. That is the one mistake the wall must never make, so the doorkeeper switches lamps on every time a guest is written down.
- A guest who leaves. Switching a lamp off could hide someone else who shares it, so lamps stay on. A leaver stays a "maybe" until the wall is rebuilt.
- Two doorkeepers, two recipes. Walls built with different recipes or sizes can't be laid on top of each other, because the same lamp number means different things.
A wall also isn't worth building if nearly every question is about someone who really came, since the answer will be "maybe" anyway.
What can go wrong
- Overfilling. The filter is sized for an expected n, but inserts go on well past it. Every insert sets up to k more bits, so the false positive rate climbs towards 1. Symptom: the slow store gets reads for keys that don't exist, and Guava's
expectedFpp()rises (stores that report the observed rate, such as Cassandra's 'Bloom filter false ratio' innodetool tablestats, show the effect directly). Fix: size for the real n with headroom, monitor the count against the plan, and rebuild bigger or use a scalable filter. - A stale filter. The filter is built from a snapshot, or a write path forgets
put. A key then exists in the store but the filter says definitely not, a false negative that turns into a real miss: a 404 for data that exists. This breaks the filter's one guarantee. Fix: add to the filter on every insert, in the same code path that writes the data, and rebuild it from the store regularly. - No deletes. In a plain filter a removed key still tests as maybe, because clearing its bits could hide other keys. That costs only needless lookups, not wrong answers. Fix: rebuild periodically (LSM engines do this at compaction), or use a counting filter (counters instead of bits, about 4 times the memory) or a cuckoo filter.
- Incompatible filters. Filters built on different nodes with different sizes, k, hash functions or seeds can't be merged or compared: bit i means something different in each. Merging them silently gives wrong answers. Guava's
putAllonly accepts a compatible filter and throwsIllegalArgumentExceptionotherwise;isCompatiblechecks first. Fix: agree on m, k and the hash in one shared config, and ship filters in the same serialised form. - A filter that earns nothing. If most lookups are for keys that exist, the answer is "maybe" anyway and the filter only costs memory. Symptom: a tiny share of lookups answered with definitely not. Fix: measure the share of lookups skipped, and drop the filter when it is negligible.
The sizing formula shows how fast overfilling bites. Take a filter planned for n = 1,000 at p = 1%. It needs m = -n * ln p / (ln 2)^2 = about 9,585 bits, with k = (m/n) * ln 2 = about 7. Then p โ (1 - e^(-k*n'/m))^k for n' inserted keys gives:
| Keys inserted | Bits set | False positive rate |
|---|---|---|
| 1,000 (as planned) | about 52% | about 1% |
| 2,000 | about 77% | about 16% |
| 3,000 | about 89% | about 44% |
| 5,000 | about 97% | about 83% |
| Choice | You gain | You pay |
|---|---|---|
| More bits per item | A lower false positive rate: about 4.8 more bits per element for each 10x drop | Memory, which must stay resident to be fast |
| More hash functions (k) | Fewer collisions, up to the optimal k | k bit reads and hashes per check, and past the optimum a fuller array |
| Counting filter | Deletes | About 4 times the memory of a plain filter |
| Cuckoo or scalable filter | Deletes (cuckoo), or growth past the planned n (scalable) | More complex code, and a scalable filter's error is bounded by the sum of its chained filters' rates |
Saving trips to the cellar
Over a long party the guest book grows into several boxes of cards in the cellar, because new cards are packed into a fresh box instead of squeezed into old ones. Each box gets its own little lamp wall at the top of the stairs. To find card 42, the doorkeeper looks at each box's lamps first and only opens the box whose lamps say "maybe". The boxes that say "surely not" are never opened, which saves most of the walking.
Boxes are never changed once packed. Now and then the doorkeeper merges a few into a new box and builds it a fresh lamp wall.
Where Bloom filters are used
LSM-tree storage engines such as Cassandra, RocksDB, LevelDB and HBase write data into many immutable sorted files (SSTables). A point read could have to look in every file. So each file can carry a Bloom filter over its keys (always in Cassandra; in RocksDB and LevelDB when a filter policy is configured), kept in memory, and a read only touches the files whose filter says "maybe".
- Cassandra builds one filter per SSTable, stored off-heap, tuned per table with
bloom_filter_fp_chance(default 0.01, or 0.1 with LeveledCompactionStrategy). A change applies to new SSTables as they are written. - RocksDB embeds a filter in each SST file when you set a filter policy, for example
NewBloomFilterPolicy(10)for 10 bits per key, about 1% false positives. Whole-key filters help point lookups (Get), not range scans.
Other common uses: skipping a cache or database lookup for keys that can't exist (stopping requests for random missing IDs from reaching the database), "have we seen this URL before?" in web crawlers, and avoiding sending data that the other side already has.
In Java, Guava has a ready-made one:
1import com.google.common.hash.BloomFilter;2import com.google.common.hash.Funnels;3import java.nio.charset.StandardCharsets;45BloomFilter<String> seen = BloomFilter.create(6Funnels.stringFunnel(StandardCharsets.UTF_8),71_000_000, // expected insertions80.01); // target false positive probability910seen.put("ana@example.com");1112if (!seen.mightContain(email)) {13// definitely new: skip the database lookup14} else {15// maybe seen: confirm against the database16}
With 1,000,000 expected insertions at 1%, that is under 10 million bits, about 1.2 MB, however long the emails are.
Without the third argument Guava uses 3%. BloomFilter is Serializable (given a serializable funnel), and
writeTo / readFrom save it in a compact form.
No deletion. You can't remove an element by clearing its bits, because other elements may share them. Clearing bit 4, set by both "ana" and "ben", would also hide "ben", a false negative, which breaks the filter's one guarantee. The usual answers are to rebuild the filter from the real data (LSM engines get this for free: a compacted file gets a fresh filter), or to use a variant.
Counting Bloom filters replace each bit with a small counter, often 4 bits. Adding increments the k counters, deleting decrements them, and a counter above 0 counts as set. That allows deletion at roughly 4 times the memory, and only for elements that really were added; a counter that overflows must stick at its maximum.
Other relatives: cuckoo filters support deletion and often use less space at low false positive rates; Ribbon filters (in RocksDB) reach the same rate as a Bloom filter in noticeably less space, at some extra CPU cost to build.
Union and intersection: two filters with the same m, k and hash functions can be OR-ed to get the filter of the union. AND-ing them only approximates the intersection.