15.8 A Bloom filter
The corpus pipeline in Data Engineering must drop exact duplicate paragraphs from millions of documents. A Python set of paragraph hashes costs 8 bytes of hash plus about 60 bytes of overhead per entry. A Bloom filter answers “have I seen this?” in about 10 bits per paragraph, with no false negatives and a false-positive rate you choose. The dedup stage in Exact dedup: paragraph hashes, a Bloom screen, and a sort-merge confirm then confirms every “seen” answer exactly with a sort-merge on the full hashes, so a false positive costs time, never data.
Concepts from other sections (4)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Block hash: a hash over token ids chained with the parent hash, independent of the payload format. Read more: 12.5 The KV format v2 migration in Systems Engineering
- Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation in Mathematics
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics in Mathematics
- Counting Bloom filter: a Bloom filter whose bits are replaced by small counters, so an element can be deleted by decrementing its counters; it supports deletion at the cost of several times the space. Read more: Chapter 14: Probabilistic data structures
This section derives the sizing formulas and the double-hashing scheme from first principles, works a 20-bit filter by hand down to its 35 serialized bytes, and then builds the filter in Rust. The serialized format matters as much as the filter. Languages in this system meet only over processes and files, and the one Bloom filter on the serving path, the dedup screen, is written in Python. No other code calls this Rust filter; what the two share is the byte layout fixed by formats/bloom.md. This section is optional and stands on its own.
The math comes from Mathematics: the false-positive rate and the optimal , and FNV-1a and the SplitMix finalizer. The solution is bloom.rs, and the independent Python screen is _Bloom in python/corpus/dedup.py.
Learning objectives
- Explain why a Bloom filter has no false negatives and derive its false-positive rate .
- Size a filter for items at rate with and .
- Generate probes from two hashes by double hashing, and explain why is forced odd.
- Merge filters by OR and serialize them to a fixed, portable byte layout.
- Validate untrusted bytes before using them.
Bits and hash functions
Section titled “Bits and hash functions”The notation for this section:
| Symbol | Meaning | Type |
|---|---|---|
| items inserted (or expected) | u64 | |
| bits in the filter | u64, | |
| hash functions (bits per item) | u32, | |
| target false-positive rate | real in | |
| an item: a byte string | &[u8] | |
| the bit positions of | u64 in | |
| the fraction of bits set | real in |
Insert sets bits ; contains answers yes when all are set. An inserted item’s bits stay set forever, because nothing clears bits, so there are no false negatives. A non-member is reported present only if all of its bits were set by other items.
The false-positive rate and the optimal k
Section titled “The false-positive rate and the optimal k”How often does that happen? Model each of the bit choices as uniform and independent. One bit stays 0 after all of them with probability , so the fraction of set bits is about , and a fresh item’s probes all hit set bits with probability
More hash functions mean more checks per query but more bits set. Minimizing over gives , where exactly half the bits are set, and . Solving for :
rounding half away from zero. That is about bits per item: 9.6 bits at 1%, 14.4 at 0.1%. For example, 4 items at 10% need 20 bits and 3 hashes.
Two hashes make k
Section titled “Two hashes make k”Computing independent hashes per item is slow. Kirsch and Mitzenmacher showed that (mod ) loses nothing asymptotically. The format fixes:
FNV-1a 64 is the same hash as the KV block hash of formats/kv-block.md. Start from the offset basis 0xcbf29ce484222325; for each byte, XOR it in, then multiply by the prime 0x100000001b3 (mod ). Multiplying first and XORing after is FNV-1, a different hash. mix64 is the SplitMix64 finalizer, a bijection that spreads every input bit over every output bit. Forcing odd keeps the probes distinct when is a power of two. Bit lives in byte at bit position , least significant bit first.
What can be measured
Section titled “What can be measured”The approximation above assumes independent bits. Given an actual filter, the exact probability that a random fresh item is a false positive is with the measured fraction of set bits, because each probe lands on a uniform bit. Over fresh items the count of false positives is then Binomial, with mean and standard deviation . A statistical test can ask the count to lie within 3 standard deviations, which a correct filter fails about 0.3% of the time.
Union and bytes
Section titled “Union and bytes”Two filters with the same and (and so the same hash positions) merge by bitwise OR: the result has exactly the bits that inserting both sets would set. n_inserted counts insert calls, and a union adds the counts.
to_bytes writes the 32-byte little-endian header (magic TLBF, version 1, , , a reserved zero, n_inserted) and then the bytes of bits; from_bytes rejects anything else. Every implementation of the format produces the same 35 bytes for the worked example below.
The Python pipeline’s _Bloom in python/corpus/dedup.py is a separate implementation with the same sizing and probes; it keeps the bits in memory and does not serialize. For the same items, both set the same bits.
Working it by hand
Section titled “Working it by hand”Call with_rate(4, 0.1). Then , so ; , so . The bit array is bytes.
Insert cat: and , which give (the format page lists every item’s positions). dog gives . After inserting both, the set bits are 0 and 3 (byte 0: ), 11, 13, 14 (byte 1: bits 3, 5, 6 of that byte, ), and 17 (byte 2: bit 1, ): 09 68 02.
Query bird: it probes . Bit 7 is clear, so contains(b"bird") is false. Six of 20 bits are set, , and a fresh item’s chance of a false positive is .
to_bytes is the 35 bytes
54 4c 42 46 01 00 00 00 14 00 00 00 00 00 00 00 "TLBF", version 1, m = 2003 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 k = 3, reserved 0, n_inserted = 209 68 02 the bitsThe interface
Section titled “The interface”// rust/crates/tl-ds/src/bloom.rs (formats/bloom.md)pub const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; pub const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;pub const MAGIC: [u8; 4] = *b"TLBF"; pub const VERSION: u32 = 1; pub const HEADER_LEN: usize = 32;pub const MAX_BITS: u64 = 1 << 40;pub enum BloomError { BadParams(String), Mismatch(String), Format(String) } // Display + Errorpub fn fnv1a64(bytes: &[u8]) -> u64;pub fn mix64(z: u64) -> u64;pub fn optimal_m(n: u64, p: f64) -> u64;pub fn optimal_k(m: u64, n: u64) -> u32;pub fn predicted_fp_rate(m: u64, k: u32, n: u64) -> f64;#[derive(Clone, Debug, PartialEq, Eq)] pub struct Bloom { /* m, k, n_inserted, bits */ }impl Bloom { pub fn with_rate(n: u64, p: f64) -> Result<Bloom, BloomError>; // BadParams unless n >= 1, 0 < p < 1 pub fn new(m: u64, k: u32) -> Result<Bloom, BloomError>; // 1 <= m <= 2^40, k >= 1 pub fn m(&self) -> u64; pub fn k(&self) -> u32; pub fn n_inserted(&self) -> u64; pub fn bit_positions(&self, item: &[u8]) -> Vec<u64>; pub fn insert(&mut self, item: &[u8]); pub fn contains(&self, item: &[u8]) -> bool; pub fn union(&mut self, other: &Bloom) -> Result<(), BloomError>; // Mismatch when m or k differ pub fn count_ones(&self) -> u64; pub fn to_bytes(&self) -> Vec<u8>; pub fn from_bytes(b: &[u8]) -> Result<Bloom, BloomError>;}Building it step by step
Section titled “Building it step by step”Read the solution in this order: hashing and sizing first, then the bit array, then bytes. Seven observations shape it.
- “Have I seen this?” with no false negatives means a set bit can never be cleared: the structure only ever ORs bits in. A miss is certain; a hit is probabilistic.
- The false-positive rate is , the chance that independent probes all land on set bits. Minimizing it for a given gives (half the bits set), and inverting gives . The ceiling matters: flooring makes the filter short of its target. For the worked example, 19.17 becomes 20 bits and 3.466 becomes 3 hashes.
- hashes per item are expensive; two are enough. gives probes from two hashes. must be odd so that, when is a power of two, the probes are distinct (an odd step generates every residue).
- must not be a simple function of ‘s low bits, or the two probes correlate. Running through the SplitMix64 finalizer, a bijection that mixes every bit, makes look independent at the cost of a few multiplies.
- Filters built in different processes and languages must be interchangeable, so everything that decides a bit is fixed by the format: FNV-1a (xor, then multiply), mix64, the wrap-around arithmetic mod before mod , and LSB-first bit numbering. The header records , , and the count so a filter can be validated and merged.
- Two filters with the same and probe the same positions for every item, so OR is exactly the filter of the union of the sets; different or have no meaningful union and must be refused.
- Bytes from a file are untrusted.
from_byteschecks every header field and that the length is exactly ; otherwise a latercontainscould index past the bit array.
Hashing and sizing
Section titled “Hashing and sizing”Each line is one formula from the derivation; the casts and wrapping_mul make the arithmetic mod explicit, which is what other implementations must reproduce.
/// FNV-1a 64 over `bytes`: for each byte, xor it in, then multiply.pub fn fnv1a64(bytes: &[u8]) -> u64 { let mut h = FNV_OFFSET; for &b in bytes { h ^= b as u64; // xor FIRST: this is what makes it FNV-1a, not FNV-1 h = h.wrapping_mul(FNV_PRIME); } h}
/// The SplitMix64 finalizer: a bijection on u64 that mixes every bit.pub fn mix64(z: u64) -> u64 { let z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); let z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31)}
/// ceil(-n ln p / (ln 2)^2): round UP, or the filter misses its target rate.pub fn optimal_m(n: u64, p: f64) -> u64 { let ln2 = std::f64::consts::LN_2; (-(n as f64) * p.ln() / (ln2 * ln2)).ceil() as u64}
/// max(1, round(m / n * ln 2)); f64::round rounds half away from zero.pub fn optimal_k(m: u64, n: u64) -> u32 { let k = (m as f64 / n as f64 * std::f64::consts::LN_2).round(); // round, not truncate: 6.64 -> 7 if k < 1.0 { 1 } else { k as u32 }}Construction
Section titled “Construction”Construction validates before allocating. !(p > 0.0 && p < 1.0) is written that way so that NaN, for which every comparison is false, is rejected too.
pub fn with_rate(n: u64, p: f64) -> Result<Bloom, BloomError> { if n < 1 { return Err(BloomError::BadParams(format!("n must be >= 1, got {n}"))); } if !(p > 0.0 && p < 1.0) { // also catches NaN return Err(BloomError::BadParams(format!("p must be in (0, 1), got {p}"))); } let m = optimal_m(n, p); Bloom::new(m, optimal_k(m, n)) // new() enforces 1 <= m <= 2^40, k >= 1}
pub fn new(m: u64, k: u32) -> Result<Bloom, BloomError> { if m == 0 || k == 0 { /* ... */ } if m > MAX_BITS { /* ... */ } // refuse a 128 GiB+ allocation from a bad config Ok(Bloom { m, k, n_inserted: 0, bits: vec![0; m.div_ceil(8) as usize] })}Probes, insert, contains, union
Section titled “Probes, insert, contains, union”bit_positions is the single definition of where an item’s bits are; insert and contains both use it, so they cannot disagree.
/// g_i = (h1 + i * h2) mod 2^64 mod m, h1 = fnv1a64(item), h2 = mix64(h1) | 1.pub fn bit_positions(&self, item: &[u8]) -> Vec<u64> { let h1 = fnv1a64(item); let h2 = mix64(h1) | 1; // odd: distinct probes when m is a power of two (0..self.k as u64).map(|i| h1.wrapping_add(i.wrapping_mul(h2)) % self.m).collect()}
pub fn insert(&mut self, item: &[u8]) { for g in self.bit_positions(item) { self.bits[(g / 8) as usize] |= 1 << (g % 8); // byte g/8, bit g%8 from the LSB } self.n_inserted += 1;}
pub fn contains(&self, item: &[u8]) -> bool { self.bit_positions(item) .into_iter() .all(|g| self.bits[(g / 8) as usize] & (1 << (g % 8)) != 0) // every probe must be set}
pub fn union(&mut self, other: &Bloom) -> Result<(), BloomError> { if self.m != other.m || self.k != other.k { return Err(BloomError::Mismatch(/* ... */)); // different probes: no meaningful union } for (a, b) in self.bits.iter_mut().zip(&other.bits) { *a |= *b; // OR: a member of either set stays present } self.n_inserted += other.n_inserted; Ok(())}Serialization
Section titled “Serialization”The header is written field by field in little-endian, so the layout does not depend on struct padding or host byte order. from_bytes checks in the order that makes each read safe: length before any field, then magic, then the rest.
pub fn to_bytes(&self) -> Vec<u8> { let mut out = Vec::with_capacity(HEADER_LEN + self.bits.len()); out.extend_from_slice(&MAGIC); // "TLBF" out.extend_from_slice(&VERSION.to_le_bytes()); // u32 out.extend_from_slice(&self.m.to_le_bytes()); // u64 out.extend_from_slice(&self.k.to_le_bytes()); // u32 out.extend_from_slice(&0u32.to_le_bytes()); // reserved out.extend_from_slice(&self.n_inserted.to_le_bytes()); // u64: 32 bytes so far out.extend_from_slice(&self.bits); out}
pub fn from_bytes(b: &[u8]) -> Result<Bloom, BloomError> { let fail = |why: String| Err(BloomError::Format(why)); if b.len() < HEADER_LEN { return fail(/* ... */); } // before reading any field if b[0..4] != MAGIC { return fail(/* ... */); } // ... read version, m, k, reserved, n (little-endian) ... if version != VERSION { return fail(/* ... */); } if m == 0 || k == 0 { return fail(/* ... */); } if m > MAX_BITS { return fail(/* ... */); } if reserved != 0 { return fail(/* ... */); } let want = HEADER_LEN as u64 + m.div_ceil(8); if b.len() as u64 != want { return fail(/* ... */); } // exact: never trust m alone Ok(Bloom { m, k, n_inserted: n, bits: b[HEADER_LEN..].to_vec() })}The full solution is bloom.rs.
Why this design
Section titled “Why this design”insert and contains are : one pass of FNV over the item, one mix64, and bit operations. Space is bits, about per item; union is .
Against the alternatives: a hash set of paragraph hashes is exact and simple, but costs about 68 bytes per entry in Python against about 1.2 bytes per entry for a 1% filter. Because dedup confirms every positive exactly anyway, a filter’s false positives cost a little time and never correctness. independent hash functions give the same false-positive rate asymptotically, at times the hashing work, and with algorithms every other implementation must reproduce bit for bit. Counting Bloom filters and cuckoo filters support deletion, which dedup never needs; a counting filter costs 4 or more times the space. As for storage, Vec<bool> is 8 times larger, and a u64 word array is equally compact in memory but makes the on-disk layout depend on word order; bytes with LSB-first bits are the layout the format fixes.
Two tradeoffs are accepted. bit_positions allocates a small Vec per call, which is simple and testable; a hot loop could iterate instead. And the filter has fixed capacity: inserting far more than items raises the rate as , and the header’s n_inserted lets a reader see that it happened.
Testing it and what can go wrong
Section titled “Testing it and what can go wrong”A correct filter handles these cases:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| The hand example’s sizing and bits | unit | , , the positions of cat, dog, bird, the 35 bytes | the code, the format page, and the worked example agree |
| Hash function values by hand | golden | FNV-1a of "", “a”, “cat”; mix64 of 0 and 1 | every implementation sets the same bits |
| Sizing formulas | unit | and for five , including the rounding of ; byte length | the screen is as small as the target allows |
| Bad parameters are errors | boundary | , , NaN, , are BadParams | a bad config fails at start, not with a 128 GiB allocation |
| No false negatives | property | 5,000 random items found in their filter, after a byte round trip, and in the union | dedup never keeps a duplicate it has seen |
| The false-positive rate is within three sigma | statistical | 100,000 fresh items: false positives within 3 sd of , and below 2% at a 1% design | the filter is as good as its sizing promises |
| Union is the filter of both sets | unit | OR of two filters equals the filter of both; counts add; mismatched or refused | the dedup stage merges per-shard screens |
| Golden bytes match the format | golden | 10 reference cases (empty items, odd , ): bytes and probe answers | every implementation of the format writes the same bytes |
from_bytes rejects malformed input | boundary | bad magic, version, , , reserved, short, long, inconsistent length | a corrupt file is refused, not misread |
A model property-test suite (proptest with a fixed seed and no failure files: the worked example bytes, the sizing table, “every inserted item is present”, “bytes round-trip”, “union equals one filter of both sets”, a mismatched union, and malformed bytes) is in ds08_bloom.rs.
The pitfalls, many of which make the bytes disagree with every other implementation:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| Flooring instead of taking the ceiling | the filter is a bit short: the rate misses its target and bytes differ from every other implementation | optimal_m uses .ceil() |
Using mix64(h1) without forcing it odd | probes coincide when is a power of two; bits differ from the format | bit_positions uses mix64(h1) | 1 |
| Numbering bits from the most significant end | bytes read back wrong in every other implementation | bit g is 1 << (g % 8) in byte g / 8 |
| Truncating instead of rounding | 6.64 becomes 6 hashes; more false positives | optimal_k uses .round() |
Forgetting to add the counts in union | the header’s n_inserted is wrong after a merge | union adds other.n_inserted |
| Setting fewer than bits on insert | false negatives: duplicates slip through dedup | insert sets every position bit_positions returns |
| Dropping the term | all probes hit one bit: the rate is , not | each probe is h1 + i * h2 |
AND instead of OR in union | the union forgets members of both sets | union ORs the bit arrays |
Trusting the length in from_bytes | a truncated file loads and later panics on an out-of-range bit | from_bytes requires the exact length |
| FNV-1 (multiply, then XOR) instead of FNV-1a | every position differs from the format and from kv-block.md hashes | fnv1a64 xors before it multiplies |
Where this leads
Section titled “Where this leads”Nothing calls this filter: the dedup stage in Exact dedup never calls Rust. Its Python exact_dedup sizes its own screen at about 10 bits per paragraph with these formulas, inserts each paragraph hash, and confirms every positive exactly; for the same items both screens set the same bits. Read that section with this one in mind.
Production systems take the same idea in several directions:
- datatrove exact dedup uses sharded hashing with sort-merge and no filter at all, trading disk for certainty (
src/datatrove/pipeline/dedup/exact_substrings.py,sentence_dedup.py). - RedisBloom offers scalable filters that add layers as grows past the design (
src/sb.c). - Cuckoo filters and xor filters support deletion and use about 20% fewer bits at low false-positive rates (Fan et al., 2014; Graf and Lemire, 2020).
- Parquet and ORC store split-block Bloom filters per column chunk, read before a scan (the Apache Parquet
BloomFilter.mdspec).
Further reading
Section titled “Further reading”- Bloom, Space/Time Trade-offs in Hash Coding with Allowable Errors (1970).
- Kirsch and Mitzenmacher, Less Hashing, Same Performance: Building a Better Bloom Filter (2006).
- Broder and Mitzenmacher, Network Applications of Bloom Filters: A Survey (2004).
Key terms
Section titled “Key terms”- Bloom filter: an -bit array with hash probes per item, answering membership with no false negatives.
- False positive: a non-member whose probes all land on bits set by other items.
- Double hashing: generating probes from two hashes.
- FNV-1a: a byte-at-a-time hash that XORs each byte in and then multiplies by a prime.
- SplitMix64 finalizer (mix64): a bijection on 64-bit words that mixes every input bit into every output bit.
- Union: the bitwise OR of two filters with the same and .
Summary
Section titled “Summary”- A Bloom filter is bits and hash functions: insert sets bits,
containschecks them, so a member is never missed and a non-member is reported present with probability about . - For items at rate , bits and hashes: 4 items at 10% need 20 bits and 3 hashes.
- Two hashes are enough: (double hashing) with = FNV-1a 64 and = the SplitMix finalizer of , forced odd.
- Union is bitwise OR of two filters with the same and , which is exactly the filter of both sets.
- A fixed byte layout makes the filter portable: every implementation of the format produces the same 35 bytes for the worked example.
Review questions
Section titled “Review questions”- Why is forced odd?
Answer
When $m$ is a power of two, the probes $h_1 + i\,h_2 \bmod m$ cycle with period $m / \gcd(h_2, m)$. An even $h_2$ shares a factor of 2 with $m$, so probes can repeat within $k$ steps (in the extreme $h_2 \equiv 0$, all $k$ probes hit one bit and the rate is $f$, not $f^k$). An odd $h_2$ is coprime to $m$, so the $k$ probes are distinct. - Why can a Bloom filter never give a false negative, and what single change to the code would break that?
Answer
`insert` sets exactly the bits `contains` checks (both call `bit_positions`), and nothing ever clears a bit. Any change that makes the two disagree breaks it: setting fewer than $k$ bits in `insert`, or AND instead of OR in `union` (which clears bits set by only one side). - Why does
optimal_mtake the ceiling andoptimal_kround?Answer
$m$ is a resource: fewer bits than $-n \ln p / (\ln 2)^2$ means the rate exceeds the target, so it must round up. $k$ is an optimum of a smooth function, so the nearest integer is best; truncation (6.64 to 6) lands further from the optimum and raises the rate. Both choices are also fixed by the format so every implementation builds the same filter. - Why does
from_bytesrequire the length to equal exactly, rather than at least that?Answer
Shorter would leave `bits` too small, and a probe near $m$ would index past it and panic later, far from the cause. Longer means the file is not what its header says (wrong $m$, a concatenation, corruption); accepting it would misread data silently. Exact equality refuses both at load time. - In the worked example, why is the false-positive chance of a fresh item rather than the designed ?
Answer
The filter was sized for 4 items but holds only 2, so only 6 of 20 bits are set: $f = 0.3$ and $f^3 = 0.027$. The design rate is reached when the filter holds its full $n$.