Bloom Filters Explained: Sizing, False Positive Rates, and When a Probabilistic Set Pays Off
A Bloom filter answers "have I seen this before? " in a few bits per item, at the cost of occasional false positives. Learn how it works, how to size it from a target error rate, and the mistakes that quietly ruin its accuracy.
Many systems spend a surprising amount of time asking a question whose answer is usually no. Does this row key exist in this file on disk? Has this user already seen this article? Is this URL on a list of known bad sites? Answering with an exact set means storing every item, and when the set holds hundreds of millions of entries that memory bill gets large fast. A Bloom filter, described by Burton Bloom in 1970, trades a small, tunable chance of a wrong yes for a structure that needs only a handful of bits per item.
This guide walks through how the structure works, the three formulas you need to size one, a small Python implementation you can run and measure, how the Redis Bloom commands map onto the same math, and the situations where a Bloom filter is the wrong tool.
The core idea: a bit array and k hash functions
A Bloom filter is an array of m bits, all starting at zero, plus k independent hash functions that each map an item to one position in that array. To add an item, you hash it k times and set each of the k resulting bits to one. To test an item, you hash it the same k ways and look at those bits.
- If any of the k bits is zero, the item was never added. This answer is certain: a Bloom filter has no false negatives.
- If all k bits are one, the item was probably added. Other items may have set those same bits by coincidence, so this answer can be wrong.
- Both operations cost O(k) hash computations no matter how many items the filter already holds.
That asymmetry is the whole design. The filter is useful whenever a definite no lets you skip expensive work and an occasional false yes only costs you the work you would have done anyway, such as a disk read that finds nothing.
The math that sizes a filter
After inserting n items into m bits with k hashes, the chance that a particular bit is still zero is roughly e^(-kn/m). A false positive happens when all k probed bits are one, so the false positive probability is approximately (1 - e^(-kn/m))^k. This approximation assumes the hash functions behave independently and uniformly, which good hashes come close to in practice.
Working backward from a target error rate p and an expected item count n gives the two numbers you actually configure:
- Number of bits: m = -n * ln(p) / (ln 2)^2, which works out to about 1.44 * log2(1/p) bits per item.
- Number of hash functions: k = (m / n) * ln 2, which simplifies to roughly log2(1/p) when the array is optimally sized.
- Notice what is missing: the size of the items themselves. A 20-byte key and a 2-kilobyte URL cost the same number of bits.
Plugging in common targets gives a useful mental table. The values below come straight from those formulas and match the sizing table in the Redis documentation.
- 1% false positives: about 9.6 bits per item and 7 hashes, roughly 11.4 MiB for 10 million items.
- 0.1% false positives: about 14.4 bits per item and 10 hashes, roughly 17.1 MiB for 10 million items.
- 0.01% false positives: about 19.2 bits per item and 14 hashes, roughly 22.9 MiB for 10 million items.
Each tenfold improvement in accuracy costs only about 4.8 extra bits per item. That is why a Bloom filter at 0.01% can still be an order of magnitude smaller than an exact set of the same keys; Redis estimates around 40 bytes per IP address in a plain set versus about 19 bits in a filter. The trade-off is not free in theory, though: a classic Bloom filter uses about 44% more space than the information-theoretic minimum for its error rate, which is the gap that newer designs such as cuckoo and quotient filters try to close.
A worked example in Python
The implementation below sizes itself from a capacity and error rate, stores bits in a bytearray, and derives all k positions from one SHA-256 digest. Instead of running k separate hash functions, it splits the digest into two 64-bit values h1 and h2 and computes position i as (h1 + i * h2) mod m. This double hashing trick is a common way to get k well-spread indices from a single hash call. Forcing h2 to be odd simply guarantees it is never zero, which would otherwise make every probe land on the same bit.
import hashlib
import math
class BloomFilter:
def __init__(self, capacity, error_rate):
# m = -n * ln(p) / (ln 2)^2 bits, k = (m / n) * ln 2 hashes
self.m = math.ceil(-capacity * math.log(error_rate) / math.log(2) ** 2)
self.k = max(1, round(self.m / capacity * 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 # odd, so never zero
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))
if __name__ == "__main__":
bf = BloomFilter(capacity=100_000, error_rate=0.01)
print(f"bits={bf.m}, bytes={len(bf.bits)}, hashes={bf.k}")
for i in range(100_000):
bf.add(f"user-{i}")
missed = sum(not bf.might_contain(f"user-{i}") for i in range(100_000))
false_pos = sum(bf.might_contain(f"other-{i}") for i in range(100_000))
print(f"false negatives: {missed}")
print(f"false positive rate: {false_pos / 100_000:.4f}")Running this script with Python 3 prints a filter of 958,506 bits (119,814 bytes) using 7 hashes, zero false negatives, and a measured false positive rate of 0.0097 across 100,000 keys that were never inserted. That is within noise of the 1% target, and the whole filter is smaller than 120 KB for 100,000 entries.
What happens when you overfill it
A fixed-size Bloom filter never refuses an insert. It just gets less accurate as more bits flip to one, until in the limit every query returns yes. Using the same formula with the example filter above (m = 958,506 bits, k = 7) shows how quickly the error rate degrades once you pass the planned capacity:
- 50,000 items (half capacity): about 0.03% false positives.
- 100,000 items (planned capacity): about 1%.
- 150,000 items: about 5.8%.
- 200,000 items (double): about 15.8%.
- 300,000 items (triple): about 43.6%, at which point the filter is barely filtering.
The failure is silent. Nothing throws an error; downstream systems simply do more unnecessary work. That makes the capacity estimate the most important input you give a Bloom filter, and monitoring the count of inserted items against it a basic production requirement.
How Redis handles growth
Redis exposes Bloom filters through commands such as BF. RESERVE, BF. ADD and BF. EXISTS. BF. RESERVE takes the same two inputs as the formulas above, an error rate and a capacity, and by default creates a scaling filter. When the first sub-filter reaches capacity, Redis stacks a new, larger sub-filter on top, multiplying the size by the EXPANSION factor, which defaults to 2. New sub-filters use extra hash functions so the overall error rate stays near the target.
BF.RESERVE seen:articles 0.001 1000000
BF.ADD seen:articles "article:84213"
BF.EXISTS seen:articles "article:84213"
BF.EXISTS seen:articles "article:99999"Scaling avoids the silent accuracy collapse, but it is not free. Each check walks the stack of sub-filters, so lookups slow down roughly in proportion to how many layers have been added, and every layer carries its own memory overhead. The Redis documentation recommends reserving a realistic capacity up front, keeping EXPANSION at 2 or higher when the final count is unknown, and setting it to 1 when you know the count and want to save memory. The NONSCALING option disables growth entirely for a slightly smaller fixed filter; check the documentation for your Redis version on exactly how it behaves at capacity.
Where Bloom filters show up in real systems
- Storage engines: Bigtable, HBase, Cassandra and ScyllaDB keep a filter per on-disk file so a read for a missing key can skip files that cannot contain it.
- CDN caching: Akamai has used filters to avoid writing objects to disk cache until they are requested a second time, keeping one-hit wonders out.
- Browsers: Chrome historically used a local filter as a fast pre-check before asking a server whether a URL was malicious.
- Recommendations and feeds: checking whether a user has already been shown an item before showing it again.
- Distributed joins: shipping a compact filter of one side's keys to filter the other side before moving data across the network.
Common mistakes
- Trying to delete items. Clearing a bit may also erase evidence of other items, creating false negatives. Use a counting Bloom filter (several times more memory) or a cuckoo filter if you need removal.
- Guessing capacity. An undersized fixed filter degrades silently, as the overfill list above shows. Size for expected peak, not today's count.
- Using weak or correlated hashes. If the k positions are not well spread, the real false positive rate will be far above the formula. Use a solid hash and derive indices carefully.
- Changing hash functions or sizes between writers and readers. Two services that disagree on m, k or the hash will produce garbage answers, so treat those parameters as part of the data format.
- Combining filters with different parameters. A bitwise OR of two filters gives an exact union only when both share the same m and the same hash functions.
When not to use a Bloom filter
- When a false positive is dangerous rather than merely wasteful, for example granting access because a token looked revoked-free. Always back a filter yes with an authoritative check.
- When the set is small enough to store exactly. A few thousand keys in a hash set is simpler and has no error at all.
- When you need to list, count precisely or retrieve the stored items. A Bloom filter only remembers fingerprints of membership, not the items.
- When items must be removed frequently. A cuckoo filter, which Redis also offers, supports deletion and faster lookups at the cost of slower inserts.
A quick sizing checklist
- Estimate the peak number of items n, then add headroom.
- Pick the error rate p by asking what one false positive costs downstream.
- Compute m = -n * ln(p) / (ln 2)^2 and k = (m / n) * ln 2, rounding k to a whole number.
- Fix the hash function and the parameters as part of your storage format.
- Track inserted count versus capacity, and rebuild or scale before the error rate drifts.
Used this way, a Bloom filter is one of the best returns on memory in systems engineering: a few megabytes standing guard in front of disks, networks and databases, turning most expensive lookups into a definite no.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter