SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

Bloom Filters

Say 'definitely not here' or 'maybe here' using very little memory.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Bloom filter is a tiny, fast structure that answers one question: "Is this item in the set?" It answers either "definitely not" or "maybe yes".

  • It uses a row of bits (0 or 1) and a few hash functions. It does not store the items themselves, so it is very small.
  • It never says "no" for an item that was added (no false negatives). It can sometimes say "maybe yes" for an item that was not added (a false positive).
  • You use it as a cheap guard in front of something slow, like a disk or a database, to skip lookups that would find nothing.

02Concept: What is it?

Start with an array of m bits, all set to 0. To add an item, run it through k hash functions. Each hash gives a position in the array. Set those k bits to 1.

To check an item, hash it the same way and look at the same k positions. If any of those bits is 0, the item was never added: the answer is a sure no. If all are 1, the item is probably there. Those bits might have been switched on by other items, which is how a false positive happens.

Adding two words and checking a third
➕add catbits 1, 4, 9
➕add dogbits 4, 6, 12
❓check foxbits 2, 6, 9
00
11
20
30
41
50
61
70
80
91
100
110
121
130
↓bit 2 is 0, so fox is NOT in the set
"cat" and "dog" switch on their own bits. "fox" finds one bit still at 0, so it is definitely not in the set.
🧠Two answers only
"Definitely not" is always true. "Maybe yes" is only probably true. That one-sided error is the whole trade: a little wrong in one direction, in return for a huge saving in memory.

03Real-Life Example

🍵The Club Doorman With a Short List
A club has a very long guest list in a big binder in the back office. Walking there to check every visitor is slow. So the doorman keeps a small card by the door. For each invited guest, he made a few tiny pencil marks in a grid, picked by the guest's name. When someone arrives, he looks at the marks for their name. If even one spot is blank, the person is certainly not on the list, and he turns them away at once. If all the spots are marked, the person is probably on the list, so he walks to the binder to be sure. Sometimes other guests' marks cover a stranger's spots, and he makes a needless walk. But he never turns away a real guest.
Club doorman
Bloom filter
The small card with the grid
The bit array
Pencil marks picked by a guest's name
The k hash functions
One blank spot means 'not invited'
Any 0 bit means 'definitely not in the set'
All spots marked means 'probably invited'
All 1 bits means 'maybe yes'
Walking to the big binder
The slow lookup in the database or on disk
A needless walk for a stranger
A false positive
Rubbing out one guest's marks
Not possible: marks are shared, so you cannot delete

04Why Do We Need It?

🪶Very small
About 10 bits per item gives roughly a 1 in 100 chance of a false positive. The item itself can be a long URL or a whole row.
⚡Very fast
A check is just k hash calculations and k memory reads. The time does not depend on how many items you stored.
💾Skip slow work
Most lookups for missing items can stop in memory, without touching the disk or the network.
✅Never misses
No false negatives. If the item was added, the filter will always say 'maybe yes'.
🔒Hides the data
The filter does not hold the items, so you can share it without sharing the list itself.
📦Easy to merge
Two filters with the same size and hashes combine with a bitwise OR into a filter of both sets.
When most questions have the answer "no", a tiny filter that can say "no" for sure saves a lot of expensive lookups.

05Where Do We Use It?

🗄️Database storage engines
LSM-tree databases (Cassandra, HBase, RocksDB and LevelDB) keep a filter per file, to skip files that cannot hold a key.
⚡Caches
Check the filter before the cache or database to avoid hits for keys that do not exist (and to blunt a cache stampede on missing keys).
🌐CDNs and web caches
Remember URLs that were seen once, so a file is only cached when it is requested a second time.
🛡️Blocklists
Check a URL or password against a huge bad list without shipping the whole list to the browser.
🕷️Crawlers and dedup
A crawler asks 'have I already visited this page?' for billions of URLs.
🧰Ready-made
Redis Stack has a Bloom filter type, and most languages have a small library.

06Types / Parts / How It Works

How a filter is built

The two numbers you choose
m: bits in the array
More bitsfewer false positives
Fewer bitsarray fills up, more mistakes
k: number of hashes
Too feweasy to collide
Just right: (m / n) x ln 2
Too manyfills the array fast
Bigger m means fewer false positives. A good k is not too small and not too big.

The formulas (n = items added)

WhatFormulaPlain meaning
False positive rate(1 - e^(-kn/m))^kChance that all k bits of an unseen item are already 1
Best number of hashesk = (m / n) x ln 2About 0.69 hashes for each bit available per item
Bits needed for target rate pm = -n x ln(p) / (ln 2)^2About 9.6 bits per item for 1%, about 14.4 for 0.1%

Variants

VariantWhat changesGood and bad
Standard Bloom filterBits onlySmallest and simplest. No delete.
Counting Bloom filterSmall counters instead of bitsSupports delete. Uses several times more memory.
Scalable Bloom filterAdds a new, bigger filter when fullGrows with the data. Checks must look in every layer.
Blocked Bloom filterAll k bits fall in one cache lineFaster in memory. A slightly higher false positive rate.
Cuckoo filterStores short fingerprints instead of bitsDelete is supported and lookups touch fewer places. See the Cuckoo Filter topic.
VisualizerBits, hashes and false positivesAdd words and watch bits turn on. Make the array too small and see false positives appear. Move k and compare the measured rate to the formula and to the best k.
The bit array: dark = 0, cyan = 1, amber = 1 shared by two or more words. A ring marks the 3 bits checked for "alice" (green ring = on, red ring = off).
"alice" was added, so all 3 of its bits are on. A Bloom filter never misses a word that was added: the answer is "maybe yes", and here it really is yes.
Bits switched on
31.3%
20 of 64
False positive rate (formula)
3.1%
(1 - e^(-kn/m))^k
Measured on 200 unseen words
4.5%
words wrongly said maybe
Best k for this m and n
6
(m / n) x ln 2

Every word uses the same fixed hash, so the picture is the same each time. The measured rate comes from 200 fixed words that were never added, so it can differ a little from the formula. The filter has no delete: a bit may belong to several words.

07How to Use It / Steps / Implementation

Using a Bloom filter well

  1. 1
    Estimate n
    How many items will be added? A filter sized for 1 million items is much worse when it gets 10 million.
  2. 2
    Pick a false positive target
    1% is a common start. Lower targets need more bits per item, but the cost grows slowly.
  3. 3
    Compute m and k
    Use m = -n ln(p) / (ln 2)^2 and k = (m / n) ln 2. Most libraries do this for you when you give n and p.
  4. 4
    Put it in front of the slow thing
    Check the filter first. On 'no', return at once. On 'maybe', do the real lookup, which gives the true answer.
  5. 5
    Add items as they are created
    Add on every write, and rebuild the filter from the real data when the process starts or when you compact.
  6. 6
    Watch the fill rate
    At the right size about half of the bits are on. Much more than that means the filter is overfull and the error is rising.
  7. 7
    Plan for deletes
    Use a counting filter or a cuckoo filter, or rebuild the filter on a schedule.
The idea in a few lines of pseudocode
add(item):
  for i in 0..k-1:
    bits[ hash_i(item) % m ] = 1

maybe_contains(item):
  for i in 0..k-1:
    if bits[ hash_i(item) % m ] == 0:
      return false      // definitely not
  return true           // maybe
💡Two hashes are enough
You do not need k separate hash functions. Compute two good hashes, h1 and h2, and use h1 + i x h2 for i = 0 to k-1. This gives almost the same false positive rate.
⚠️Do not trust a 'maybe'
A "maybe yes" must always be confirmed against the real data when a wrong answer matters. The filter only saves you from the sure "no" cases.

08Key Terms to Know

TermMeaning in easy words
Bloom filterA small bit-array structure that answers 'definitely not' or 'maybe yes' for set membership
Bit arrayThe row of m bits (0 or 1) that holds the filter state
Hash functionA function that turns an item into a number, so we can pick a bit position
kHow many hash functions (and bit positions) are used for each item
mThe number of bits in the array
nThe number of items added to the filter
False positiveThe filter says 'maybe yes' for an item that was never added
False negativeThe filter says 'no' for an item that was added. A Bloom filter never does this
Fill ratioThe share of bits that are set to 1
Counting Bloom filterA variant with small counters instead of bits, so items can be removed
Double hashingMaking k hashes out of two: h1 + i x h2

09Pros, Cons and Trade-offs

✅ Pros
  • Tiny memory compared with storing the items
  • Constant-time add and check
  • No false negatives
  • Simple to build and to merge (OR)
  • Works well in front of disks, caches and networks
⚠️ Cons
  • False positives can happen
  • No delete in the basic form
  • Cannot list or count the items
  • Must be sized for n in advance, or it gets worse
  • A 'maybe' still needs the real lookup

Trade-offs

ChoiceWe gainWe lose
More bits per itemFewer false positivesMore memory
More hash functions (up to the best k)Lower errorSlower add and check; past the best k the error goes up again
Counting filterDelete supportAbout 3 to 4 times more memory
Bloom vs hash setFar less memoryPossible false positives, no way to read items back
Bloom vs cuckoo filterSimpler and often faster to insertNo delete, and usually more space at low error rates
Rebuild on a scheduleRemoves old items, keeps filter smallExtra work and a short period of reduced accuracy

10Common Problems and Mistakes

Common mistakes

  1. Treating "maybe" as "yes". A positive answer is only a hint. Check the real data.
  2. Adding far more items than planned. The array fills with 1s and nearly every check says "maybe".
  3. Trying to delete. Clearing a bit can break other items that share it, and then real items get a false "no".
  4. Using weak or related hash functions. Bits cluster and the real error is above the formula.
  5. Forgetting to keep it in sync. If the data changes and the filter does not, it will say "no" for items that are really there.
  6. Using it when most answers are "yes". Then the filter saves almost nothing.

Things to watch

📈Rising error
As n grows past the planned size the error climbs fast. Track the fill ratio.
🔁Restart and rebuild
The filter lives in memory. Know how it is rebuilt after a restart.
🧮Different sizes
Only filters with the same m, k and hashes can be merged with OR.
🎯Adversarial input
If users can pick items, a skilled user can craft items that cause false positives. Use a keyed hash.

11Real-World Examples

🪵LSM-tree databases
Cassandra, HBase, RocksDB and LevelDB use a filter per data file, so a read for a missing key skips most files.
🌍CDN caching
A filter can remember URLs seen only once, so the cache is not filled with files nobody asks for again.
🔍Safe browsing and blocklists
A local filter of known bad URLs lets the browser say 'surely safe' without a network call for most pages.
🕸️Web crawlers
Tracking billions of visited URLs in a hash set takes too much memory. A filter fits in a fraction.
🟥Redis Stack
Offers Bloom (and cuckoo) filters as a ready data type.
🎵Recommendations
'Has this user already seen this item?' checked for millions of users with a small filter each.
📝Note
Product details change over time. Check the documentation of your database or library for the exact filter options and default error rates.
Mini case: a read for a key that does not exist
📨Read key X
→↓
🌸Bloom filterin memory
→↓'no'
✅Return 'not found'no disk read
Filter Fast path
The filter answers in memory, so the disk is not touched.

12Related Topics to Read Next

Cuckoo Filter→

A similar filter that can also delete items.

LSM Trees→

Where filters guard every data file.

Cache Stampede→

Missing keys can hammer the database. A filter can stop them.

Count-Min Sketch→

Another small structure that trades exactness for memory, for counting.

HyperLogLog→

Counts how many different items, in a tiny amount of memory.

Indexing→

Another way to avoid reading everything to find one thing.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: m bits and k hashes. Answers "definitely not" or "maybe yes".
  • ✔Add: set the k bits. Check: all k bits must be 1.
  • ✔Errors: false positives yes, false negatives never.
  • ✔Rate: (1 - e^(-kn/m))^k. About 10 bits per item gives about 1%.
  • ✔Best k: (m / n) x ln 2.
  • ✔No delete in the basic form. Use counting or cuckoo filters.
  • ✔Use it: in front of disks, databases and caches, when most lookups find nothing.
  • ✔One line: “A tiny list of definite no’s that saves the big lookup.”
← Previous
S2 and H3
Next →
Cuckoo Filter