Bloom Filters
A Bloom filter answers 'have I seen this?' with a bit array and a few hash functions, storing none of the items. A 'no' is always right; a 'yes' may be wrong. About 10 bits per item keeps those wrong answers near 1%.
Membership Without Storing Anything
A hash set answers 'have I seen this?' in O(1), but it stores every element. A set of a billion URLs averaging 60 bytes needs 60 gigabytes plus the table's own overhead. When the only question is membership, storing the elements is paying for information you never read back.
A bloom filter answers the same question while storing no elements at all. It is a bit array of m bits, all initially 0, plus k independent hash functions, each mapping an element to a position in that array.
To insert an element, hash it with all k functions and set the k resulting bits to 1. Bits already set stay set — nothing records which element set them.
To query an element, hash it the same way and check those k bits. If any is 0, the element was definitely never inserted, because insertion would have set it. If all are 1, the element is probably present — but the bits may have been set by other elements coincidentally.
So the structure gives an asymmetric answer, and the asymmetry is the whole design: false positives are possible, false negatives are not. It may claim something is present when it is not; it will never claim something is absent when it is.
The size does not depend on what is stored. Ten bits per element covers a 60-byte URL or a 4-byte integer alike, because only the hash positions matter. That is where the saving comes from: a billion URLs fit in about 1.25 gigabytes of bits instead of 60.
- An empty filter answers 'definitely absent' to every query
- Adding the same key twice changes nothing the second time
- Insert and query must compute the same positions. Python's built-in
hash()of a string changes between runs, so a filter that is saved or shared needs its own hash function, as in the code below
Why the Asymmetry Is Useful
A structure that sometimes lies seems unusable until you see the pattern it fits: a bloom filter is a cheap filter in front of an expensive check.
The arrangement is always the same. Query the filter first. If it says definitely absent, skip the expensive operation entirely — and that answer is always correct. If it says maybe present, perform the expensive check to find out. The filter never causes a wrong final answer; it only removes work.
So a 1% false positive rate means 1% of negative queries do an unnecessary expensive lookup, while 99% of them are eliminated for free. The correctness of the system is unaffected because the authoritative check still runs whenever the filter says maybe.
This is why the direction of the error matters so much. A false negative would cause the expensive check to be skipped when it should have run, producing a genuinely wrong answer. False positives only cost time. A structure with the errors reversed would be useless for this pattern.
The common bloom filter use cases all have this shape. Databases built on LSM trees (Cassandra, HBase, LevelDB, RocksDB) keep a filter per on-disk file, so a lookup skips files that certainly do not hold the key and avoids the disk read that dominates the cost. Web caches and CDNs avoid a backend fetch for content known to be absent. Chrome once checked URLs against a local filter of known malicious sites before asking the server. Bitcoin light clients used them to request only possibly relevant transactions.
The general form is worth stating: use a bloom filter whenever a negative answer is common and the authoritative check is expensive. If most queries are positive, the filter rarely saves anything and is not worth its memory.
- If most queries are positive, almost every query pays for the filter and then the real check anyway
- The filter must be updated on every insert into the real store; a missed update is a false negative
- A false positive rate of p means a fraction p of the absent keys get through, not a fraction of all queries
Sizing and the Optimal k
The bloom filter false positive rate is tunable, and the formulas are standard exam material.
For n elements in m bits with k hash functions, the probability that a given bit is still 0 after all insertions is (1 − 1/m)^(kn) ≈ e^(−kn/m). A false positive requires all k checked bits to be 1, so the rate is approximately (1 − e^(−kn/m))^k.
Minimising that expression over k gives the optimal number of hash functions: k = (m/n) · ln 2, about 0.693 times the bits per element. Putting it back in gives the size needed for a target rate p: m = −(n · ln p) / (ln 2)².
Working the numbers gives figures worth remembering. A 1% error rate needs about 9.6 bits per element and 7 hash functions. 0.1% needs about 14.4 bits and 10 functions. 10% needs about 4.8 bits and 3.
The striking part is how slowly the cost grows: each additional factor of ten in accuracy costs only about 4.8 more bits per element. Even a very low error rate stays far below the cost of storing the elements themselves.
The behaviour of k is worth understanding rather than just computing. Too few hash functions means each element sets few bits, so collisions between different elements become likely. Too many means each element sets many bits, filling the array faster and pushing the whole structure toward all-ones. The optimum sits where the array ends up roughly half full of ones, which is a useful sanity check on an implementation.
In practice k separate hash functions are not needed. Double hashing builds all k positions from two base hashes as h1 + i·h2, and Kirsch and Mitzenmacher showed this keeps the same error bounds. Libraries such as Guava compute one 128-bit MurmurHash and split it into the two halves; the code below uses two small polynomial hashes.
The parameters must be chosen from an estimate of n in advance. A bloom filter cannot be resized, and inserting far more than planned degrades the error rate sharply — eventually every query returns a false positive once the array is saturated.
| False positive rate | Bits per element | Optimal k |
|---|---|---|
| 10% | ≈ 4.8 | 3 |
| 1% | ≈ 9.6 | 7 |
| 0.1% | ≈ 14.4 | 10 |
| 0.01% | ≈ 19.2 | 13 |
- Worked example: n = 1 million and p = 1% give m ≈ 9.59 million bits (about 1.2 MB) and k = 7
- The tracer's filter has n = 3 and m = 10, so the best k is about 2.3; with k = 3 and 7 of 10 bits set, a random key is a false positive about 34% of the time
- Sanity check for an implementation: after n inserts at the optimal k, about half the bits should be 1
Terms, operations, and practical uses
Mechanics
- Bit ArrayThe underlying storage is a single array of
mbits, initially all set to 0. - Multiple HashesWhen an item is added, it is processed by
kdifferent hash functions, yieldingkindices in the bit array to flip to 1. - Membership QueryTo check existence, hash the item
ktimes. If allkbits are 1, it 'probably' exists. If any bit is 0, it definitively does not exist.
Properties
- False PositivesOccur when the
kbits queried were flipped to 1 by a combination of other inserted elements. - No False NegativesIf an element was actually inserted, its
kbits were irrevocably flipped to 1, meaning it will never report as missing. - No DeletionsStandard Bloom Filters cannot delete items, because flipping a 1 back to 0 might break the record of other colliding items.
Tuning and Variants
- Optimal ParametersThe math dictates that for
nitems and a target false positive ratep, the optimal bit array size ism = - (n * ln p) / (ln 2)^2. - Counting Bloom FilterReplaces single bits with small counters (usually 4 bits), allowing deletions at four times the memory.
- Database UsageLSM-tree databases such as Cassandra, LevelDB and RocksDB keep one filter per on-disk file to skip disk reads for keys that are certainly absent.
Code in Python, C++ and Java
M, K = 10, 3 # 10 bits, 3 hash functions
def poly_hash(s, base):
h = 0
for ch in s:
h = (h * base + ord(ch)) % 1000003
return h
def positions(item):
# double hashing: k positions from two base hashes
h1 = poly_hash(item, 31)
h2 = poly_hash(item, 37) % (M - 1) + 1
return [(h1 + i * h2) % M for i in range(K)]
class BloomFilter:
def __init__(self):
self.bits = [0] * M
def add(self, item):
for p in positions(item):
self.bits[p] = 1
def check(self, item):
return all(self.bits[p] for p in positions(item))
bloom = BloomFilter()
for word in ['apple', 'banana', 'cherry']:
bloom.add(word)
print('add', word, positions(word))
print('bits', ''.join(map(str, bloom.bits)))
for word in ['apple', 'kiwi', 'plum']:
print(word, 'possibly present' if bloom.check(word) else 'definitely absent')
for p in positions('banana'): # clearing bits to "delete" banana
bloom.bits[p] = 0
print('after clearing banana, apple', 'possibly present' if bloom.check('apple') else 'definitely absent')#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int M = 10, K = 3; // 10 bits, 3 hash functions
long long polyHash(const string& s, long long base) {
long long h = 0;
for (char ch : s) h = (h * base + ch) % 1000003;
return h;
}
vector<int> positions(const string& item) {
// double hashing: k positions from two base hashes
long long h1 = polyHash(item, 31);
long long h2 = polyHash(item, 37) % (M - 1) + 1;
vector<int> out;
for (int i = 0; i < K; i++) out.push_back((h1 + i * h2) % M);
return out;
}
struct BloomFilter {
vector<int> bits = vector<int>(M, 0);
void add(const string& item) {
for (int p : positions(item)) bits[p] = 1;
}
bool check(const string& item) const {
for (int p : positions(item))
if (!bits[p]) return false;
return true;
}
};
string list(const vector<int>& v) {
string s = "[";
for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
return s + "]";
}
int main() {
BloomFilter bloom;
for (string word : {"apple", "banana", "cherry"}) {
bloom.add(word);
cout << "add " << word << " " << list(positions(word)) << '\n';
}
cout << "bits ";
for (int b : bloom.bits) cout << b;
cout << '\n';
for (string word : {"apple", "kiwi", "plum"})
cout << word << (bloom.check(word) ? " possibly present" : " definitely absent") << '\n';
for (int p : positions("banana")) bloom.bits[p] = 0; // clearing bits to "delete" banana
cout << "after clearing banana, apple"
<< (bloom.check("apple") ? " possibly present" : " definitely absent") << '\n';
}import java.util.ArrayList;
import java.util.List;
public class Main {
static final int M = 10, K = 3; // 10 bits, 3 hash functions
static long polyHash(String s, long base) {
long h = 0;
for (char ch : s.toCharArray()) h = (h * base + ch) % 1000003;
return h;
}
static List<Integer> positions(String item) {
// double hashing: k positions from two base hashes
long h1 = polyHash(item, 31);
long h2 = polyHash(item, 37) % (M - 1) + 1;
List<Integer> out = new ArrayList<>();
for (int i = 0; i < K; i++) out.add((int) ((h1 + i * h2) % M));
return out;
}
static int[] bits = new int[M];
static void add(String item) {
for (int p : positions(item)) bits[p] = 1;
}
static boolean check(String item) {
for (int p : positions(item))
if (bits[p] == 0) return false;
return true;
}
public static void main(String[] args) {
for (String word : new String[] {"apple", "banana", "cherry"}) {
add(word);
System.out.println("add " + word + " " + positions(word));
}
StringBuilder sb = new StringBuilder();
for (int b : bits) sb.append(b);
System.out.println("bits " + sb);
for (String word : new String[] {"apple", "kiwi", "plum"})
System.out.println(word + (check(word) ? " possibly present" : " definitely absent"));
for (int p : positions("banana")) bits[p] = 0; // clearing bits to "delete" banana
System.out.println("after clearing banana, apple"
+ (check("apple") ? " possibly present" : " definitely absent"));
}
}Step through it
Running on add apple, banana, cherry; query apple, kiwi, plum; then delete banana
What It Cannot Do
The limitations are as important as the capabilities, and each one has a named workaround.
No deletion. Clearing an element's k bits would also clear bits shared with other elements, creating false negatives and destroying the structure's only guarantee. A plain bloom filter is insert-only.
The fix is a counting bloom filter, which replaces each bit with a small counter, typically 4 bits. Insertion increments the k counters, deletion decrements them, and a slot counts as set while its counter is above zero. It costs four times the memory, and a counter can overflow, but deletion becomes safe for keys that really were inserted.
No enumeration. The filter cannot list what it contains, because nothing is stored. There is no way to iterate, and no way to recover an element from the bits.
No resizing. The parameters are fixed at creation. Scalable bloom filters address this by chaining a series of filters, adding a new and larger one with a tighter error rate when the current one fills; a query checks all of them, so the cost grows with the chain length.
No count of occurrences. Membership is all it answers. A count-min sketch is the related structure for approximate frequency, using the same hashing idea with counters and returning an estimate that may overcount but never undercount.
Two comparisons worth being able to make. Against a hash set: the set is exact and supports deletion and iteration, but costs O(n) space proportional to the element sizes — take the set when it fits in memory, the filter when it does not. Against a cuckoo filter: it supports deletion, has better lookup locality, and is smaller at error rates below about 3%, at the cost of a more complex insertion that can fail when the structure is nearly full.
The decision rule: use a bloom filter when the data is too large to store exactly, the query is membership only, and a small false positive rate is acceptable because an authoritative check follows. If any of those three does not hold, use a hash set.
- A 4-bit counter saturates at 15; implementations leave it at 15 rather than wrap to 0
- Deleting a key that was never inserted corrupts a counting filter too, so check membership in the real store first
- For exact membership with deletion and iteration, use a hash table; for a probabilistic ordered structure, see skip lists