Saltar al contenido principal

The Cheapest Way to Say No: Bloom Filters and the Negative Lookup

· 12 min de lectura
Clustron Team
Ingeniería de Sistemas Distribuidos

Caches are built to make the common case — the key is present — fast, and they do. What they handle badly, almost by construction, is the key that is absent. A request arrives for a key that does not exist: a user id that was never registered, a product that was removed, a session that expired and was swept. The cache has no entry, so it misses. The miss falls through to the database, which does the full work of looking and finds nothing. And now you are stuck, because there is nothing to put in the cache — the key has no value to store — so the very next request for that same non-existent key repeats the entire round trip.

It gets worse when the absent keys are not the same key repeated but a stream of distinct non-existent keys: a crawler walking ids, a bug generating bad references, or simply a sparse keyspace where most possible keys were never used. Each distinct miss penetrates the cache exactly once and lands on the database, and because they are all different, nothing you could cache would stop the next one. This is cache penetration, and it is the failure mode where a cache not only fails to help but actively adds a hop to every doomed lookup on its way to crushing the database behind it.

What you want is a way to know a key is absent without asking the database — a gatekeeper that sits in front of the real lookup and, for keys that definitely do not exist, returns "not found" immediately. The catch is that a structure holding every key that does exist, so it can answer by exclusion, would be nearly as large as the dataset itself, which defeats the purpose. A Bloom filter is the structure that escapes this bind: it answers "is this key definitely absent?" using a few bits per key, by accepting a small, controllable chance of being wrong in the one direction that is safe to be wrong in.

A set that forgets the members but remembers the shape​

A Bloom filter is a bit array — say m bits, all zero to start — plus k independent hash functions, each of which maps a key to one of the m positions. To add a key, hash it with all k functions and set the k bits they point at to one. To test whether a key might be present, hash it the same way and look at those same k bits: if any of them is zero, the key was certainly never added — because adding it would have set that bit — so you can answer definitely not present with total confidence. If all k bits are one, the key is probably present, but you cannot be sure, because those bits might have been set to one by the combination of other keys that happened to hash there.

That is the entire asymmetry, and it is exactly the right asymmetry. A Bloom filter has no false negatives: if it says a key is absent, the key is absent, period. It has false positives: it can say "probably present" for a key that was never added, when other keys collectively lit up all of its bits by coincidence. For the negative-lookup problem this is perfect — a "definitely absent" answer lets you skip the database entirely and return not-found, while a "probably present" answer simply falls through to the real lookup you would have done anyway. The filter can only ever save you a lookup or cost you nothing; it never causes you to miss a key that exists.

add user:7 → set its three bits01010010110100query user:99 → one of its bits is 0a single 0 ⇒ definitely NOT present ⇒ skip the databaseall-ones would only mean "probably present" → fall through to the real lookup

Sizing the bits against the error rate​

The false-positive rate is a dial, and the knobs are the array size m, the number of items n, and the number of hash functions k. Intuitively, more bits per item means fewer collisions and a lower false-positive rate; too few hash functions underuses the space, too many fills it with ones too fast. The false-positive probability is approximately p ≈ (1 − e^(−kn/m))^k, minimized when k = (m/n) · ln 2. The practical takeaway is a rule of thumb worth memorizing: about 10 bits per item with 7 hash functions gives roughly a 1% false-positive rate, and each additional ~5 bits per item cuts the rate by another order of magnitude.

// Build once over the keys that exist; keep it tiny — bits, not keys.
var bloom = new BloomFilter(expectedItems: 10_000_000, falsePositiveRate: 0.01);
foreach (var key in existingKeys) bloom.Add(key); // sets k bits per key

bool MightExist(string key) => bloom.MightContain(key);

// The negative-lookup guard, in front of the cache and database.
object Get(string key) {
if (!bloom.MightContain(key)) // a definite NO — provably absent
return NotFound; // return now; never touch cache or DB
return cache.Get(key) ?? db.Get(key); // a MAYBE — do the real lookup
}

Ten million keys at ten bits each is about twelve megabytes — small enough to hold in memory on every node, versus the gigabytes the keys themselves would occupy. That compression is the reason a Bloom filter is worth the false positives: it lets every node carry a complete map of "what definitely is not here" in a rounding error of RAM, which matters when you are already watching the memory ceiling.

The one real limitation is deletion. A plain Bloom filter cannot remove a key, because clearing its bits might clear a bit some other key relies on, which would introduce a false negative — and false negatives are the one error a Bloom filter must never have. Where keys come and go, you either rebuild the filter periodically from the current key set, or use a variant built for it: a counting Bloom filter replaces each bit with a small counter so adds and removes increment and decrement, and a cuckoo filter supports deletion while often using less space at low error rates. For a cache fronting a mostly-growing keyspace, periodic rebuilds are usually simplest and entirely adequate.

Where the one-sided certainty pays off​

The negative-lookup guard is the headline use, and it composes with the other anti-penetration tools rather than replacing them. Single-flight collapses a thundering herd of concurrent requests for the same key into one backend call — but it does nothing for a flood of distinct non-existent keys, because each distinct key is only requested once and sails straight through. A Bloom filter is exactly the complement: it stops each distinct absent key at the door with one certain "no," so the two together cover both shapes of the miss storm — the repeated hot key and the scattered absent ones.

The same structure earns its keep deeper in the system. A storage node can keep a Bloom filter over the keys it owns and consult it before touching disk, turning a doomed read into a bit-check instead of a seek — which is precisely how log-structured stores avoid probing every on-disk segment for a key that is not there. A node can gossip a compact filter of its keys so peers route around it for keys it clearly lacks. In every case the value is the same: a Bloom filter does not tell you where something is, it tells you, cheaply and with certainty, where something is not — and in a distributed system, a fast, confident "no" is often worth more than a slow "yes."

Wrap-up​

Caches are weakest exactly where a Bloom filter is strongest: the lookup for a key that does not exist, which misses, penetrates to the database, and cannot be cached away when the absent keys are all distinct. A Bloom filter packs the set of existing keys into a few bits each — a bit array and k hashes — and answers one question with total certainty: if any of a key's bits is zero, the key was never added, so it is definitely absent and the expensive lookup can be skipped. Its errors fall only in the safe direction, false positives that merely trigger a lookup you would have done anyway, never a false negative that hides a real key. Size it with the ten-bits-per-item rule for about one percent false positives, rebuild or use a counting or cuckoo variant where keys are deleted, and pair it with single-flight to cover both the repeated and the scattered miss. It will not find your data for you — but it will tell you, in a handful of bits and a few hash evaluations, when there is nothing to find, and saying no that cheaply is a large part of staying fast under load.