System Design

Core Concepts

Bloom Filters and Probabilistic Structures

The error is one-sided, and which side it falls on is the entire design. A Bloom filter never says no about something present, which is why it belongs in front of an expensive operation and never in place of the answer.

Why you are doing this at all

The mechanics of a Bloom filter, a bit array and a few hash functions, take 5 minutes to learn. They aren't what anyone gets wrong.

What people get wrong is where to put one. A Bloom filter is wrong in only one direction, and the whole skill is putting it where that kind of wrong answer does no harm.

When you ask a Bloom filter whether it has seen an item, it gives one of two answers:

  • "Definitely not." This is always true. The filter never says no about an item it holds, so there are no false negatives, ever.
  • "Probably yes." This can be wrong, at a rate you choose in advance. A wrong yes is a false positive.

So a Bloom filter never gives you the final answer. It is a cheap gate in front of an expensive operation. When it says no, you skip the expensive operation, and you're certainly right to. When it says yes, you do the expensive operation, which you were going to do anyway. Now and then you do it for nothing.

Anywhere else, it's a bug. If a false yes means a user sees somebody else's data, or a payment is skipped, the structure isn't too slow or too big. It's the wrong structure for the job.

The same filter in two places
On the left, the filter sits in front of a disk read. A no skips the read, and a false yes costs one read that finds nothing. On the right, the filter takes the place of a permission check. A no still denies access correctly, but a false yes shows the document to a user who is not allowed to see it, in red.On the left, the filter sits in front of a disk read. A no skips the read, and a false yes costs one read that finds nothing. On the right, the filter takes the place of a permission check. A no still denies access correctly, but a false yes shows the document to a user who is not allowed to see it, in red.
A wrong yes has to cost only work. On the left, the filter sits in front of a disk read. A no skips the read, and a false yes costs one read that finds nothing. On the right, the filter takes the place of a permission check. A no still denies access correctly, but a false yes shows the document to a user who is not allowed to see it, in red.

The number that makes it worth learning

For a 1 percent false positive rate, a Bloom filter needs about 9.6 bits per element, and that figure doesn't depend on how big the elements are.

A million URLs of 80 bytes each take about 80 MB in a hash set, before overhead. The same million URLs take 1.2 MB in a Bloom filter, at a 1 percent error rate. A billion URLs take 1.2 GB in the filter, which fits in the memory of an ordinary machine. The exact set would need 80 GB, and that doesn't fit.

The cost per element stays the same because the filter never stores the elements. It only stores evidence that some item hashing to particular positions was inserted. So it can tell you "no" for certain, and it can never tell you what's inside it.

Bits per element, exact set against Bloom filter
The orange bars are the raw bits of each element, which an exact set has to store, and they grow with the element. The purple bars are the Bloom filter at 1 percent false positives, 9.6 bits each time. The axis is a log scale, so each step up is ten times more: the gap is 3 times for a 4-byte integer and about 3,400 times for a 4 KB document.The orange bars are the raw bits of each element, which an exact set has to store, and they grow with the element. The purple bars are the Bloom filter at 1 percent false positives, 9.6 bits each time. The axis is a log scale, so each step up is ten times more: the gap is 3 times for a 4-byte integer and about 3,400 times for a 4 KB document.
The filter costs the same whatever it holds. The orange bars are the raw bits of each element, which an exact set has to store, and they grow with the element. The purple bars are the Bloom filter at 1 percent false positives, 9.6 bits each time. The axis is a log scale, so each step up is ten times more: the gap is 3 times for a 4-byte integer and about 3,400 times for a 4 KB document.

When to skip this entirely

If the exact set fits in memory, use the exact set. A hash set has no false positives, supports deletion, can list its contents, and is easier to debug at 3 a.m.

The arithmetic is short. A million 8-byte integers take roughly 40 MB in a hash set, overhead included. That fits on any machine. If you use a Bloom filter to save 38 MB, you take on an error rate you then have to reason about forever. That's a bad trade, and it's a common misuse of this whole family.

There's no threshold number of elements. The test is a comparison: does the exact structure fit in the memory you have, on the machine it has to run on? Work out both sides before you choose.

Memory needed against one machine
The dashed line is one machine with 64 GB of memory. On the left, a million integers take 40 MB as an exact set and 1.2 MB as a filter, and both are too small to see on this axis, so the exact set wins. On the right, a billion URLs take 80 GB as an exact set, past the line, and 1.2 GB as a filter, so only the filter fits.The dashed line is one machine with 64 GB of memory. On the left, a million integers take 40 MB as an exact set and 1.2 MB as a filter, and both are too small to see on this axis, so the exact set wins. On the right, a billion URLs take 80 GB as an exact set, past the line, and 1.2 GB as a filter, so only the filter fits.
Use the filter only when the exact set does not fit. The dashed line is one machine with 64 GB of memory. On the left, a million integers take 40 MB as an exact set and 1.2 MB as a filter, and both are too small to see on this axis, so the exact set wins. On the right, a billion URLs take 80 GB as an exact set, past the line, and 1.2 GB as a filter, so only the filter fits.

The toolkit

Which structure answers which question

A common mistake here isn't misusing a Bloom filter. It's reaching for one when the question was never about membership, meaning "is this item in the set?". Find your question first.

the questionstructuretypical sizewhich way it is wrong
have I seen this before?Bloom filter, cuckoo filter~10 bits per elementfalse positives only
how many distinct things?HyperLogLogfixed 12 KBtwo-sided, ~0.81% standard error
how many times this one thing?Count-Min sketchset by error budgetoverestimates only
what are the top K?Space-Saving, heavy hittersproportional to Kcan miss items near the cut
what is the p99?t-digest, HDR histograma few KBerror concentrated in the middle, not the tails
are these two things similar?MinHash, SimHasha few hundred bytestwo-sided

Membership and cardinality are different questions, and one structure can't stand in for the other. Cardinality is the number of distinct items. A Bloom filter can't tell you how many items it holds. A HyperLogLog can't tell you whether it has seen a specific item. Approximate counting covers the trade in more depth.

How a Bloom filter actually works

A Bloom filter is an array of m bits, all starting at zero, plus k independent hash functions.

To insert an item, hash it k ways, take each result modulo m, and set those k bits to one. Bits are never set back to zero.

To query an item, hash it the same k ways and look at those k bits. If any of them is zero, the item was definitely never inserted, because inserting it would have set that bit. If all k are one, the item was probably inserted. The other possibility is that other insertions happened to set exactly those bits between them.

Inserting two items and querying two
Inserting cat sets bits 2, 7 and 11 to 1, and inserting dog sets 4, 7 and 14, shown in orange. Bit 7 is shared. A query for fox, never inserted, lands on bits 2, 7 and 14, which other items happened to set, so the filter says probably yes and is wrong, in red. A query for owl lands on bit 9, which is 0, so the answer is definitely not, in green.Inserting cat sets bits 2, 7 and 11 to 1, and inserting dog sets 4, 7 and 14, shown in orange. Bit 7 is shared. A query for fox, never inserted, lands on bits 2, 7 and 14, which other items happened to set, so the filter says probably yes and is wrong, in red. A query for owl lands on bit 9, which is 0, so the answer is definitely not, in green.
A zero bit is proof, and a set bit is only a hint. Inserting cat sets bits 2, 7 and 11 to 1, and inserting dog sets 4, 7 and 14, shown in orange. Bit 7 is shared. A query for fox, never inserted, lands on bits 2, 7 and 14, which other items happened to set, so the filter says probably yes and is wrong, in red. A query for owl lands on bit 9, which is 0, so the answer is definitely not, in green.

A zero bit proves the item is absent. A set bit is only evidence that it's present. Every property of the structure follows from this: there are no false negatives, you can't delete, and you can't list what's inside.

The formulas, and the three you actually need

For m bits, n inserted items and k hash functions, the false positive rate is:

p = (1 - e^(-kn/m))^k

You won't use that one directly. You'll use three formulas that follow from it.

The best number of hash functions, for a given number of bits:

k = (m/n) x ln 2  ≈  0.693 x (m/n)

Bits per element, for a target error rate. This is the one to memorise:

m/n = -ln(p) / (ln 2)^2  ≈  -1.44 x log2(p)

The error rate at the best k:

p = 2^(-k)

So seven hash functions give you about 1 in 128, and ten give about 1 in 1000. Each extra 1.44 bits per element halves the error.

Back of envelopeWhat a Bloom filter costs, at every error rate
Bits per element, at the optimal k:

  false positive   bits/elem     k      1M items   100M items
  ─────────────────────────────────────────────────────────────
      10%            4.8         3        0.6 MB     60 MB
       1%            9.6         7        1.2 MB    120 MB
     0.1%           14.4        10        1.8 MB    180 MB
    0.01%           19.2        13        2.4 MB    240 MB
   0.001%           24.0        17        3.0 MB    300 MB

Compare the exact set, storing the elements:

  8-byte integers, hash set    ~40 bytes/elem   4 GB at 100M
  80-byte URLs, hash set      ~112 bytes/elem  11 GB at 100M

  ⇒ Bloom at 1% is 33x smaller than the integer set
  ⇒ Bloom at 1% is 93x smaller than the URL set

And the point that matters most:

  the 9.6 bits/elem does NOT change with element size.
  A 4-byte int and a 4-kilobyte document cost the same.

  Halving the error costs 1.44 more bits per element.
  Going from 1% to 0.01% is 2x the memory, not 100x.

The information-theoretic floor for any structure
answering this question is about 1.44x smaller than
Bloom. That gap is why cuckoo and quotient filters
exist, and it is the only reason to prefer them on
size alone.

The last two points in the worksheet are the ones that change decisions. Precision is cheap. Teams often pick 1 percent because it's the number in every tutorial. At 0.01 percent, false positives are 100 times rarer, and the memory only doubles.

The variants, and what each one buys

A plain Bloom filter has three limits. It can't delete, its capacity is fixed, and it's 44 percent bigger than the theoretical minimum. Each variant fixes one of these.

variantwhat it addswhat it costsreach for it when
counting Bloomdeletion, by replacing each bit with a small counterroughly 4x the spacethe set genuinely shrinks
cuckoo filterdeletion, and a smaller size below about 3% errormore complex, and inserts can fail when it is nearly fullyou need deletes and care about size
quotient filterdeletion, mergeability, and better cache behaviourmore complex, less common in librariesyou merge filters often, or you are cache-bound
blocked Bloomone cache line per query rather than k random probesa slightly worse error rate for the same bitslookups are hot and CPU-bound
scalable Bloomgrowth, by chaining filters of increasing sizethe error rate is the sum across the chainyou genuinely cannot bound n in advance
partitioned Bloomeach hash function owns its own slicemarginalmostly a correctness convenience

After the plain filter, the one to know is the cuckoo filter, because it answers the two most common objections at once. It supports deletion. And below roughly a 3 percent error rate, it's smaller than a Bloom filter with the same accuracy. The cost is that an insert can fail when the filter is nearly full, so you need a plan for resizing it.

The other structures, briefly but precisely

HyperLogLog answers "how many distinct". It hashes every item and keeps an array of small numbers called registers. Each register records the longest run of leading zeros it has seen at the start of a hash. Long runs are rare, so the longest run seen tells you roughly how many distinct values must have passed through. The standard error is about 1.04 / sqrt(number of registers), meaning a typical estimate lands within that fraction of the true count. So 16,384 registers at 6 bits each take 12 KB and give roughly 0.81 percent. You merge two sets of registers by taking the larger value at each position. So each shard can keep its own registers, and you combine them at read time with no coordination.

Count-Min sketch answers "how many times this one thing". It's a grid of counters, d rows by w columns, with one hash function per row. To record an item, you hash it once per row and add one to the counter it lands on in each row. To read an item's count, you take the minimum of its d counters. Other items can add to a counter but never subtract from it, so every counter is at least the true count, and the minimum is the closest. That's why it can only overestimate. A width of w = e/ε and a depth of d = ln(1/δ) keep the error at most ε x N with probability 1 - δ, where N is the total of all the counts.

Reading a count from a Count-Min sketch
Fox has been seen 5 times. Its three hashes land on one counter in each row, outlined in purple. Other items landed on two of those counters too, adding 2 in row 1 and 1 in row 3. The read takes the minimum, 5. If all three rows had been shared, the answer would be too high, never too low.Fox has been seen 5 times. Its three hashes land on one counter in each row, outlined in purple. Other items landed on two of those counters too, adding 2 in row 1 and 1 in row 3. The read takes the minimum, 5. If all three rows had been shared, the answer would be too high, never too low.
The smallest counter is the closest, and it is never too low. Fox has been seen 5 times. Its three hashes land on one counter in each row, outlined in purple. Other items landed on two of those counters too, adding 2 in row 1 and 1 in row 3. The read takes the minimum, 5. If all three rows had been shared, the answer would be too high, never too low.

t-digest and HDR histograms answer "what is the p99", the value that 99 percent of measurements fall below. Both keep a compressed summary of the distribution that stays accurate at the tails, where percentiles are read. t-digests merge, so you can combine per-host summaries into a correct p99 for the whole fleet. Averaging the per-host p99s, which is what most dashboards do, gives a number that isn't the p99 of anything.

MinHash and SimHash answer "are these similar". MinHash estimates the Jaccard similarity of two sets, the size of their overlap divided by the size of their union, from a signature of a few hundred bytes. Near-duplicate detection at web scale works this way.

The one-sidedness table

This table shows which way each structure can be wrong. Check it before you place any of them.

structurecan say a wrong "yes"can say a wrong "no"so put it
Bloom, cuckoo, quotientyesneverin front of an expensive lookup
Count-Minoverestimatesnever underestimateswhere over-counting is safe, as in rate limiting
HyperLogLogboth directionsboth directionswhere the number is displayed or compared loosely
top-K sketchescan include a near-misscan omit a near-misswhere the tail of the list does not matter
t-digestboth, small near tailsboth, small near tailsanywhere a percentile is read

The method

1. Name the question. Is it membership, cardinality, frequency, top K, quantile or similarity? This is a common place to go wrong, and no amount of tuning recovers from it.

2. Compute what the exact structure costs. It's the number of elements times the bytes per element, plus overhead. If it fits in the memory you have, use the exact structure and stop here.

3. Name which way it can be wrong, and what each way costs. Write both sentences. "A false positive costs one wasted disk read." "A false negative would mean a duplicate charge."

4. If being wrong that way is a correctness bug, stop. Nothing in this family is safe there. Either add an exact check behind the structure, or use a different design.

5. Pick the error budget from the cost, then size it. Don't take a tutorial's 1 percent. Multiply the cost of one false positive by the false positive rate. Then compare that with the memory you'd spend on each extra 1.44 bits per element, which halves the rate.

6. Answer the operational questions. What happens when it fills past its design size? How is it rebuilt after a restart? Is it per node or shared, and if shared, how do the copies stay in step?

Step 6 is the one people skip, and it's where these structures fail in production rather than in design review.

Worked examples

There are four examples. Each one ends in a decision, and each shows a different way the obvious approach fails.

A key lookup in an LSM store

This is the standard use, and the one to have ready in an interview. Every LSM engine (log-structured merge tree) you're likely to meet does it, including RocksDB, LevelDB and Cassandra.

An LSM engine writes data into sorted files that never change once written. A read for one key may have to check several of these files, newest first, until it finds the key or runs out of files. A key that doesn't exist is the worst case. The read checks every file and finds nothing.

The obvious approach is to check each file's index. That works, but it still touches the disk once for every file. This is I/O amplification: one lookup turns into many disk reads, and it happens on exactly the queries that return nothing. Workloads with many such misses are common. Examples are checking whether a username is taken, whether a user has already voted, or whether a cache entry exists.

So keep a small Bloom filter in memory for each file, holding that file's keys. Before the read touches a file, it asks that file's filter. A "no" skips the file entirely, and it's always right.

Reading an absent key from eight files
At the top, with no filters, the read opens all eight files and finds nothing, about 800 microseconds of disk reads, in red. At the bottom, each file has a filter in memory. All eight say definitely not, in green, so no file is touched. At 1 percent, about 1 lookup in 12 gets a false yes from one filter and reads one file for nothing.At the top, with no filters, the read opens all eight files and finds nothing, about 800 microseconds of disk reads, in red. At the bottom, each file has a filter in memory. All eight say definitely not, in green, so no file is touched. At 1 percent, about 1 lookup in 12 gets a false yes from one filter and reads one file for nothing.
Filters in memory turn eight disk reads into almost none. At the top, with no filters, the read opens all eight files and finds nothing, about 800 microseconds of disk reads, in red. At the bottom, each file has a filter in memory. All eight say definitely not, in green, so no file is touched. At 1 percent, about 1 lookup in 12 gets a false yes from one filter and reads one file for nothing.
Back of envelopeThe LSM read path, with and without
A read that must check 8 files, and the key is absent.

Without filters:
  disk reads                              8
  at ~100 microseconds each         =   800 us

With a Bloom filter per file, 1% error:
  filters consulted                       8
  expected false positives     8 x 0.01 = 0.08
  ⇒ disk reads, on average            = 0.08
  at ~100 microseconds each         =     8 us

  ⇒ 100x fewer disk reads on absent keys

Memory cost, for 100 million keys across the files:
  9.6 bits/key x 100M       = 120 MB

That 120 MB is why the technique is universal:
it is a rounding error against the data it guards,
and the data itself is measured in terabytes.

At 0.1% error the memory is 180 MB and the expected
disk reads fall to 0.008. Precision is cheap here,
and most engines let you configure exactly this.

Decision: a Bloom filter per file, held in memory, at whatever error rate the read amplification justifies. A false positive costs one disk read, and the design without filters made that read anyway. So being wrong in this direction costs nothing extra.

Cache admission, where caching everything is the mistake

The obvious approach to a cache is to store everything you fetch. The problem here isn't speed. Most objects are never requested twice. So if you cache an object on its first request, the cache fills with things nobody will ask for again, and they push out the things people will ask for.

Akamai measured this on their own network. About 75 percent of cached objects were requested exactly once. These are one-hit wonders, objects that are requested once and never again. Three quarters of the cache was holding them.

The fix is to use a Bloom filter as an admission test, a check that decides whether an object goes into the cache at all. On an object's first request, you don't cache it. You add it to the filter instead. On a later request, the filter says it has seen the object before, and only then do you cache it. A false positive lets an object in on its first request. The cache did that for every object before, so being wrong in this direction costs nothing.

Caching on the second request
Object A is requested once. The filter records it, and it is never cached, which is what happens to about 75 percent of objects. Object B is recorded on its first request and cached on its second, when the filter says it has seen B before, so every later request is a hit, in green. Object C gets a false yes and is cached on its first request, which is what the cache did for every object before the filter.Object A is requested once. The filter records it, and it is never cached, which is what happens to about 75 percent of objects. Object B is recorded on its first request and cached on its second, when the filter says it has seen B before, so every later request is a hit, in green. Object C gets a false yes and is cached on its first request, which is what the cache did for every object before the filter.
An object seen once never takes up cache space. Object A is requested once. The filter records it, and it is never cached, which is what happens to about 75 percent of objects. Object B is recorded on its first request and cached on its second, when the filter says it has seen B before, so every later request is a hit, in green. Object C gets a false yes and is cached on its first request, which is what the cache did for every object before the filter.

Decision: a Bloom filter as an admission gate. This isn't a smaller cache or a better eviction policy. It asks a different question, and it asks it before eviction comes into play.

A distributed crawler's seen-set, where the error is not harmless

A crawler must avoid fetching the same URL twice. There are billions of URLs and dozens of machines, and the exact set of seen URLs doesn't fit on any one of them.

This looks like a job for a Bloom filter, but the obvious version is wrong here, for a reason the first two examples didn't have.

Here, a false positive says "I've seen this" about a URL the crawler has never seen, so the page is never fetched at all. That isn't a wasted operation. It's permanent data loss, and nothing in the system will ever report it. At a 1 percent rate across a billion new URLs, ten million pages are missing from the index, and no log shows an error.

There are three options.

Accept it and size for it. If you're crawling the open web, missing 0.01 percent of pages may not matter. Size the filter at 19.2 bits per element, state the loss as a number, and move on.

Put an exact check behind the filter. For a new URL, the filter almost always says "definitely not", and the crawler fetches the page with no lookup. Only a "probably yes" pays for a read against the exact store to confirm it. That's every URL the crawler has already seen, plus 1 percent of new ones. New URLs stay fast, and every yes gets an exact answer. This is the general fix whenever a wrong yes is too expensive.

An exact check behind the filter
A new URL gets definitely not from the filter (1) and is fetched with no lookup, in green. A probably yes goes to the exact store of seen URLs (2). If the URL is there, the crawler skips it. If it is not, the yes was false and the page is fetched anyway (3). Without that check, the false yes would skip the page for good, in red.A new URL gets definitely not from the filter (1) and is fetched with no lookup, in green. A probably yes goes to the exact store of seen URLs (2). If the URL is there, the crawler skips it. If it is not, the yes was false and the page is fetched anyway (3). Without that check, the false yes would skip the page for good, in red.
Only a yes pays for the exact lookup. A new URL gets definitely not from the filter (1) and is fetched with no lookup, in green. A probably yes goes to the exact store of seen URLs (2). If the URL is there, the crawler skips it. If it is not, the yes was false and the page is fetched anyway (3). Without that check, the false yes would skip the page for good, in red.

Partition instead of approximating. Split the URLs across machines by hash, so each machine holds an exact set for its slice. There's no error at all, and the cost is a network hop.

Decision: the filter plus an exact check to confirm each yes. A page skipped by mistake is never fetched, and nothing limits what that costs. The check costs one lookup for each URL the filter says it has seen. In an interview, say the middle option out loud, because it shows you noticed that a wrong yes is too expensive here.

Counting distinct viewers, where the structure family is wrong

The question is how many distinct users viewed a post. The obvious approach is a set of user IDs, and it runs out of memory. With 100 million distinct viewers and 8-byte IDs, the set takes 800 MB for one popular post, and it keeps growing.

The tempting fix is a Bloom filter, and it doesn't work. A Bloom filter can't count. It answers membership. You could insert each viewer and keep a separate counter that goes up only when the filter says "definitely not". But each false positive is then a new viewer the counter skips. The count comes out low by exactly the number of false positives, and the gap grows with the number of viewers.

The question was never membership. It was cardinality, and that needs a different structure: HyperLogLog, at a fixed 12 KB for 0.81 percent standard error, whatever the true count is.

Memory to count 100 million distinct viewers
The exact set of 8-byte IDs takes 800 MB, in orange. A Bloom filter at 1 percent takes 120 MB, in grey, and its count still comes out too low. HyperLogLog, in purple, takes 12 KB at 0.81 percent standard error. The axis is a log scale, so each tick up is ten times more memory.The exact set of 8-byte IDs takes 800 MB, in orange. A Bloom filter at 1 percent takes 120 MB, in grey, and its count still comes out too low. HyperLogLog, in purple, takes 12 KB at 0.81 percent standard error. The axis is a log scale, so each tick up is ten times more memory.
The right structure is 65,000 times smaller than the exact set. The exact set of 8-byte IDs takes 800 MB, in orange. A Bloom filter at 1 percent takes 120 MB, in grey, and its count still comes out too low. HyperLogLog, in purple, takes 12 KB at 0.81 percent standard error. The axis is a log scale, so each tick up is ten times more memory.

Decision: HyperLogLog. This is step 1 of the method. The design failed before any sizing happened, because the question sounded like membership and wasn't, so the wrong family was chosen.

Where it goes wrong

1. Putting the false positive where it is a correctness bug

This is the failure that does the most damage. Suppose you put a Bloom filter in front of a permission check, a payment deduplication, or a "have I already sent this email" test. The rare wrong answer then denies access, skips a payment, or drops a message. These aren't degraded responses. They're defects, and they happen rarely enough to reach production and often enough to matter.

The test is one question: what happens to a user when the filter says yes and the truth is no? If the answer is "a wasted lookup", go ahead. If it's anything a user could notice, add the exact check behind it.

2. Forgetting there is no delete

A plain Bloom filter is insert-only. You can't remove an item. If you clear its bits, you may clear a bit that another item also set. That item then reads "definitely not" while it is still in the set. That's a false negative, the one mistake the structure promises never to make.

What clearing an item's bits does
Cat and dog share bit 7. The top row is the filter after inserting both. In the bottom row, cat's bits 2, 7 and 11 have been cleared to delete it. A query for dog now finds bit 7 at 0, in red, and answers definitely not, even though dog is still in the set.Cat and dog share bit 7. The top row is the filter after inserting both. In the bottom row, cat's bits 2, 7 and 11 have been cleared to delete it. A query for dog now finds bit 7 at 0, in red, and answers definitely not, even though dog is still in the set.
Deleting one item can hide another. Cat and dog share bit 7. The top row is the filter after inserting both. In the bottom row, cat's bits 2, 7 and 11 have been cleared to delete it. A query for dog now finds bit 7 at 0, in red, and answers definitely not, even though dog is still in the set.

Teams often find this out after shipping. The usual fix is to rebuild the filter on a schedule from the source of truth. That's a sound design, but plan it up front: how often to rebuild, where the rebuild runs, and what answers queries while it runs.

3. Sizing for the count you have

The error rate depends on how full the filter is. Suppose you size a filter for today's 10 million items at 1 percent, and the set grows to 50 million. About 97 percent of the bits are now set, and the filter says "probably yes" to more than 80 percent of the items it has never seen.

Nothing reports this failure. The filter keeps returning answers, nearly all of them "yes", and the expensive operation you were avoiding now runs almost every time. The system gets slower, and no error appears.

Monitor the fill ratio, the fraction of bits set to one, and alert on it. At the design item count, it sits near 50 percent. At 80 percent, a filter built for 1 percent says yes to about 1 in 5 items it has never seen, 20 times its design rate.

What happens past the design count
The filter is sized for 10 million items at 1 percent. The orange line is the fill ratio, and the red line is the false positive rate. At the design count, half the bits are set and the rate is 1 percent. At 20 million it is 16 percent, and at 50 million, 97 percent of the bits are set and the rate is 83 percent.The filter is sized for 10 million items at 1 percent. The orange line is the fill ratio, and the red line is the false positive rate. At the design count, half the bits are set and the rate is 1 percent. At 20 million it is 16 percent, and at 50 million, 97 percent of the bits are set and the rate is 83 percent.
Five times the items, eighty times the false positives. The filter is sized for 10 million items at 1 percent. The orange line is the fill ratio, and the red line is the false positive rate. At the design count, half the bits are set and the rate is 1 percent. At 20 million it is 16 percent, and at 50 million, 97 percent of the bits are set and the rate is 83 percent.

4. Reaching for it when the exact structure fits

A million integers take 40 MB in a hash set. If you choose a Bloom filter to save 38 MB, you take on an error rate you'll reason about for years. Work out both sides. A Bloom filter pays when the exact set doesn't fit in memory and the filter does, as with the billion URLs earlier: 80 GB against 1.2 GB.

5. Believing k hash functions means k hash computations

A naive implementation computes k independent hashes, which is slower than it needs to be. Kirsch and Mitzenmacher showed that two independent hashes are enough. You derive the rest as h1 + i x h2 for i from 0 to k-1, and the false positive rate barely changes.

This removes the main argument against a large k. Precision is cheap in memory and nearly free in CPU, so a default of 1 percent is worth questioning.

6. Unioning filters that do not match, and intersecting ones that do

You can merge two filters with a bitwise OR only if they have the same m, the same k and the same hash functions. If you merge mismatched filters, the result is wrong in both directions, and nothing reports an error.

Intersection is easier to get wrong, because the bitwise AND looks like the filter of the intersection and isn't. It keeps every bit set by items that are in only one of the two sets. So it never misses an item that's in both, but it says yes to other items more often than a filter built from the intersection would. The usual formula doesn't give you that rate. If you need a known error rate for an intersection, build a new filter from the items in it.

7. Leaking what is inside

Anyone who holds a filter can query it. So if you hand out a filter, you hand out the ability to test any candidate item against it. Bitcoin's BIP 37 (Bitcoin Improvement Proposal 37) used Bloom filters so that lightweight clients could ask for relevant transactions without revealing their addresses. Later analysis showed that the filters often leaked enough to identify a wallet's addresses. That's why the mechanism fell out of use.

If the set is sensitive, remember that the filter is an oracle for it: anyone can ask it about an item and get an answer. It doesn't encrypt the set.

8. Confusing membership with cardinality, or with frequency

Use Bloom for "have I seen this", HyperLogLog for "how many distinct" and Count-Min for "how many times this one". They share the word approximate and nothing else. If you answer the wrong question, no amount of tuning fixes it, so check this first.

If you memorise nothing else

the linethe number or reason behind it
No false negatives, evera zero bit is proof; a set bit is only evidence
It is a gate, never an answerput it in front of an expensive operation
Ask what a wrong yes costs a userif it is more than a wasted lookup, add an exact check
~9.6 bits per element at 1%and 14.4 at 0.1%, 19.2 at 0.01%
Size is independent of element sizea 4-byte int and a 4 KB document cost the same
Precision is cheaphalving the error costs 1.44 more bits per element
Optimal k = 0.693 x (m/n)and then p = 2^-k
No deletion in a plain filteruse counting Bloom or cuckoo, or rebuild on a schedule
Over-fill and it silently stops filteringmonitor the fill ratio; ~50% at design, ~20% false positives at 80%
Union needs identical m, k and hashesand an AND says yes more often than a filter of the intersection
Cuckoo filters delete, and beat Bloom below ~3%at the cost of inserts that can fail when nearly full
HyperLogLog: 12 KB, ~0.81% standard errorand registers merge across shards by taking the max
Count-Min overestimates, never underread the minimum of the d cells
Merge t-digests; never average percentilesan average of p99s is arithmetically meaningless
The filter is an oracle for its contentsso do not hand one out if the set is sensitive

What is expected at each level

Mid-level

Can explain the bit array and the k hash functions, and knows there are false positives but no false negatives. Reaches for a Bloom filter in the LSM read path or a deduplication case, which is right. Usually quotes a 1 percent error rate without tying it to a memory figure or to the cost of being wrong. Does not mention that the structure cannot delete, or that it degrades once over-filled.

Senior

Sizes it: bits per element for a stated error rate, and the resulting memory against the thing being guarded. Names which way it can be wrong, and checks that a false positive is affordable where it is being placed. Knows deletion is unavailable and proposes rebuilding or a counting variant. Distinguishes membership from cardinality and reaches for HyperLogLog when the question is how many distinct.

Staff+

Treats which way it can be wrong as a gate rather than a parameter, and says when nothing in this family is allowed. Picks the error budget from the cost of a false positive rather than from convention. Points out that precision is cheap, because halving the error costs 1.44 more bits per element. Plans the operational side: fill-ratio monitoring, rebuild strategy, and whether the filter is per node or shared. Knows the structure is a queryable oracle for its contents and treats that as a privacy property. Reaches for a confirming exact check when being wrong that way is not affordable, rather than abandoning the structure.

Sources

Every real-world figure here comes from a published source, named below. The formulas are standard results rather than measurements, and can be derived from the definition of the structure.

  • Burton Bloom's 1970 paper, "Space/time trade-offs in hash coding with allowable errors", which introduced the structure and the trade it is named for.
  • Akamai's finding that about 75 percent of objects in their cache were requested exactly once, and their use of a Bloom filter as a cache admission test in response. The standard citation is Maggs and Sitaraman's survey of Akamai's algorithms in ACM SIGCOMM Computer Communication Review. The figure is widely reported in secondary write-ups of that work, and it is treated here as their published result rather than as an independent measurement.
  • Kirsch and Mitzenmacher, "Less hashing, same performance: building a better Bloom filter", for the result that two independent hashes suffice to simulate k, which is what makes large k practical.
  • Fan, Andersen, Kaminsky and Mitzenmacher, "Cuckoo filter: practically better than Bloom", for deletion support and for the size comparison below roughly a 3 percent false positive rate.
  • Bitcoin's BIP 37, and the subsequent privacy analyses of it, for the leakage case. The mechanism was effectively deprecated over these concerns.
  • The use of per-file Bloom filters to avoid disk reads on absent keys is documented behaviour in LevelDB, RocksDB and Cassandra, and is configurable in each.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.