Discussion on Hacker News.

Bloom filters are one of those simple and handy engineering tools that any engineer should have in their toolbox.

It is a space-efficient probabilistic data structure that represents a set and allows you to test if an element is in it.

They are really simple to construct and look like this:

The cool thing is that to achieve such space-efficiency Bloom filters allow for errors with an arbitrarily small probability!

Remarkably, a Bloom filter that represents a set of 1 1 1 million items with an error rate of 0.01 0.01 0.01 requires only 9585059 9585059 9585059 bits ( ~ 1.14 MB \text{\textasciitilde}1.14 \text{MB} ~1.14MB)! Irrespective of the length of each element in S S S!

There’re many kinds of Bloom filters. We’ll cover the Standard Bloom Filter as it is the basis for the others and also serves as a nice intro for more advanced probabilistic set-membership data structures such as Cuckoo Filter.

What’s on our menu for today?

All code snippets can be found on Github.

Academic fellows might want to review Bloom’s original 1970 1970 1970 paper []. Strikingly, Bloom has only 3 3 3 references in his article!

Standard Bloom Filters

A Bloom filter represents a set S = { x 1 , x 2 , … , x n } S=\{x_1, x_2, \ldots, x_n\} S={x1​,x2​,…,xn​} of n n n elements by an array of m m m bits (initially set to 0 0 0). Lets call it B B B.

B = [ b 1 , b 2 , b 3 , b 4 , … , b _ m − 1 , b m ] B = [b_1, b_2, b_3, b_4, \ldots, b\_{m-1}, b_m] B = [ b 1 ​ , b 2 ​ , b 3 ​ , b 4 ​ , … , b _ m − 1 , b m ​ ]

A Bloom filter uses k k k independent hash functions h 1 , … , h k h_1, \ldots, h_k h1​,…,hk​ that are assumed to be uniformly distributed over the range { 1 , … , m } \{1, \ldots, m \} {1,…,m}.

Standard Bloom filters have two operations:

1. Add( x x x) - Add x x x to the Bloom filter.

For 1 ≤ i ≤ k set B [ h i ( x ) ] = 1 \text{For} \space 1 \leq i \leq k \space \text{set} \space B[h_i(x)]=1 For 1 ≤ i ≤ k set B [ h i ​ ( x ) ] = 1

To represent set S S S by Bloom filter B B B we need to Add all x ∈ S x \in S x∈S.

2. Contains( y y y) - Check if y y y is in the Bloom filter.

If for all 1 ≤ i ≤ k , B [ h i ( y ) ] = = 1 return true, otherwise false \text{If for all} \space 1 \leq i \leq k \space, \space B[h_i(y)]==1 \\ \text{return true, otherwise false} If for all 1 ≤ i ≤ k , B [ h i ​ ( y ) ] = = 1 return true, otherwise false

To make things clearer, here is a hand-drawn illustration (heavily inspired by Julia Evans (@b0rk) blog illustrations):

False-Negatives and False-Positives

If Contains( y y y) returns False, clearly y y y is not a member of S S S. This property is why we say Bloom filters have zero false-negatives. A situation where Contains( e e e) is False and e ∈ S e \in S e∈S simply can’t happen (because otherwise all relevant bits were 1 1 1).

If Contains( y y y) returns True, y y y may or may not be a member of S S S. This is why we say that Bloom filters may have false-positives, because a situation where Contains( e e e) is True and e ∉ S e

otin S e∈/​S can occur.

Arbitrarily Small Probability of Error (False-Positive)

The cool thing about Bloom filters is that based on n n n (number of elements in the set S S S) and a chosen probability of false positives P F P P_{FP} PFP​ we can derive optimal k k k (number of hash functions) and m m m (length of bit vector B B B).

These are the formulae (we derive those in the Appendix):

k = − ln ⁡ P F P ln ⁡ 2 , m = − n ln ⁡ P F P ( ln ⁡ 2 ) 2 k=-{\frac {\ln P_{FP}}{\ln 2}}, \enspace m=-{\frac {n\ln P_{FP}}{(\ln 2)^{2}}} k = − ln 2 ln P F P ​ ​ , m = − ( ln 2 ) 2 n ln P F P ​ ​

A very cool result is that the optimal number of hash functions k k k depends only on the false-positive probability P F P P_{FP} PFP​.

Lets play with it:

import math def optimal_km ( n , p ) : ln2 = math . log ( 2 ) lnp = math . log ( p ) k = - lnp / ln2 m = - n * lnp / ( ( ln2 ) ** 2 ) return int ( math . ceil ( k ) ) , int ( math . ceil ( m ) ) print ( optimal_km ( 10 ** 6 , 0.01 ) )

Remarkably, a Bloom filter that represents a set of 1 1 1 million items with a false-positive probability of 0.01 0.01 0.01 requires only 9585059 9585059 9585059 bits ( 1.14 MB ~1.14 \text{MB} 1.14MB) and 7 7 7 hash functions. Only 9.6 9.6 9.6 bits per element! ( 9585059 1000000 \frac{9585059}{1000000} 10000009585059​).

Toy Implementation

The first thing that comes to mind is how exactly do we get a family of hash functions h 1 , … , h k h_1, \ldots, h_k h1​,…,hk​ that are uniformly distributed?

Since our objective is learning and we are not aiming for efficiency, we can simply build our family of hash functions on top of an existing hash function as a primitive. Such as SHA256.

One such construction is the following:

h i ( s ) = SHA256 ( i ∣ ∣ s ) mod m h_i(s) = \text{SHA256}(i\space||\space s) \text{ mod } m h i ​ ( s ) = SHA256 ( i ∣ ∣ s ) mod m

Where:

i i i - the number of the hash function.

- the number of the hash function. s s s - the string to be hashed.

- the string to be hashed. m m m - the length of the bit vector.

- the length of the bit vector. ∣ ∣ || ∣ ∣ - string concatenation.

And with Python:

def h_i ( i , m , s ) : return int ( sha256 ( bytes ( [ i ] ) + s ) . hexdigest ( ) , 16 ) % m

Recall that the standard bloom filter had two simple operations:

class bloom_filter : def __init__ ( self , m , k , h = h_i ) : self . m = m self . k = k self . h = h self . bits = bitarray ( self . m ) def add ( self , s ) : for i in range ( self . k ) : self . bits [ self . h ( i , self . m , s ) ] = 1 def contains ( self , s ) : for i in range ( self . k ) : if self . bits [ self . h ( i , self . m , s ) ] == 0 : return False return True

Example: Efficiently Verify Compromised SSH Keys

In 2008, Luciano Bello discovered that Debian’s OpenSSL random number generator was seriously flawed and depended only on a process id integer.

Without getting into the gory details, essentially it means that between 2006 and 2008, cryptographic keys that were generated using OpenSSL on Debian-based operating systems were limited to 32768 different possible keys given their type (e.g. RSA ) and size (e.g. 1024 bit ).

Fortunately, g0tmi1k (@g0tmi1k), generated all possible compromised keys and uploaded them to a repo.

Say we’d like to build a system that allows users to query whether their keys were compromised.

Moreover say we’d like our system to use a minimal amount of bandwidth and/or requests to the server.

Using a bloom filter for that purpose fits perfectly! Lets see why:

Note that the initial client request is just a fetch (GET) request, the actual key X isn't sent with it.

Since Bloom filters have zero false negatives, if key X X X isn’t in Bloom filter B B B we know that X X X isn’t compromised with certainty! Therefore, no more requests needed.

The other case is that X X X is in B B B:

Note that the initial client request is just a fetch (GET) request, the actual key X isn't sent with it.

So a request to verify the state of X X X must be sent to the server as it may be either a true positive ( X X X is in B B B and X X X is compromised) or a false positive ( X X X is in B B B but X X X isn’t compromised).

The nice thing about bloom filters is that the size of the Bloom filter is dependent on the false positive probability that is arbitrarily chosen by us!

So if we notice a lot of false positives we can just tune the Bloom filter to our needs and sacrifice some bandwidth for more accuracy.

In Github there’s test_bloom.py which populates a toy Bloom filter with the compromised keys and tests its effectiveness:

$ ./test_bloom.py [ + ] Number public keys in ./dsa/1024: 32768 . Total length: 19004952 bytes ( 18 .12Mb ) . [ + ] False-positive probability of 0.001 . [ + ] Optimal number of bits is 471125 ( 57Kb ) . 322 times more space efficient. [ + ] Optimal number of hash functions is 10 . [ + ] Test: All public keys were found within the bloom filter. [ + ] Test: Average number of false positives: 21 , false positive rate: 0.0213 . Averaged over 10 tests, 1000 random strings in each test.

Notice that the bloom filter is 322 322 322 more space efficient than the actual length of the public keys (18.12Mb vs. 57Kb)!

If you’d like to run it yourself make sure to follow the simple installation instructions.

For completeness, here’s the code of test_bloom.py :

` '''A test script that queries vulnearble keys (debian openssl debacle) in a space efficient manner using Bloom filters.''' import glob import random from string import ascii_letters import bloom def random_string ( size = 10 ) : rand_str = '' . join ( ( [ random . choice ( ascii_letters ) for i in range ( size ) ] ) ) return str . encode ( rand_str ) def empirical_false_positive_rate ( bf , nr_tests = 1 , nr_strings = 1000 ) : c = 0 for i in range ( nr_tests ) : rand_strings = [ random_string ( 30 ) for i in range ( nr_strings ) ] t = 0 for r in rand_strings : if bf . contains ( r ) : t += 1 c += t avg_fpr = ( ( c / nr_tests ) * ( 1 / nr_strings ) ) avg_errs = c / nr_tests return ( int ( avg_errs ) , avg_fpr ) if __name__ == '__main__' : public_keys = set ( ) total_keys_bytes = 0 for pk_file in glob . glob ( './dsa/1024/*.pub' ) : pk_base64 = open ( pk_file , 'rb' ) . read ( ) . split ( ) [ 1 ] total_keys_bytes += len ( pk_base64 ) public_keys . add ( pk_base64 ) n = len ( public_keys ) print ( '[+] Number public keys in ./dsa/1024: {}. Total length: {} bytes ({:0.2f}Mb).' . format ( n , total_keys_bytes , total_keys_bytes / ( 2 ** 20 ) ) ) p = 1 / 1000 print ( '[+] False-positive probability of {}.' . format ( p ) ) k , m = bloom . optimal_km ( n , p ) t = int ( ( total_keys_bytes * 8 ) / m ) print ( '[+] Optimal number of bits is {} ({}Kb). {} times more space efficient.' . format ( m , int ( m / ( 8 * ( 2 ** 10 ) ) ) , t ) ) print ( '[+] Optimal number of hash functions is {}.' . format ( k ) ) bf = bloom . bloom_filter ( m , k ) for pk in public_keys : bf . add ( pk ) all_pks_in_bf = True for pk in public_keys : if not bf . contains ( pk ) : all_pks_in_bf = False break if all_pks_in_bf : print ( '[+] Test: All public keys were found within the bloom filter.' ) else : print ( '[-] Test: One or more public key were not found within the bloom filter.' ) nr_tests = 10 nr_strings = 1000 avg_errs , avg_fpr = empirical_false_positive_rate ( bf , nr_tests , nr_strings ) print ( '[+] Test: Average number of false positives: {}, false positive rate: {:0.4f}. Averaged over {} tests, {} random strings in each test.' . format ( avg_errs , avg_fpr , nr_tests , nr_strings ) )

Applications

In their 1994 paper, Andrei Broder and Michael Mitzenmacher coined the Bloom Filter Principle:

Wherever a list or set is used, and space is at a premium, consider using a Bloom filter if the effect of false positives can be mitigated. Andrei Broder and Michael Mitzenmacher

Below are some cool applications I’ve bumped into over the years.

Breaking Bitcoin (and Ethereum) Brainwallets

In DEFCON 23 (2015), Ryan Castellucci (@ryancdotorg) presented Brainflayer. A cryptocurrency brainwallet cracker that uses a Bloom filter under the hood.

I specifically abstracted away low level Bitcoin technicalities.

Bitcoin’s blockchain is made out of a sequence of blocks. Each block contains transactions and each transaction cryptographically instructs to transfer X X X Bitcoins from a previous transaction to a Bitcoin address.

How does a Bitcoin address is generated?

A Bitcoin address A A A is simply a hashed ECDSA public-key Q Q Q. Lets denote A = H ( Q ) A = H(Q) A=H(Q).

How does an ECDSA public key is generated?

An ECDSA public key Q Q Q is the outcome of multiplying a private key d d d with some known constant base point G G G. That is, Q = d × G Q = d \times G Q=d×G.

How does an ECDSA private key is generated?

An ECDSA private key d d d is simply an integer that is preferably generated using a cryptographically secure random number generator. Anyone that knows d d d can redeem Bitcoins that were sent to A A A.

What’s a Brainwallet address?

A Brainwallet is simply a Bitcoin address where its corresponding private key d d d was generated using a mnemonic (!) rather then a secure random number generator. One possible Brainwallet construction looks like:

d = SHA256(MNEMONIC) d = \text{SHA256(MNEMONIC)} d = SHA256(MNEMONIC)

For instance, the string (embedded in Bitcoin’s Genesis block):

The Times 03/Jan/2009 Chancellor on brink of second bailout for banks

When hashed with SHA256 yields the following ECDSA private key:

a6d72baa3db900b03e70df880e503e9164013b4d9a470853edc115776323a098

That yields the following Bitcoin address:

1Nbm3JoDpwS4HRw9WmHaKGAzaeSKXoQ6Ej

Using a blockchain explorer we can check the address’s history and see that it was used :)

Using a Bloom filter to crack Brainwallets

It is rather straight forward:

Extract all Bitcoin addresses from the Blockchain. Add them to a Bloom filter B B B . Generate a set W W W of Bitcoin addresses using plausible mnemonics (“Brainwallets”). Gather possible candidates set C C C - addresses from W W W that B B B returns positive on. Filter out false positives by checking which addresses in C C C exist on the Blockchain.

Currently, Bitcoin’s blockchain contains about 440 M 440M 440M unique addresses (according to Quandl - press on Cumulative).

Ryan’s implenetation contains a bloom filter of length 512 M B 512MB 512MB and 20 20 20 hash functions (he actually uses simple functions over the original public key hashes - no heavy cryptographic hash - neat).

In the Appendix we derived an experssion for the false positive probability:

P F P = ( 1 − P 0 ) k = ( 1 − ( 1 − 1 m ) k n ) k P_{FP} = (1 - P_0)^{k} = \left(1 - \left(1 - \frac{1}{m}\right)^{kn}\right)^{k} P F P ​ = ( 1 − P 0 ​ ) k = ( 1 − ( 1 − m 1 ​ ) k n ) k

Where k k k is the number of hash functions, n n n the length of the set and m m m the length of the bloom filter.

def exact_pfp ( n , m , k ) : return ( 1 - ( 1 - ( 1 / m ) ) ** ( k * n ) ) ** k m_bytes = 512 * 1024 * 1024 m_bits = m_bytes * 8 k = 20 print ( exact_pfp ( 440 * ( 10 ** 6 ) , m_bits , k ) ) print ( exact_pfp ( 220 * ( 10 ** 6 ) , m_bits , k ) ) print ( exact_pfp ( 110 * ( 10 ** 6 ) , m_bits , k ) ) print ( exact_pfp ( 80 * ( 10 ** 6 ) , m_bits , k ) )

As one can tell from above, a Bloom filter of length 512 M B 512MB 512MB and 20 20 20 hash functions has a high false positive rate on 440 M 440M 440M items.

In 2015, when Ryan released Brainflayer, there were about 80 M 80M 80M unique addresses on the blockchain and such a construction yielded a very low false postive rate of ∼ 7.16 × 1 0 − 11 \sim 7.16\times 10^{-11} ∼7.16×10−11.

Today, in order to maintain a similar false positive rate, one would have to either dissect the blockchain to chunks and use several Bloom filters of length 512 M B 512MB 512MB, or simply increase the length of the bloom filter and the number of hash functions.

I highly recommened you to go and watch Ryan’s talk.

Recommender System Optimization

Simply put, a recommender system R R R is an algorithm that predicts the preferences of a user.

For instance, you’ve just bought The Hard Thing About Hard Things. Amazon’s recommender system learns that you like books about entrepreneurship and start show you other book recommendations.

But, how do you keep track of irrelevant recommendations such as books the user already read or dismissed ?

Say X X X books were recommended by R R R. X X X is comprised of Y Y Y relevant and Z Z Z irrelevant recommendations ( Y ∩ Z = ∅ Y \cap Z = \emptyset Y∩Z=∅).

Using a Bloom filter B Z B_Z BZ​ to store irrelevant recommendations Z Z Z is one possible answer.

First, say we’re dealing with a lot of irrelevant recommendations, then since Bloom filters are space efficient, it reduces the data stored per user substantially, and even bandwidth (if your logic resides in client side).

Second, since Bloom filters have zero false-negatives, we are guarunteed that a user will never be shown irrelevant recommendations (the event where e ∈ Z e \in Z e∈Z and B Z . c o n t a i n s ( e ) B_{Z}.contains(e) BZ​.contains(e) is false can’t happen).

Third, since Bloom filters may have false-positives, a relevant recommendation may not be shown to the user (the event where e ∈ Y e \in Y e∈Y and B Z . c o n t a i n s ( e ) B_{Z}.contains(e) BZ​.contains(e) is true). But that’s ok since nothing will happen if a user won’t get a relevant recommendation once every 1K visits.

I’d like to thank Sébastien Bratières for spotting an error in this clause.

Search Engine Optimizations

In his 2016 Strange Loop talk, Dan Luu (@danluu), shared some of the internals of one of Bing’s production search indices: BitFunnel (hint: they use Bloom filters, but not in a trivial way).

The talk is short and built in a very constructive way:

You might want to review BitFunnel’s SIGIR’17 paper.

Appendix

While studying the math behind Bloom filters I found myself rusty and confused. Here is a guided tour for the rusty-confused engineer :)

False-Positive Probability and Formulae

Assume Bloom filter B B B was populated with elements from S S S.

A false-positive is an input y y y that isn’t an element of S S S but B [ h 1 ( y ) ] , … , B [ h k ( y ) ] B[h_1(y)], \ldots, B[h_k(y)] B[h1​(y)],…,B[hk​(y)] are all set to 1 1 1.

The false-positive probability P F P P_{FP} PFP​ then is simply the probability of having any k k k arbitrary cells set to 1 1 1 after Bloom filter B B B is populated with elements from S S S.

Lets define P 1 P_1 P1​ to be the probability that a certain bit is set to 1 1 1 after we populate the Bloom filter.

Given P 1 P_1 P1​, the probability of a false positive, P F P P_{FP} PFP​ is simply:

P F P = P 1 k P_{FP} = P_{1}^{k} P F P ​ = P 1 k ​

But, how do we calculate P 1 P_{1} P1​ ?

Lets assume now that Bloom filter B B B is empty and we begin add elements from S S S.

Given x 1 x_1 x1​ we compute h 1 ( x 1 ) h_1(x_1) h1​(x1​) and set B [ h 1 ( x 1 ) ] B[h_1(x_1)] B[h1​(x1​)] to 1 1 1. What’s P 1 P_1 P1​ now?

P 1 = 1 m P_1 = \frac{1}{m} P 1 ​ = m 1 ​

because we assume h i h_i hi​ are uniform over { 1 , … , m } \{1, \ldots, m\} {1,…,m}.

Next, we compute h 2 ( x 1 ) h_2(x_1) h2​(x1​) and set B [ h 2 ( x 1 ) ] B[h_2(x_1)] B[h2​(x1​)] to 1 1 1. What’s P 1 P_1 P1​ now?

P 1 = 1 m + 1 m − 1 m 2 P_1 = \frac{1}{m} + \frac{1}{m} -\frac{1}{m^2} P 1 ​ = m 1 ​ + m 1 ​ − m 2 1 ​

Wait! Why did you subtract 1 m 2 \frac{1}{m^2} m21​ ?

Recall that we defined P 1 P_1 P1​ to be the probability that a specific bit is set to 1 1 1. This specific bit might be set to 1 1 1 by either h 1 h_1 h1​ or h 2 h_2 h2​ or both. That is, we search for the probability of the union of independent events that are not mutually exclusive.

We subtract 1 m 2 \frac{1}{m^2} m21​, since otherwise we “count” the event that both h 1 h_1 h1​ and h 2 h_2 h2​ set the bit to 1 1 1 twice. This is due to the Inclusion-Exclusion Principle.

Doing the same thing for h 3 h_3 h3​. What’s P 1 P_1 P1​ now?

P 1 = 3 m − 3 m 2 + 1 m 3 P_1 = \frac{3}{m} -\frac{3}{m^2} +\frac{1}{m^3} P 1 ​ = m 3 ​ − m 2 3 ​ + m 3 1 ​

As evident from above, if we continue this way we end up with a rather intricate expression for P 1 P_1 P1​. For this reason, most derivations of the false-positive probability use the complementary event to go around it.

Lets define P 0 P_0 P0​ to be the probability that a certain bit is not set to 1 1 1.

If we knew P 0 P_0 P0​ we could easily compute P 1 P_1 P1​ and P F P P_{FP} PFP​:

P F P = P 1 k = ( 1 − P 0 ) k P_{FP} = P_{1}^{k} = (1 - P_0)^{k} P F P ​ = P 1 k ​ = ( 1 − P 0 ​ ) k

So, how do we calculate P 0 P_{0} P0​ ?

Lets start with an empty Bloom filter B B B again and add elements from S S S.

Given x 1 x_1 x1​ we compute h 1 ( x 1 ) h_1(x_1) h1​(x1​) and set B [ h 1 ( x 1 ) ] B[h_1(x_1)] B[h1​(x1​)] to 1 1 1. What’s P 0 P_0 P0​ now?

P 0 = 1 − 1 m P_0 = 1 - \frac{1}{m} P 0 ​ = 1 − m 1 ​

Next, we compute h 2 ( x 1 ) h_2(x_1) h2​(x1​) and set B [ h 2 ( x 1 ) ] B[h_2(x_1)] B[h2​(x1​)] to 1 1 1. What’s P 0 P_0 P0​ now?

P 0 = ( 1 − 1 m ) 2 P_0 = \left(1 - \frac{1}{m}\right)^2 P 0 ​ = ( 1 − m 1 ​ ) 2

Wait! Why does P 1 P_1 P1​ and P 0 P_0 P0​ differ at this stage of the analysis?

Because when calculating P 1 P1 P1 we wanted the probability of the event that at least one of the hash functions sets a specific bit. But, for P 0 P_0 P0​ we want the probability that all hash functions does not set a specific bit!

That is, we search for the probability of the intersection of independent events that are not mutually exclusive.

Setting the bits for the other hash functions h 3 ( x 1 ) , h 4 ( x 1 ) , … , h k ( x 1 ) h_3(x_1), h_4(x_1), \ldots, h_k(x_1) h3​(x1​),h4​(x1​),…,hk​(x1​):

P 0 = ( 1 − 1 m ) k P_0 = \left(1 - \frac{1}{m}\right)^k P 0 ​ = ( 1 − m 1 ​ ) k

And since we add n n n elements:

P 0 = ( 1 − 1 m ) k n P_0 = \left(1 - \frac{1}{m}\right)^{kn} P 0 ​ = ( 1 − m 1 ​ ) k n

Therefore:

P F P = ( 1 − P 0 ) k = ( 1 − ( 1 − 1 m ) k n ) k P_{FP} = (1 - P_0)^{k} = \left(1 - \left(1 - \frac{1}{m}\right)^{kn}\right)^{k} P F P ​ = ( 1 − P 0 ​ ) k = ( 1 − ( 1 − m 1 ​ ) k n ) k

Since we want to find the optimal k k k and m m m such that P F P P_{FP} PFP​ (the false probably rate) is minimized, we will need to differentiate it.

The expression for P F P P_{FP} PFP​ isn’t easy to differentiate, this is why most derivations use a neat trick that represents it with e e e (Euler’s number).

One of e e e’s many definitions is:

lim ⁡ n → ∞ ( 1 + 1 n ) n = e \lim_{n\to\infty} \left( 1 + \frac{1}{n}\right) ^n = e n → ∞ lim ​ ( 1 + n 1 ​ ) n = e

That is, for large enough n n n, e e e is approximately ( 1 + 1 n ) n \left( 1 + \frac{1}{n}\right)^n (1+n1​)n.

Therefore,

( 1 − 1 m ) k n = ( 1 + 1 − m ) − m k n − m = ( ( 1 + 1 − m ) − m ) k n − m ≈ e k n − m \begin{aligned} \left(1 - \frac{1}{m}\right)^{kn} &= \left(1 + \frac{1}{-m}\right)^{\frac{-mkn}{-m}}\\ &= \left(\left(1 + \frac{1}{-m}\right)^{-m}\right)^{\frac{kn}{-m}}\\ &\approx e^{\frac{kn}{-m}} \end{aligned} ( 1 − m 1 ​ ) k n ​ = ( 1 + − m 1 ​ ) − m − m k n ​ = ( ( 1 + − m 1 ​ ) − m ) − m k n ​ ≈ e − m k n ​ ​

Hence, P F P P_{FP} PFP​ can be reduced to the following expression:

P F P ≈ ( 1 − e k n − m ) k P_{FP} \approx \left(1 - e^{\frac{kn}{-m}}\right)^{k} P F P ​ ≈ ( 1 − e − m k n ​ ) k

Although we got a nicer expression for P F P P_{FP} PFP​, we would like to differentiate it with respect to k k k (to find the the optimal number of hash functions). But k k k is the exponent.

To differentiate such equations usually one uses some ln ⁡ \ln ln (natural logarithm) trickery.

For any function f ( x , y ) = g ( y ) x f(x,y) = g(y)^{x} f(x,y)=g(y)x ( g g g is simply a function of y y y) it holds that:

f ( x , y ) = e l n ( f ( x , y ) ) = e l n ( g ( y ) x ) = e x ⋅ l n ( g ( y ) ) \begin{aligned} f(x,y) &= e^{ln(f(x,y))}\\ &= e^{ln(g(y)^x)}\\ &= e^{x \cdot ln(g(y))} \end{aligned} f ( x , y ) ​ = e l n ( f ( x , y ) ) = e l n ( g ( y ) x ) = e x ⋅ l n ( g ( y ) ) ​

Therefore, in the case of our P F P P_{FP} PFP​:

P F P = e l n ( ( 1 − e k n − m ) k ) = e k ⋅ l n ( ( 1 − e k n − m ) ) P_{FP} = e^{ln(\left(1 - e^{\frac{kn}{-m}}\right)^{k})} = e^{k \cdot ln(\left(1 - e^{\frac{kn}{-m}}\right))} P F P ​ = e l n ( ( 1 − e − m k n ​ ) k ) = e k ⋅ l n ( ( 1 − e − m k n ​ ) )

Lets denote g = k ⋅ l n ( ( 1 − e k n − m ) ) g = k \cdot ln(\left(1 - e^{\frac{kn}{-m}}\right)) g=k⋅ln((1−e−mkn​)), which makes P F P = e g P_{FP} = e^{g} PFP​=eg.

Since e e e is a monotonically increasing function minimizing e g e^{g} eg is equivalent to minimizing g g g with respect to k k k.

Differentiating g g g with respect to k k k (WolframAlpha):

∂ g ∂ k = l n ( 1 − e − k n m ) + k n m ⋅ e − k n m 1 − e − k n m \frac{\partial g}{\partial k} = ln \left( 1 - e^{\frac{-kn}{m}}\right) + \frac{kn}{m} \cdot \frac{e^{\frac{-kn}{m}}}{1 - e^{\frac{-kn}{m}}} ∂ k ∂ g ​ = l n ( 1 − e m − k n ​ ) + m k n ​ ⋅ 1 − e m − k n ​ e m − k n ​ ​

To find the optimal k k k, the one that minimizes the above expression, one needs to equate it to 0 0 0

It is easy to verify that the derivative is 0 0 0 when k = l n 2 ⋅ m n k=ln 2 \cdot \frac{m}{n} k=ln2⋅nm​:

∂ g ∂ k = l n ( 1 − e − l n 2 ) + l n 2 ⋅ e − l n 2 1 − e − l n 2 = l n ( 1 − 1 2 ) + l n 2 ⋅ 1 2 1 2 = l n ( 1 2 ) + l n 2 = 0 \begin{aligned} \frac{\partial g}{\partial k} &= ln \left( 1 - e^{-ln2}\right) + ln2 \cdot \frac{e^{-ln2}}{1 - e^{-ln2}}\\ &= ln \left( 1 - \frac{1}{2}\right) + ln2 \cdot \frac{\frac{1}{2}}{\frac{1}{2}}\\ &= ln \left(\frac{1}{2} \right) + ln2\\ &= 0 \end{aligned} ∂ k ∂ g ​ ​ = l n ( 1 − e − l n 2 ) + l n 2 ⋅ 1 − e − l n 2 e − l n 2 ​ = l n ( 1 − 2 1 ​ ) + l n 2 ⋅ 2 1 ​ 2 1 ​ ​ = l n ( 2 1 ​ ) + l n 2 = 0 ​

Great! Now we know that k = l n 2 ⋅ m n k=ln 2 \cdot \frac{m}{n} k=ln2⋅nm​ is the optimal number of needed hash functions.

A very cool result of bloom filters is that k k k only depends on a given P F P P_{FP} PFP​.

To achieve that result, lets plug the k k k we got in equation we derived for the false positive probability:

P F P ≈ ( 1 − e k n − m ) k = ( 1 − 1 2 ) l n 2 ⋅ m n = ( 2 ) − l n 2 ⋅ m n \begin{aligned} P_{FP} &\approx \left(1 - e^{\frac{kn}{-m}} \right)^{k}\\ &= \left(1 - \frac{1}{2}\right)^{ln2 \cdot \frac{m}{n}}\\ &= \left(2\right)^{-ln2 \cdot \frac{m}{n}}\\ \end{aligned} P F P ​ ​ ≈ ( 1 − e − m k n ​ ) k = ( 1 − 2 1 ​ ) l n 2 ⋅ n m ​ = ( 2 ) − l n 2 ⋅ n m ​ ​

Taking l n ln ln on both sides:

l n ( P F P ) = − m n ⋅ ( l n 2 ) 2 ln(P_{FP}) = -\frac{m}{n} \cdot (ln2)^{2} l n ( P F P ​ ) = − n m ​ ⋅ ( l n 2 ) 2

Therefore, m m m, the number of bits in our bloom filter (number of bits in B B B) is:

m = − n ln ⁡ P F P ( ln ⁡ 2 ) 2 m=-{\frac {n\ln P_{FP}}{(\ln 2)^{2}}} m = − ( ln 2 ) 2 n ln P F P ​ ​

Pluggin that m m m into the k k k we got yields:

k = − ln ⁡ P F P ln ⁡ 2 k=-{\frac {\ln P_{FP}}{\ln 2}} k = − ln 2 ln P F P ​ ​

And voila, k k k depends only on a given false positive probability P F P P_{FP} PFP​!

Summary

Bloom filters are simple and useful beasts. They were designed in times of great scarcity in memory, but since nowadays we explode in data they fit almost perfectly for our times as well!

If you found this article interesting, make sure to read about Scalable Bloom filters which allows you to add items to an already existing Bloom filter and Counting Bloom filters which allows you to delete items from an already existing Bloom filter.

If you spot an error / have any question please let me know so others may gain :)

Comments and thoughts are also welcome on this tweet: