Skip to content
BytePatterns

Bloom Filter Sizing

MediumSystem Design#bloom-filter#double-hashing~25m

Problem

A cache sits in front of a database, and lookups for keys that do not exist at all go straight through it and hit the database every time. A Bloom filter of known keys can stop most of them: it answers "definitely absent" or "maybe present". Given the expected number of keys n and the false-positive rate p you can accept, return the number of bits m = ceil(-n ln p / (ln 2)²) and the number of hash functions k = round(m / n × ln 2), at least 1. Then build the filter, deriving its k bit positions from one SHA-256 digest, and check that it never misses a key it holds while its false-positive rate stays close to p.

Examples

Input:  n = 1000, p = 0.01
Output: (9586, 7)
Why:    about 9.6 bits and 7 hashes per key for a 1% false-positive rate
Input:  n = 1000000, p = 0.001
Output: (14377588, 10)
Why:    each tenfold drop in p costs about 4.8 more bits per key
Input:  n = 10, p = 0.5
Output: (15, 1)
Why:    edge case, a very loose target still needs at least one hash function

Hints

0 / 3

Stuck on the idea rather than the code? Caching covers it.