Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Bloom Filters & Their Successors

Set membership with false positives, and cuckoo and xor filters.

A Bloom filter answers "have I seen this before?" with about 9.6 bits per item at a 1% error rate, whatever the items are. Information theory says 6.6 bits would do. This lesson computes the false-positive rate exactly, proves that lower bound, and follows fifty years of successors that close part of the gap while adding what Bloom filters lack: deletions, cache locality and speed.

What you’ll learn

  • Express a Bloom filter's false-positive rate exactly, and prove that the classic formula is a lower bound on it.
  • Prove that any approximate-membership structure needs about nlog⁡2(1/ε)n\log_2(1/\varepsilon) bits, and place Bloom filters' factor 1/ln⁡2≈1.441/\ln 2 \approx 1.44 against static and dynamic lower bounds.
  • Compare counting, partitioned and blocked Bloom filters by space, false-positive rate and cache misses.
  • Explain how quotient, cuckoo and xor filters store fingerprints, and choose among them by space, deletions and static or dynamic use.

The false-positive rate, exactly

Fix the set SS of nn inserted keys and a key x∉Sx \notin S. The false-positive rate ε\varepsilon is the probability, over the hash functions, that the Bloom filter answers "present" for xx. Model the kk functions as independent and uniform over the mm bits, as Bloom did. Then the whole analysis turns on one random quantity: the number XX of bits that are set after the knkn insertions.

DerivationThe exact rate, and why the classic formula is low
  1. ε=E ⁣[(Xm)k]\varepsilon = \E\!\left[\left(\frac Xm\right)^{k}\right]

    Condition on XX. The kk positions probed for xx are uniform and independent of the filter's contents. Given X=iX = i set bits, all kk probes hit set bits with probability (i/m)k(i/m)^k, so

  2. Pr⁡[X=i]=(mi) i!  S(kn,i)mkn\Pr[X = i] = \frac{\binom mi\, i!\; S(kn, i)}{m^{kn}}

    The distribution of XX. The knkn settings are uniform throws into mm bits. Exactly ii bits are hit when the throws map onto some ii-set, which a Stirling number of the second kind S(⋅,⋅)S(\cdot,\cdot) counts:

  3. (1−(1−1m)kn)k=(E ⁣[Xm])k ≤ E ⁣[(Xm)k]=ε\left(1 - \left(1 - \tfrac1m\right)^{kn}\right)^{k} = \left(\E\!\left[\tfrac Xm\right]\right)^{k} \ \le\ \E\!\left[\left(\tfrac Xm\right)^{k}\right] = \varepsilon

    The classic formula plugs in the mean. Each bit is set with probability 1−(1−1/m)kn1 - (1-1/m)^{kn}, which is therefore E[X/m]\E[X/m], and Bloom's formula is (E[X/m])k(\E[X/m])^k. The map t↦tkt \mapsto t^k is convex, so Jensen's inequality gives

  4. ε/(1−(1−1m)kn)k ⟶ 1(m→∞)\varepsilon \Big/ \left(1 - \left(1 - \tfrac1m\right)^{kn}\right)^{k} \ \longrightarrow\ 1 \qquad (m \to \infty)

    The inequality is strict for k≥2k \ge 2 because XX is genuinely random: the classic formula underestimates the false-positive rate (Bose et al., 2008). Since XX stays within O(m)O(\sqrt m) of its mean, the gap vanishes as mm grows with n/mn/m and kk fixed:

mmnnkkExact ε\varepsilonClassic (1−(1−1/m)kn)k(1-(1-1/m)^{kn})^k(1−e−kn/m)k(1-e^{-kn/m})^k
8220.17780.17120.1548
16220.05290.05180.0489
64640.010160.009810.00956
1001070.008940.008400.00819
Computed from the exact formula. The gap is a few percent for toy filters and negligible for real ones with millions of bits; the e−kn/me^{-kn/m} shortcut is lower still.

Optimizing kk with the approximation gives k∗=(m/n)ln⁡2k^* = (m/n)\ln 2, at which half the bits are set and ε≈2−k∗\varepsilon \approx 2^{-k^*}. In practice kk is rounded to an integer, and the kk positions need not come from kk separate functions: gi(x)=h1(x)+i h2(x) mod mg_i(x) = h_1(x) + i\,h_2(x) \bmod m for i=0,…,k−1i = 0, \dots, k-1 has the same asymptotic false-positive rate (Kirsch & Mitzenmacher, 2006), so two hash computations suffice.

Check your understanding

Even with truly random hash functions, why is Bloom's classic formula (1−(1−1/m)kn)k\big(1 - (1-1/m)^{kn}\big)^k a lower bound on the exact false-positive rate?

  1. Real hash functions are not truly random
  2. The formula ignores that two keys can set the same bit
  3. It uses e−kn/me^{-kn/m} in place of (1−1/m)kn(1-1/m)^{kn}
  4. The fraction of set bits X/mX/m is random, and E[(X/m)k]≥(E[X/m])k\E[(X/m)^k] \ge (\E[X/m])^k by convexity
Show the answer

D. The fraction of set bits X/mX/m is random, and E[(X/m)k]≥(E[X/m])k\E[(X/m)^k] \ge (\E[X/m])^k by convexity

Given the number XX of set bits, the rate is exactly (X/m)k(X/m)^k. Averaging a convex function of a random quantity gives at least the function of its average. Fillings with more set bits than average hurt more than fillings with fewer help.

How much space must any filter use?

DerivationProof by counting
  1. ∣A(σ)∣ ≤ n+ε(u−n)=:v\abs{A(\sigma)} \ \le\ n + \varepsilon(u-n) =: v

    What a memory state accepts. Each of the 2b2^b memory states σ\sigma answers "yes" on some set A(σ)⊆UA(\sigma) \subseteq U. If σ\sigma represents SS, then S⊆A(σ)S \subseteq A(\sigma) and at most ε(u−n)\varepsilon(u-n) other keys are accepted:

  2. 2b(vn) ≥ (un)2^b \binom vn \ \ge\ \binom un

    One state serves few sets. A state can represent only nn-subsets of A(σ)A(\sigma), at most (vn)\binom vn of them, and each of the (un)\binom un possible sets needs a state:

  3. (un)/(vn)=∏i=0n−1u−iv−i ≥ (uv)n\binom un \Big/ \binom vn = \prod_{i=0}^{n-1}\frac{u-i}{v-i} \ \ge\ \left(\frac uv\right)^{n}

    Estimate the ratio. Each factor u−iv−i\frac{u-i}{v-i} increases with ii when u≥vu \ge v, so it is at least its value at i=0i = 0:

  4. b ≥ nlog⁡2uv ⟶ nlog⁡21εb \ \ge\ n\log_2\frac uv \ \longrightarrow\ n\log_2\frac1\varepsilon

    Conclude. Take logarithms. For a universe much larger than n/εn/\varepsilon, u/v→1/εu/v \to 1/\varepsilon:

A Bloom filter uses nlog⁡2(1/ε)/ln⁡2n\log_2(1/\varepsilon)/\ln 2 bits, so its overhead is exactly the factor 1/ln⁡2≈1.441/\ln 2 \approx 1.44. Is the bound reachable? For a static set, yes: structures built from perfect hashing and retrieval reach (1+o(1)) nlog⁡2(1/ε)(1+o(1))\,n\log_2(1/\varepsilon) bits (Dietzfelbinger & Pagh, 2008; Porat, 2009). For a set that grows by insertions, no: Lovett and Porat (2010) proved that a dynamic structure needs C(ε) nlog⁡2(1/ε)C(\varepsilon)\,n\log_2(1/\varepsilon) bits for some C(ε)>1C(\varepsilon) > 1 depending only on ε\varepsilon, a bound sharpened since.

Predict before you look

At ε=0.1%\varepsilon = 0.1\%, how many bits per element could an optimal static filter save compared with an optimally tuned Bloom filter?

Show the answer

4.4 bits

The Bloom filter needs 1.44×log⁡21000≈1.44×9.97≈14.41.44 \times \log_2 1000 \approx 1.44 \times 9.97 \approx 14.4 bits per element, and the lower bound is log⁡21000≈10.0\log_2 1000 \approx 10.0. The difference, 0.44×9.97≈4.40.44 \times 9.97 \approx 4.4 bits per element, is the prize that fingerprint filters compete for.

Engineering Bloom filters

Three engineering problems recur, and each has a standard fix.

  • Deletion. A counting Bloom filter (Fan, Cao, Almeida & Broder, 2000) keeps a small counter per position, incremented on insert and decremented on delete. Four-bit counters overflow only with negligible probability at the usual loads, so it costs about four times the space. Deleting a key that was never inserted silently creates false negatives.
  • Cache misses. The kk probes of a standard filter land in up to kk different cache lines. A blocked Bloom filter (Putze, Sanders & Singler, 2007) first hashes the key to one block the size of a cache line, then sets all kk bits inside it: one cache miss per query.
  • Hashing cost. Double hashing h1+i h2h_1 + i\,h_2 derives all kk positions from two hash values, and a partitioned filter gives each function its own slice of m/km/k bits, so a key's kk positions are always distinct.
VariantSpaceFalse-positive rateMemory accesses per query
Standard1.44log⁡2(1/ε)1.44\log_2(1/\varepsilon) bits per keybaselineup to kk cache misses
Countingabout 4×4\times standardsame; deletions allowedup to kk
Partitionedsameslightly higherup to kk
Blocked (512-bit blocks)samehigher, increasingly so at small ε\varepsilon1 cache miss
cpp
#include <cstdint>
#include <vector>

// Blocked Bloom filter: each key touches one 512-bit block, i.e. one 64-byte cache line.
struct BlockedBloom {
    std::vector<uint64_t> words;                  // 8 words per block
    uint64_t blocks;
    int k;                                        // bits per key, at most 7 here
    BlockedBloom(uint64_t nblocks, int k) : words(8 * nblocks), blocks(nblocks), k(k) {}

    static uint64_t mix(uint64_t x) {             // splitmix64 finalizer
        x += 0x9e3779b97f4a7c15ULL;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
        x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
        return x ^ (x >> 31);
    }
    void add(uint64_t key) {
        uint64_t h = mix(key), base = (h % blocks) * 8, g = mix(h);
        for (int i = 0; i < k; i++, g >>= 9)      // 9 bits: word (3) and bit (6)
            words[base + (g >> 6 & 7)] |= 1ULL << (g & 63);
    }
    bool contains(uint64_t key) const {
        uint64_t h = mix(key), base = (h % blocks) * 8, g = mix(h);
        for (int i = 0; i < k; i++, g >>= 9)
            if (!(words[base + (g >> 6 & 7)] >> (g & 63) & 1)) return false;
        return true;
    }
};

With 10610^6 keys, 10 bits per key and k=7k = 7, this filter measured a false-positive rate of 0.97%, against 0.82% for a standard filter of the same size. The splitmix64 finalizer mixes well but has no formal guarantee; add a secret random seed to the key when inputs may be adversarial.

Why the penalty? A block receives a Poisson number of keys with mean λ=512 n/m\lambda = 512\,n/m, and the false-positive rate averages a convex function of the block's load, the same Jensen effect as before:

εblocked≈∑j≥0e−λλjj!(1−(1−1512)kj)k.\varepsilon_{\text{blocked}} \approx \sum_{j \ge 0} e^{-\lambda}\frac{\lambda^j}{j!}\left(1 - \left(1 - \tfrac{1}{512}\right)^{kj}\right)^{k}.

At 10 bits per key this predicts 0.96%, matching the measurement. At 20 bits per key with k=14k = 14 it is about three times the standard rate, so blocked filters usually spend a bit or two more per key.

Fingerprint filters: quotient, cuckoo and xor

Bloom filters spread each key over kk bits. Their successors store one short fingerprint per key instead, an ff-bit hash f(x)f(x) with ff about log⁡2(1/ε)\log_2(1/\varepsilon) plus a few bits, inside a compact hash table. A key that was never inserted is a false positive only if it meets an equal fingerprint where it looks, which happens with probability about 2−f2^{-f} per comparison.

A quotient filter (Bender et al., 2012, building on Cleary's compact hash tables of 1984) splits a fingerprint into a qq-bit quotient, used as the home slot, and an rr-bit remainder, stored in a slot. Collisions are resolved by linear probing; the remainders of each home slot form a sorted run, and three metadata bits per slot tell the runs apart. A lookup scans one short contiguous region, deletion works, and two filters merge like sorted lists.

A cuckoo filter (Fan, Andersen, Kaminsky & Mitzenmacher, 2014) is a cuckoo hash table of fingerprints with buckets of b=4b = 4 entries. Key xx may live in bucket i1=h(x)i_1 = h(x) or in i2=i1⊕h(f(x))i_2 = i_1 \oplus h(f(x)). This partial-key cuckoo hashing computes either bucket from the other and the fingerprint alone, so the filter can evict and relocate fingerprints without knowing the keys. A lookup reads two buckets, so ε≤2b/2f\varepsilon \le 2b/2^f, and deletion removes one copy of f(x)f(x). Tables fill to about 95% before insertions start to fail, for (log⁡2(1/ε)+3)/α(\log_2(1/\varepsilon) + 3)/\alpha bits per key, or one bit less with "semi-sorted" buckets; that version beats a Bloom filter below roughly a 3% false-positive rate.

DerivationXor filters: build by peeling, query by XOR
  1. B[h0(x)]⊕B[h1(x)]⊕B[h2(x)]=f(x)B[h_0(x)] \oplus B[h_1(x)] \oplus B[h_2(x)] = f(x)

    The equations. An xor filter (Graf & Lemire, 2020) is an array BB of c≈1.23 nc \approx 1.23\,n slots of ff bits. Each key xx has three slots h0(x),h1(x),h2(x)h_0(x), h_1(x), h_2(x), one in each third of the array, and the filter must satisfy, for every key of the set,

  2. cn=1.23 > 1.222≈the peeling threshold\frac cn = 1.23 \ >\ 1.222 \approx \text{the peeling threshold}

    Peel. Repeatedly take a slot used by exactly one remaining key, push that (key, slot) pair on a stack and delete the key. The keys' slot triples form a random 3-uniform hypergraph, and peeling removes every key with high probability once c/nc/n exceeds the threshold of about 1.2221.222; otherwise, draw new hash functions and retry:

  3. B[s]←f(x)⊕B[h0(x)]⊕B[h1(x)]⊕B[h2(x)]⊕B[s]B[s] \leftarrow f(x) \oplus B[h_0(x)] \oplus B[h_1(x)] \oplus B[h_2(x)] \oplus B[s]

    Assign in reverse. Pop the pairs and set each popped slot so that its key's equation holds. That slot belonged to no key still present when its key was peeled, so it occurs in no equation already satisfied, and no later assignment touches a slot of a settled key:

  4. ε=2−f,1.23 log⁡21ε bits per key\varepsilon = 2^{-f}, \qquad 1.23\,\log_2\tfrac1\varepsilon \ \text{bits per key}

    Query. Read three slots and compare their XOR with f(x)f(x). For a key outside the set the XOR is unrelated to its fingerprint, so a false positive has probability 2−f2^{-f}, at 1.23f1.23f bits per key: within 23% of the lower bound. The price is that the filter is static. Binary fuse filters (Graf & Lemire, 2022) place the three slots in nearby segments, which speeds up construction and brings the space within 13% of the bound.

FilterBits per keyDeletesGrows after buildLookup reads
Bloom1.44log⁡2(1/ε)1.44\log_2(1/\varepsilon)noyesup to kk bits
Counting Bloomabout 4×1.44log⁡2(1/ε)4 \times 1.44\log_2(1/\varepsilon)yesyesup to kk counters
Quotient(r+3)/α(r+3)/\alpha, with ε\varepsilon at most about 2−r2^{-r}yesyes; mergeable, resizableone contiguous run
Cuckoo (b=4b = 4)(log⁡2(1/ε)+3)/α(\log_2(1/\varepsilon)+3)/\alpha, α≈95%\alpha \approx 95\%yesyes, until about 95% full2 buckets
Xor1.23log⁡2(1/ε)1.23\log_2(1/\varepsilon)nono (static)3 slots
Binary fuseabout 1.13log⁡2(1/ε)1.13\log_2(1/\varepsilon)nono (static)3 slots
Lower boundlog⁡2(1/ε)\log_2(1/\varepsilon)———
Real implementations round fingerprints to whole bits, so the formulas are evaluated at integer ff or rr.

Where filters live, and the frontier

Filters earn their keep wherever a quick "no" saves an expensive operation. Bloom's own 1970 example was hyphenation: most words follow simple rules, and a filter of the exceptions decides, without touching the disk, which words need the slow dictionary. Today, log-structured merge (LSM) key-value stores such as LevelDB, RocksDB and Cassandra keep a filter for each sorted file on disk, so a lookup skips every file that cannot contain its key. Web caches have exchanged Bloom filters that summarize their contents, and network devices use filters in packet processing.

The guarantee Pr⁡[false positive]≤ε\Pr[\text{false positive}] \le \varepsilon is for a query fixed in advance. A query that happens to be a false positive fails every time it is repeated, and an attacker who can test queries can collect false positives and replay them. Adaptive filters (Bender, Farach-Colton, Goswami, Johnson, McCauley & Singh, 2018) repair false positives as they are discovered, so the bound holds even for queries chosen after seeing earlier answers. Learned Bloom filters put a trained classifier in front of a small backup filter (Kraska et al., 2018); their guarantees depend on the query distribution (Mitzenmacher, 2018).

Key takeaways

  • With ideal hash functions a Bloom filter's false-positive rate is exactly E[(X/m)k]\E[(X/m)^k], where XX counts the set bits; the classic formula (1−(1−1/m)kn)k(1-(1-1/m)^{kn})^k is its Jensen lower bound, accurate for large mm.
  • Any approximate-membership structure needs about nlog⁡2(1/ε)n\log_2(1/\varepsilon) bits (Carter et al., 1978). Bloom filters use 1.441.44 times that; static structures reach (1+o(1))(1+o(1)) times, and dynamic ones provably need a constant factor more (Lovett & Porat, 2010).
  • Counting filters add deletions at about four times the space, blocked filters cut each query to one cache miss for a somewhat higher error rate, and double hashing reduces the work to two hash computations.
  • Fingerprint filters store about log⁡2(1/ε)\log_2(1/\varepsilon) plus a few bits per key: quotient filters (sorted runs, mergeable), cuckoo filters (deletions, two bucket reads) and xor or binary fuse filters (static, within 23% and 13% of the bound).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A filter must have false-positive rate ε=1/64\varepsilon = 1/64 over a huge universe. At least how many bits per stored element does any such structure need?

  1. about 1.44
  2. about 6
  3. about 8.7
  4. about 64
Show the answer

B. about 6

The Carter et al. bound is nlog⁡2(1/ε)=6nn\log_2(1/\varepsilon) = 6n bits. An optimally tuned Bloom filter needs 1.44×6≈8.71.44 \times 6 \approx 8.7 bits per element; static fingerprint-based structures come close to 6.

Question 2

A blocked Bloom filter puts all kk bits of a key into one 512-bit block. At the same total size and kk, why is its false-positive rate higher than a standard filter's?

  1. Blocks receive a random, roughly Poisson, number of keys, and overloaded blocks raise the average rate more than underloaded ones lower it
  2. Bits inside one cache line are correlated in hardware
  3. It uses fewer hash functions
  4. It is not higher; only the speed changes
Show the answer

A. Blocks receive a random, roughly Poisson, number of keys, and overloaded blocks raise the average rate more than underloaded ones lower it

The rate is an average of a convex function of each block's load, the same Jensen effect as in the exact analysis. At 10 bits per key and k=7k = 7 the rate rises from about 0.82% to about 0.96%, and the penalty grows at low error rates, so blocked filters often add a bit or two per key.

Question 3

You need an approximate-membership filter that supports deletions without multiplying the space by four. Which fits?

  1. A standard Bloom filter
  2. An xor filter
  3. A blocked Bloom filter
  4. A cuckoo filter
Show the answer

D. A cuckoo filter

A cuckoo filter stores one fingerprint per key in one of two buckets, so deleting a key removes one copy of its fingerprint. Quotient filters also support deletion.

Further reading

  • L. Carter, R. Floyd, J. Gill, G. Markowsky & M. Wegman, "Exact and approximate membership testers," Proceedings of the 10th ACM Symposium on Theory of Computing (1978), 59–65.
  • P. Bose, H. Guo, E. Kranakis, A. Maheshwari, P. Morin, J. Morrison, M. Smid & Y. Tang, "On the false-positive rate of Bloom filters," Information Processing Letters 108(4) (2008), 210–213.
  • B. Fan, D. G. Andersen, M. Kaminsky & M. D. Mitzenmacher, "Cuckoo filter: Practically better than Bloom," Proceedings of ACM CoNEXT (2014), 75–88.
  • T. M. Graf & D. Lemire, "Xor filters: Faster and smaller than Bloom and cuckoo filters," ACM Journal of Experimental Algorithmics 25 (2020).
  • M. Mitzenmacher & E. Upfal, Probability and Computing, 2nd ed. (Cambridge University Press, 2017), on balls into bins and Bloom filters.