Sub topic 10
Where Bloom filters are used in practice
This chapter assumes you know how a Bloom filter inserts and queries items, why it has no false negatives, and how to size it with m and k. Here we look at where those properties pay off and where they don't.
The pattern: a cheap guard in front of an expensive check
Nearly every real use follows one shape. A Bloom filter sits in front of a slow or costly operation, such as a disk read, a network call, or a database query. The filter answers first.
- If it says "no", the item is definitely absent, so you skip the expensive step.
- If it says "maybe", you do the expensive step and get the exact answer.
A false positive costs one wasted lookup. A false negative would cause wrong results, which is why the one-sided error matters here.
Common use cases
| Use case | What the filter guards | Why a false positive is tolerable |
|---|---|---|
| LSM-tree databases (for example Cassandra, RocksDB, HBase) | Reads of on-disk table files | An extra disk read, not a wrong answer |
| Web caches and CDNs | Caching objects seen only once | The object is cached one request early |
| Unsafe-URL or password checks | A large blocklist | A "maybe" triggers an exact check |
| Duplicate detection in crawlers | Whether a URL was visited | A rare page may be skipped |
| Distributed joins | Sending only rows that might match | Some extra rows are sent and discarded |
Databases: skipping disk reads
An LSM-tree database stores data in many immutable files. A lookup for a missing key would otherwise check every file. Each file keeps a Bloom filter in memory. Most files answer "no" immediately, so a read touches only the files that might hold the key.
Blocklists: a small local filter
A browser can keep a Bloom filter of known bad URLs. Most URLs are safe and get a fast "no" with no network call. Only a "maybe" triggers a request to a server that holds the exact list.
Checking the guard in code
This sketch reuses the BloomFilter class from earlier chapters. It counts how often the filter saves a lookup.
import hashlib
import math
class BloomFilter:
def __init__(self, expected_items, false_positive_rate):
self.m = math.ceil(-expected_items * math.log(false_positive_rate) / (math.log(2) ** 2))
self.k = max(1, round((self.m / expected_items) * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
digest = hashlib.sha256(item.encode("utf-8")).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 pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def might_contain(self, item):
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
store = {f"user{i}" for i in range(10_000)} # stands in for a slow database
bf = BloomFilter(expected_items=10_000, false_positive_rate=0.01)
for key in store:
bf.add(key)
store_reads = 0
wasted_reads = 0
queries = [f"missing{i}" for i in range(100_000)] # all absent
for key in queries:
if bf.might_contain(key):
store_reads += 1 # the expensive lookup happens
if key not in store:
wasted_reads += 1 # a false positive
print(f"queries: {len(queries)}")
print(f"store reads: {store_reads}")
print(f"wasted reads: {wasted_reads}")With a 1% target rate, expect about 1,000 wasted reads out of 100,000 absent queries. Without the filter, all 100,000 would hit the store.
When a Bloom filter is the wrong choice
Check these conditions before you use one.
- Most queries are for present items. The filter then saves little, because nearly every answer is "maybe".
- The check is already cheap. If the real lookup is an in-memory hash table read, the filter adds complexity for no gain.
- You need exact answers. A "maybe" is not an answer. The design must have a fallback.
- Items must be removed. A standard filter cannot delete. Later chapters cover this.
- You cannot estimate n. The false positive rate rises as the filter fills past its planned size.
Exercise
Exercise
A service checks a remote API for each incoming ID. About 90% of IDs are absent from the API's data, and each call takes 50 ms. A Bloom filter with a 1% false positive rate sits in front of the API. For 1,000,000 requests, roughly how many API calls are made? Assume the filter holds every present ID.
Show answer
100,000 requests have present IDs (10%), and all of them pass the filter, so they cause 100,000 calls. Of the 900,000 absent IDs, about 1% (9,000) are false positives and also cause calls. The total is about 109,000 calls, down from 1,000,000. That saves roughly 89% of the calls.
Exercise
Why is a Bloom filter a poor fit when 95% of queries are for items that are in the set?
Show answer
Present items always pass the filter, so 95% of queries still reach the expensive check. The filter only avoids work for absent items, which are the other 5%. It saves little and adds memory use and code.