Bloom Filters and False Positives
A Bloom filter (Bloom, 1970) answers "is in the set?" with one-sided error: a "no" is always right, a "yes" is wrong with a small probability , the false-positive rate. In exchange it uses about bits per element, independent of how large the elements are: under 10 bits per element for a 1% error, whether the elements are integers or URLs. Databases use Bloom filters to skip disk reads for keys that are not in a file (LSM trees in RocksDB, Cassandra, Bigtable), browsers and networks to pre-filter lookups, and genome assemblers to store huge sets of -mers.
The structure
An array of bits, all 0, and hash functions into .
- INSERT: set the bits to 1.
- QUERY: answer "yes" if all bits are 1, else "no".
An inserted element always finds its bits set, so there are no false negatives. A non-member is reported present when all its bits happen to have been set by other elements. Deletion is not supported: clearing a bit could remove other elements (counting Bloom filters replace bits by small counters to allow it).
The false-positive rate
Assume the hash functions are independent and uniform. After insertions, a fixed bit is still 0 with probability
A query for a non-member checks bits. If they were independent, it would see all of them set with probability
The bits are not quite independent, so this is an approximation; Bose et al. (2008) showed the formula slightly underestimates the true rate, but for practical the difference is tiny. A cleaner statement conditions on the filter: if a fraction of the bits is set, a fresh non-member is a false positive with probability exactly (its positions are independent of the filter), and is concentrated around . That is what the lab above displays next to the formula.
The best . For fixed , minimizing over gives
so to reach error one needs bits per element.
Derivation of the optimal k (sketch)
Write , so and . The product is symmetric in and and is maximized at , which minimizes . Then and .
An implementation and a measurement
The program derives the positions from two 64-bit hashes by double hashing, , which Kirsch and Mitzenmacher (2006) showed has the same asymptotic false-positive rate as independent hash functions. It inserts 2000 keys into bits (), queries 20000 non-members, and compares the measured rate with the formula for several .
import math, random
MASK = (1 << 64) - 1
def mix64(x): # splitmix64 finalizer: a fixed, well-mixing hash
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class BloomFilter:
def __init__(self, m, k):
self.m, self.k, self.bits = m, k, bytearray(m)
def _positions(self, x):
h1, h2 = mix64(x), mix64(x ^ 0x5851F42D4C957F2D) | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, x):
for p in self._positions(x): self.bits[p] = 1
def __contains__(self, x):
return all(self.bits[p] for p in self._positions(x))
rng = random.Random(1970)
n, m = 2000, 16000
members = rng.sample(range(10 ** 9), n)
others = []
while len(others) < 20000:
x = rng.randrange(10 ** 9, 2 * 10 ** 9) # disjoint from the members by construction
others.append(x)
print(f"n = {n}, m = {m} bits ({m // n} per element); best k = (m/n) ln 2 = {m / n * math.log(2):.2f}")
for k in [1, 2, 4, 6, 8, 12]:
bf = BloomFilter(m, k)
for x in members: bf.add(x)
assert all(x in bf for x in members) # no false negatives
fp = sum(x in bf for x in others) / len(others)
rho = sum(bf.bits) / m
print(f"k = {k:2}: bits set {rho:.3f}, measured {fp:.4f}, rho^k {rho ** k:.4f}, "
f"formula (1 - e^(-kn/m))^k {(1 - math.exp(-k * n / m)) ** k:.4f}")n = 2000, m = 16000 bits (8 per element); best k = (m/n) ln 2 = 5.55
k = 1: bits set 0.119, measured 0.1205, rho^k 0.1187, formula (1 - e^(-kn/m))^k 0.1175
k = 2: bits set 0.221, measured 0.0506, rho^k 0.0490, formula (1 - e^(-kn/m))^k 0.0489
k = 4: bits set 0.393, measured 0.0231, rho^k 0.0237, formula (1 - e^(-kn/m))^k 0.0240
k = 6: bits set 0.526, measured 0.0213, rho^k 0.0212, formula (1 - e^(-kn/m))^k 0.0216
k = 8: bits set 0.636, measured 0.0268, rho^k 0.0267, formula (1 - e^(-kn/m))^k 0.0255
k = 12: bits set 0.780, measured 0.0510, rho^k 0.0506, formula (1 - e^(-kn/m))^k 0.0483
The measured rate follows and the formula closely, and the best is near , where about half the bits are set. Too few hash functions leave the filter sparse but each query checks few bits; too many fill the filter.
In C++
A Bloom filter over std::vector<bool> with the same splitmix64 double hashing, sized for a 1% error: bits per element and .
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
std::uint64_t mix64(std::uint64_t x) {
x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
return x ^ (x >> 31);
}
class BloomFilter {
std::vector<bool> bits;
std::uint64_t m;
int k;
public:
BloomFilter(std::uint64_t m_, int k_) : bits(m_), m(m_), k(k_) {}
void add(std::uint64_t x) {
std::uint64_t h1 = mix64(x), h2 = mix64(x ^ 0x5851F42D4C957F2DULL) | 1;
for (int i = 0; i < k; ++i) bits[(h1 + i * h2) % m] = true;
}
bool contains(std::uint64_t x) const {
std::uint64_t h1 = mix64(x), h2 = mix64(x ^ 0x5851F42D4C957F2DULL) | 1;
for (int i = 0; i < k; ++i) if (!bits[(h1 + i * h2) % m]) return false;
return true;
}
};
int main() {
const std::uint64_t n = 100000;
const double eps = 0.01;
std::uint64_t m = static_cast<std::uint64_t>(std::ceil(n * std::log2(1 / eps) / std::log(2.0)));
int k = static_cast<int>(std::lround(double(m) / n * std::log(2.0)));
BloomFilter bf(m, k);
std::mt19937_64 rng(1970);
for (std::uint64_t i = 0; i < n; ++i) bf.add(rng() >> 1); // members: top bit 0
std::uint64_t fp = 0, trials = 1000000;
for (std::uint64_t i = 0; i < trials; ++i) fp += bf.contains((rng() >> 1) | (1ULL << 63)); // non-members
std::printf("n = %llu, m = %llu bits (%.2f per element), k = %d\n", static_cast<unsigned long long>(n),
static_cast<unsigned long long>(m), double(m) / n, k);
std::printf("false-positive rate %.4f (target %.2f)\n", double(fp) / trials, eps);
}n = 100000, m = 958506 bits (9.59 per element), k = 7
false-positive rate 0.0099 (target 0.01)
How close to optimal is a Bloom filter?
Any structure for approximate membership with false-positive rate (and no false negatives) on sets of elements from a large universe needs at least bits (Carter, Floyd, Gill, Markowsky and Wegman, 1978). A Bloom filter uses : 44% more than necessary. Newer filters get closer:
| Filter | Bits per element for error | Deletions |
|---|---|---|
| lower bound | ||
| Bloom filter | no (counting variant: about 4 times the space) | |
| cuckoo filter (Fan et al. 2014): fingerprints in a cuckoo hash table | about | yes |
| quotient filter (Bender et al. 2012) | about at load | yes |
| xor filter (Graf and Lemire, 2020), static | about | no |
The program tabulates bits per element for common error rates.
import math
print(f"{'error':>8} {'lower bound':>12} {'Bloom':>8} {'best k':>7} {'xor filter':>11}")
for eps in [0.1, 0.01, 0.001, 1e-6]:
lb = math.log2(1 / eps)
print(f"{eps:>8g} {lb:12.2f} {lb / math.log(2):8.2f} {lb:7.1f} {1.23 * lb:11.2f}") error lower bound Bloom best k xor filter
0.1 3.32 4.79 3.3 4.09
0.01 6.64 9.59 6.6 8.17
0.001 9.97 14.38 10.0 12.26
1e-06 19.93 28.76 19.9 24.52
The best equals : each of the probes halves the chance of a false positive.
Test yourself
A Bloom filter answers QUERY = yes. What can you conclude?
- is certainly in the set
- is in the set, or is a false positive (probability about for a non-member)
- is certainly not in the set
- Nothing
With bits per element, what is the best number of hash functions?
- About 3
- About 7, since
- 10
- About 14
How many bits per element does an optimally configured Bloom filter use for error , compared with the lower bound?
- The same,
- , about 44% more than the lower bound