Sub topic 10
Bloom filters: skipping files that cannot contain a key
This chapter assumes you know how the LSM read path works. A lookup checks the memtable, then each SSTable from newest to oldest. It also assumes you can read short Python programs and know what a hash function is.
The problem: misses are expensive
A read for a key that exists stops at the first table that holds it. A read for a key that does not exist must check every table. Even with a sparse index, each check costs at least one disk read. If the store has 20 SSTables, one miss can cost 20 reads.
A Bloom filter is a compact structure that answers "is this key possibly in this file?" It is kept in memory, one per SSTable, so most tables can be skipped without touching the disk.
How a Bloom filter works
A Bloom filter is a bit array plus several hash functions.
- Add: hash the key with each function. Each hash picks a bit position. Set those bits to 1.
- Query: hash the key the same way. If any of those bits is 0, the key is definitely absent. If all are 1, the key might be present.
The answers are asymmetric:
| Filter says | Meaning |
|---|---|
| Not present | The key is certainly not in the file. |
| Possibly present | The key may be in the file, or other keys may have set the same bits. |
A false positive costs one wasted disk read. A false negative never happens, because bits are only ever set, never cleared.
import hashlib
class BloomFilter:
def __init__(self, num_bits=1024, num_hashes=3):
self.num_bits = num_bits
self.num_hashes = num_hashes
self.bits = bytearray((num_bits + 7) // 8)
def _positions(self, key):
for i in range(self.num_hashes):
digest = hashlib.sha256(f"{i}:{key}".encode()).digest()
yield int.from_bytes(digest[:8], "big") % self.num_bits
def add(self, key):
for p in self._positions(key):
self.bits[p // 8] |= 1 << (p % 8)
def might_contain(self, key):
return all(self.bits[p // 8] & (1 << (p % 8)) for p in self._positions(key))
bf = BloomFilter()
for k in ["apple", "banana", "cherry"]:
bf.add(k)
print(bf.might_contain("banana")) # True
print(bf.might_contain("zebra")) # almost certainly FalseThe _positions method derives each hash by prefixing the key with the function's index. This is a simple way to get several independent hashes from one algorithm.
Where it fits in the read path
An SSTable is immutable, so its filter is built once, when the table is written during a flush or compaction. It never needs deletion support. Each table in the read path is then guarded by its filter.
Sizing and common errors
The false-positive rate depends on bits per key and on the number of hashes. As a rule of thumb, about 10 bits per key with 7 hashes gives roughly a 1% false-positive rate. More bits lower the rate but use more memory.
Common mistakes:
- Using a fixed size for every table. A filter that is too small for its table fills with 1s and answers "maybe" for everything. Size it from the number of keys in the table.
- Expecting help with range scans. A filter tests exact keys only. It cannot rule out a range.
- Expecting help with hits. If the key exists, you still read the table. Filters pay off on misses and on keys found only in older tables.
- Forgetting tombstones. A deleted key's tombstone is still a key in the table, so it must be added to the filter. Otherwise the read could skip the tombstone and find an older value.
Exercise
A table holds 1,000 keys, and its Bloom filter has 100 bits that are all set to 1. What does might_contain return for a key that was never added, and why is that a problem?
Show answer
It returns True, because every bit position the key hashes to is already 1. The filter never rules anything out, so every lookup reads the table anyway and the filter saves no disk reads. The fix is to size the filter from the table's key count, for example about 10 bits per key.