Video in progress

Strong Middle 🏗️ System design

What is a Bloom filter, and where does it give real benefit in system design?

A Bloom filter is a compact structure made of a bit array and several hash functions: it answers "definitely not there" or "probably there". There are no false negatives, and false positives occur at a tunable rate, so it is used as a cheap filter in front of an expensive check.

📖 Answer

How it works: an array of m bits and k hash functions. When an element is added, 1 is written at k positions. On a lookup, if any one of those k positions is 0, the element was definitely not added. If all are 1, it was probably added (other elements may have switched those bits on by chance).

The size is surprisingly small: for 100 million elements at a 1% false positive rate, about 120 MB (~9.6 bits per element). Storing the same IDs in a HashSet<Long> would take several GB.

Where it's used:

  • LSM databases (Cassandra, RocksDB): each SSTable file has a Bloom filter, so "this key isn't in this file" avoids a disk read.
  • Cache penetration — an attack with nonexistent IDs: if the filter says "no", we don't go to the DB.
  • "Is this username taken?" — a fast pre-check; if it says "probably taken", we ask the DB for a definite answer.
  • Crawlers — has this URL been seen before.
// Guava
BloomFilter<Long> ids = BloomFilter.create(Funnels.longFunnel(), 100_000_000, 0.01);
ids.put(42L);
if (!ids.mightContain(id)) return Optional.empty(); // we don't go to the DB

Limitations: you can't remove an element from a plain Bloom filter (you need a counting Bloom filter or a Cuckoo filter). If the number of elements goes beyond what was planned, false positives climb sharply — the filter has to be rebuilt from time to time. If several instances need a shared filter, you can use the RedisBloom module.