TExcelTAD
Home › Advanced & Succinct Data Structures › Bloom Filters and False Positives

Bloom Filters and False Positives

A Bloom filter (Bloom, 1970) answers "is xx in the set?" with one-sided error: a "no" is always right, a "yes" is wrong with a small probability ε\varepsilon, the false-positive rate. In exchange it uses about 1.44lg⁡(1/ε)1.44 \lg(1/\varepsilon) 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 kk-mers.

The structure

An array of mm bits, all 0, and kk hash functions h1,…,hkh_1, \ldots, h_k into {0,…,m−1}\{0, \ldots, m - 1\}.

  • INSERT(x)(x): set the bits h1(x),…,hk(x)h_1(x), \ldots, h_k(x) to 1.
  • QUERY(x)(x): answer "yes" if all kk bits h1(x),…,hk(x)h_1(x), \ldots, h_k(x) 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 kk 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).

bit array (m = 64): 35 of 64 bits setitem 16 set bits 2, 45, 54025%50%75%100%0816items insertedfalse-positive ratemeasured: (bits set / m)^k for this arrayestimate: (1 − e^(−kn/m))^k

The false-positive rate

Assume the hash functions are independent and uniform. After nn insertions, a fixed bit is still 0 with probability

p0=(1−1m)kn≈e−kn/mp_0 = \left(1 - \frac{1}{m}\right)^{kn} \approx e^{-kn/m}

A query for a non-member checks kk bits. If they were independent, it would see all of them set with probability

ε≈(1−p0)k≈(1−e−kn/m)k\varepsilon \approx (1 - p_0)^k \approx \left(1 - e^{-kn/m}\right)^k

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 mm the difference is tiny. A cleaner statement conditions on the filter: if a fraction ρ\rho of the bits is set, a fresh non-member is a false positive with probability exactly ρk\rho^k (its kk positions are independent of the filter), and ρ\rho is concentrated around 1−p01 - p_0. That is what the lab above displays next to the formula.

The best kk. For fixed m/nm/n, minimizing (1−e−kn/m)k(1 - e^{-kn/m})^k over kk gives

k∗=mnln⁡2,half of the bits set,ε∗=2−k∗≈0.6185m/nk^* = \frac{m}{n} \ln 2, \qquad \text{half of the bits set}, \qquad \varepsilon^* = 2^{-k^*} \approx 0.6185^{m/n}

so to reach error ε\varepsilon one needs m/n=lg⁡(1/ε)ln⁡2≈1.44lg⁡(1/ε)m/n = \frac{\lg(1/\varepsilon)}{\ln 2} \approx 1.44 \lg(1/\varepsilon) bits per element.

Derivation of the optimal k (sketch)

Write p=e−kn/mp = e^{-kn/m}, so k=−mnln⁡pk = -\frac{m}{n} \ln p and ln⁡ε=kln⁡(1−p)=−mnln⁡pln⁡(1−p)\ln \varepsilon = k \ln(1 - p) = -\frac{m}{n} \ln p \ln(1 - p). The product ln⁡pln⁡(1−p)\ln p \ln(1 - p) is symmetric in pp and 1−p1 - p and is maximized at p=12p = \frac12, which minimizes ε\varepsilon. Then k=mnln⁡2k = \frac{m}{n} \ln 2 and ε=2−k\varepsilon = 2^{-k}.

An implementation and a measurement

The program derives the kk positions from two 64-bit hashes by double hashing, gi(x)=h1(x)+i h2(x) mod mg_i(x) = h_1(x) + i \, h_2(x) \bmod m, which Kirsch and Mitzenmacher (2006) showed has the same asymptotic false-positive rate as kk independent hash functions. It inserts 2000 keys into m=16000m = 16000 bits (m/n=8m/n = 8), queries 20000 non-members, and compares the measured rate with the formula for several kk.

python · try it yourself
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 ρk\rho^k and the formula closely, and the best kk is near 5.55.5, 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: m/n=1.44lg⁡100≈9.6m/n = 1.44 \lg 100 \approx 9.6 bits per element and k=7k = 7.

cpp · try it yourself
#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 ε\varepsilon (and no false negatives) on sets of nn elements from a large universe needs at least nlg⁡(1/ε)n \lg(1/\varepsilon) bits (Carter, Floyd, Gill, Markowsky and Wegman, 1978). A Bloom filter uses 1.44 nlg⁡(1/ε)1.44\, n \lg(1/\varepsilon): 44% more than necessary. Newer filters get closer:

Filter Bits per element for error ε\varepsilon Deletions
lower bound lg⁡(1/ε)\lg(1/\varepsilon)
Bloom filter 1.44lg⁡(1/ε)1.44 \lg(1/\varepsilon) no (counting variant: about 4 times the space)
cuckoo filter (Fan et al. 2014): fingerprints in a cuckoo hash table about (lg⁡(1/ε)+3)/0.95(\lg(1/\varepsilon) + 3) / 0.95 yes
quotient filter (Bender et al. 2012) about (lg⁡(1/ε)+3)/α(\lg(1/\varepsilon) + 3)/\alpha at load α\alpha yes
xor filter (Graf and Lemire, 2020), static about 1.23lg⁡(1/ε)1.23 \lg(1/\varepsilon) no

The program tabulates bits per element for common error rates.

python · try it yourself
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 kk equals lg⁡(1/ε)\lg(1/\varepsilon): each of the kk probes halves the chance of a false positive.

Test yourself

A Bloom filter answers QUERY(x)(x) = yes. What can you conclude?

  1. xx is certainly in the set
  2. xx is in the set, or xx is a false positive (probability about ε\varepsilon for a non-member)
  3. xx is certainly not in the set
  4. Nothing

With m/n=10m/n = 10 bits per element, what is the best number of hash functions?

  1. About 3
  2. About 7, since k∗=(m/n)ln⁡2≈6.9k^* = (m/n)\ln 2 \approx 6.9
  3. 10
  4. About 14

How many bits per element does an optimally configured Bloom filter use for error ε\varepsilon, compared with the lower bound?

  1. The same, lg⁡(1/ε)\lg(1/\varepsilon)
  2. 1.44lg⁡(1/ε)1.44 \lg(1/\varepsilon), about 44% more than the lower bound lg⁡(1/ε)\lg(1/\varepsilon)
  3. 2lg⁡(1/ε)2 \lg(1/\varepsilon)
  4. lg⁡n\lg n