Bloom Filters
A Bloom filter answers one question with very little memory: is this item in the set? Its answers are either "definitely not" or "probably yes". It never gives a false negative, and it gives false positives at a rate you choose when you size it. That trade makes it one of the most useful data structures in system design.
| Where | What it avoids |
|---|---|
| LSM-tree databases (Cassandra, RocksDB, HBase, Bigtable) | Reading an SSTable from disk that can't contain the key |
| Web crawlers | Re-crawling URLs already seen (billions of them) |
| CDNs (Akamai) | Caching "one-hit wonders": only cache on the second request |
| Browsers / password checkers | Calling a server for every URL or password that isn't on a blocklist |
| Databases joins | Shipping rows to another node that can't match |
How it works
A Bloom filter is an array of m bits, all zero, and k hash functions.
- Add an item: compute its
khashes, each giving a bit position, and set those bits to 1. - Check an item: compute the same
kpositions. If any is 0, the item was never added. If all are 1, it was probably added; or other items happened to set all those bits.
add "cat": hashes -> 2, 7, 11 bits: 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 0
add "dog": hashes -> 4, 7, 13 bits: 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 0
check "fox": hashes -> 2, 4, 13 -> all 1 -> "probably yes" (a false positive!)
check "owl": hashes -> 3, 7, 11 -> bit 3 is 0 -> "definitely not"An implementation
We derive the k positions from one SHA-256 digest using the standard double hashing trick (h1 + i * h2), which behaves like k independent hashes:
import hashlib
class BloomFilter:
def __init__(self, m_bits, k_hashes):
self.m, self.k = m_bits, k_hashes
self.bits = bytearray((m_bits + 7) // 8)
def _positions(self, item):
digest = hashlib.sha256(item.encode()).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for p in self._positions(item):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, item):
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(item))
seen = BloomFilter(m_bits=1_000, k_hashes=7)
for url in ["example.com/a", "example.com/b", "example.com/c"]:
seen.add(url)
for url in ["example.com/a", "example.com/c", "example.com/zzz", "other.org/"]:
verdict = "probably seen" if seen.might_contain(url) else "definitely new"
print(f"{url:<16} {verdict}")
print("filter size:", len(seen.bits), "bytes")example.com/a probably seen
example.com/c probably seen
example.com/zzz definitely new
other.org/ definitely new
filter size: 125 bytes
Sizing: the false positive rate
With n items, m bits and k hashes, the false positive probability is about (1 - e^(-k·n/m))^k. The best k is (m/n)·ln 2, and for a target rate p you need about m = -n·ln(p) / (ln 2)^2 bits. In practice that's about 10 bits per item for 1%, and each extra 5 bits per item divides the rate by ten.
import math
def bits_needed(n, p):
return math.ceil(-n * math.log(p) / math.log(2) ** 2)
def best_k(m, n):
return max(1, round(m / n * math.log(2)))
n = 1_000_000_000 # one billion URLs
for p in [0.1, 0.01, 0.001, 0.0001]:
m = bits_needed(n, p)
print(f"p={p:<7} bits/item {m / n:5.2f} k={best_k(m, n):2} memory {m / 8 / 2**30:5.2f} GiB")
print("storing the URLs themselves (~60 bytes each):", f"{n * 60 / 2**30:.0f} GiB")p=0.1 bits/item 4.79 k= 3 memory 0.56 GiB
p=0.01 bits/item 9.59 k= 7 memory 1.12 GiB
p=0.001 bits/item 14.38 k=10 memory 1.67 GiB
p=0.0001 bits/item 19.17 k=13 memory 2.23 GiB
storing the URLs themselves (~60 bytes each): 56 GiB
A billion URLs at 1% false positives fit in about 1.1 GiB, compared with about 56 GiB to store the URLs themselves.
Checking the theory
Let's measure the real false positive rate of our filter against the formula:
import hashlib
import math
class BloomFilter:
def __init__(self, m, k):
self.m, self.k, self.bits = m, k, bytearray((m + 7) // 8)
def _positions(self, item):
d = hashlib.sha256(item.encode()).digest()
h1, h2 = int.from_bytes(d[:8], "big"), int.from_bytes(d[8:16], "big") | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for p in self._positions(item):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, item):
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(item))
n, m, k = 5_000, 48_000, 7 # ~9.6 bits per item
bf = BloomFilter(m, k)
for i in range(n):
bf.add(f"member-{i}")
false_negatives = sum(not bf.might_contain(f"member-{i}") for i in range(n))
trials = 20_000
false_positives = sum(bf.might_contain(f"stranger-{i}") for i in range(trials))
expected = (1 - math.exp(-k * n / m)) ** k
print("false negatives:", false_negatives)
print(f"false positive rate: measured {false_positives / trials:.2%}, formula {expected:.2%}")false negatives: 0
false positive rate: measured 1.12%, formula 1.00%
Limitations and relatives
- No deletion in a plain Bloom filter: clearing a bit might remove other items too. A counting Bloom filter uses small counters instead of bits; a cuckoo filter supports deletion and is often smaller at low error rates.
- It can't list its members or tell you how many there are (although HyperLogLog, a related sketch, estimates counts of distinct items in a few kilobytes).
- The false positive rate grows if you add more items than planned. Size for the future, or use a scalable Bloom filter that adds layers.
Tip: Use a Bloom filter as a cheap pre-check in front of an expensive exact check (disk, network, database). A "definitely not" skips the expensive step; a "probably yes" still does it.
Test yourself
A Bloom filter says an item is 'not present'. How reliable is that?
- It is certain
- It is right about 99% of the time
- It depends on the number of hash functions
- It is a guess
Roughly how many bits per item does a Bloom filter need for a 1% false positive rate?
- About 1
- About 10
- About 100
- About 1,000
Why can't you delete from a plain Bloom filter?
- Hash functions are one-way
- A bit can be shared by several items, so clearing it could remove others
- The array is read-only
- Deletion is too slow