Published on
A Bloom filter answers one question: is this element in the set? It needs far less memory for that than, say, one Redis key per element. But only its NO is certain; otherwise it says "maybe".
The example: a CDN that only caches on the second request
A CDN server that caches every file it serves fills most of its disks with files nobody ever asks for again, so-called one-hit wonders. Akamai measured this on one cluster: of roughly 400 million objects requested over two days, 74 % were requested exactly once (Maggs and Sitaraman, "Algorithmic Nuggets in Content Delivery" Opens in a new window).
The fix is a simple rule: cache a file only on its second request. For that the server has to remember which URLs it has already seen, across hundreds of millions of URLs. That is the Bloom filter's job.
When a client requests a file that is not in the cache, the server asks the filter:
- NO: the URL has never been requested. The server adds it to the filter, fetches the file from the origin and serves it without caching it.
- maybe: the URL has probably been requested before. The server serves the file and caches it. Nobody checks, because a mistake costs next to nothing: at a 1 % false positive rate, one new URL in a hundred ends up in the cache although it is only requested once. Without the filter, every one of them would.
At Akamai this rule raised the share of bytes served from cache from 74 to 83 %. Disk writes dropped by 44 %, and mean disk latency went from 15.6 to 11.9 ms. The space the one-hit wonders no longer take up is left for files that really are requested again.
How it works
The letters used in this article:
- n: number of elements added, here the URLs
- m: number of bits in the filter, so its size
- k: number of hash functions, so how many bits each element sets
- p: false positive rate, so how often the filter wrongly says "maybe"
A hash turns a URL into a large number, and the same URL always into the same number. At the start, all m bits are 0.
- Adding: the element is hashed k times. Each hash points at one bit: the remainder of
the hash value divided by m is the position (
hash % m). Those k bits are set to 1. - Looking up: the same k bits are checked. If any of them is 0, the answer is NO: the element is not in the set. If all are 1, the answer is maybe.
In the picture, /img/1.jpg and /img/2.jpg set three bits each. The lookup for
/img/3.jpg hits two set bits and one that is 0. That settles it: /img/3.jpg has never
been requested.
The "maybe" happens when all k bits were set by other elements by chance. Not a single URL is stored, only bits. That is where the savings come from, and why it makes no difference whether a URL is 20 or 200 characters long.
Is the NO really 100 % right?
Yes. Once an element is added, its k bits are 1, and nothing sets them back. A wrong NO (a false negative) is mathematically impossible. Only the "maybe" can be wrong (a false positive).
In practice that holds as long as four things are true:
- Nothing is deleted. Setting a bit back to 0 would make the filter "forget" other elements too. If you need to delete single elements, use a counting Bloom filter or a cuckoo filter. The CDN does not need to: it throws away whole filters, more on that below.
- Every new element ends up in the filter. If a URL is served but not added, the filter says NO again on the next request. That is a bug in operations, not in the maths.
- Every process uses the same hash functions, or they point at different bits.
- The filter is complete. A filter that is empty after a restart, or still being built, says NO to known elements. More on that under restarts.
In the CDN, a wrong NO only means a file gets cached one request later. Wherever something else relies on the NO, for example because nobody looks in the database after it, you have to watch these four points closely.
Calculating size and false positive rate
It holds:
p ≈ (1 − e^(−k·n/m))^k
best k = (m/n) · ln 2
bits per element = −ln(p) / (ln 2)²
That tells you how much memory a target rate costs:
| False positive rate | Bits per element | k | 10 million elements |
|---|---|---|---|
| 1 % | 9.6 | 7 | 12 MB |
| 0.1 % | 14.4 | 10 | 18 MB |
| 0.01 % | 19.2 | 13 | 24 MB |
So what matters is the bits per element, m/n. Whether 1 million URLs sit in 1.2 MB or 10 million in 12 MB, the false positive rate is the same. Every factor of ten fewer errors costs just under 5 bits per element.
A filter is planned for a fixed number of elements. If it is built for 10 million URLs at 1 % and 20 million go in, the rate does not rise to 2 % but to about 16 %:
k·n/m = 7 · 2 / 9.585 = 1.46
(1 − e^(−1.46))^7 ≈ 0.768^7 ≈ 0.158
Only the number of elements actually added counts, not how many there could be.
Two filters taking turns
A CDN sees new URLs every day, so the set never stops growing. A single filter would fill up at some point and say "maybe" to almost everything. Then every file would be cached again.
Akamai describes two filters for this, a current one and an old one:
- New URLs are only added to the current filter.
- Both are queried. If the URL is in either of them, this is the second request.
- Once the current filter has taken in as many URLs as it was planned for, it becomes the old one. The previous old one is thrown away, and an empty one becomes current.
That way the server forgets URLs that have not been requested for a long time, and no filter is filled beyond what it was planned for. "Second request" then means: within the last one or two fillings.
Because two filters are asked, their false positive rates add up. To stay at 1 % overall, plan each one at 0.5 %. With 10 million URLs per filter that is 11 bits per URL, so just under 14 MB per filter and 28 MB for both. Measured with the PHP code below: with both filters full, they wrongly say "maybe" to 1.02 % of new URLs.
Memory: Bloom filter versus Redis
Measured with Redis 8.2 and one million URLs of the form
https://cdn.example.com/img/0012345/foto-0012345.jpg (52 characters), scaled up to ten
million:
| Storage | per entry | 1 million | 10 million |
|---|---|---|---|
One key per URL (SET seen:… 1) |
94 bytes | 94 MB | ~940 MB |
One big set (SADD seen …) |
70 bytes | 70 MB | ~700 MB |
Bloom filter in Redis, 1 % (BF.RESERVE) |
11 bits | 1.4 MB | ~14 MB |
| Bloom filter by the formula, 1 % | 9.6 bits | 1.2 MB | 12 MB |
On top of the URL itself, Redis stores the bookkeeping for every entry: the hash table, the object header and the memory allocator's rounding. Longer URLs make the top rows bigger, not the bottom ones.
So the Bloom filter is 50 to 80 times smaller. The price: 1 % of the one-hit wonders still end up in the cache.
Measuring the false positive rate
The formula tells you what to expect. Whether it holds, you measure like this:
- In a test: add n known URLs, then look up a million URLs that are guaranteed not to be in the filter. The share of "maybe" answers is the real false positive rate. With the PHP code below it came out at 1.00 %, with 0 wrong NOs.
- Quick check: how many bits are 1? That share to the power of k is roughly the false positive rate. A correctly sized filter is about half full (measured: 51.8 %, and 0.518⁷ ≈ 1 %). If the share is clearly higher, the filter has become too small.
- In production: in the CDN nobody checks the "maybe", so false positives never show up anywhere. All that matters is that no filter takes in more URLs than planned. The two filters taking turns make sure of exactly that.
Redis's own filter came out at 0.50 % in the same test. BF.RESERVE plans the first layer
at half the target rate, so that the sum across all the layers Redis adds as it grows
stays under 1 %. That is also why it uses 11 instead of 9.6 bits per element.
Why not just store the URLs?
Because the memory is needed to cache files. An exact list of every URL from the last few days costs up to 940 MB of RAM in Redis for 10 million URLs of 52 characters, more for longer URLs. The Bloom filter stays at 12 MB.
Then there is speed: a lookup in the filter measured 0.5 µs in PHP for a NO, because the lookup stops at the first bit that is 0, and just under 1 µs for a "maybe", as long as the filter lives in the same process.
Where else it helps
The CDN is the ideal case, because nothing checks the "maybe". Most of the time a Bloom filter is only a pre-filter: a NO is answered on the spot, a "maybe" is looked up in the database. So the savings only come from the NOs, and that only pays off when most lookups end in NO:
- Have I crawled this URL before? For a crawler, almost always NO.
- Is this password on a list of leaked passwords? Almost always NO, and the list is too big to ship to the client.
- Does this ID exist at all? That protects against requests with made-up IDs that go straight past every cache to the database.
- Is this key in this file? Cassandra, RocksDB and LevelDB keep a Bloom filter per file, so they never open files in which a key is definitely not stored.
The often-quoted question "is this username still available?" is a weaker fit. People signing up try short names first, and those are mostly taken. Then the answer is mostly "maybe", and the database gets asked anyway.
A Bloom filter in PHP
This code is for understanding, not for copying. Under PHP-FPM every request starts from scratch, so the filter would have to be loaded again on every request: 12 MB for 7 bits. In practice it lives in a long-running process or in Redis (see below). Redis costs a network round trip of a fraction of a millisecond per lookup. In the CDN that goes unnoticed, because the filter is only asked when the file comes from the origin anyway.
final class BloomFilter
{
private string $bits;
public function __construct(
private readonly int $size, // m: number of bits
private readonly int $hashes, // k: number of hash functions
?string $bits = null,
) {
$this->bits = $bits ?? str_repeat("\0", intdiv($size + 7, 8));
}
public static function for(int $items, float $falsePositiveRate): self
{
$size = (int) ceil(-$items * log($falsePositiveRate) / (log(2) ** 2));
$hashes = max(1, (int) round($size / $items * log(2)));
return new self($size, $hashes);
}
public function add(string $item): void
{
foreach ($this->positions($item) as $position) {
$byte = $position >> 3;
$this->bits[$byte] = chr(ord($this->bits[$byte]) | (1 << ($position & 7)));
}
}
public function mightContain(string $item): bool
{
foreach ($this->positions($item) as $position) {
if ((ord($this->bits[$position >> 3]) & (1 << ($position & 7))) === 0) {
return false; // a bit is 0: NO, not in the set
}
}
return true; // all bits are 1: maybe in the set
}
public function bits(): string
{
return $this->bits;
}
/** @return iterable<int> */
private function positions(string $item): iterable
{
// One 128-bit hash gives two values; all k positions are derived from them.
$hash = hash('xxh128', $item, true);
$first = (unpack('J', $hash, 0)[1] & PHP_INT_MAX) % $this->size;
// never 0, or all k positions would land on the same bit
$second = 1 + (unpack('J', $hash, 8)[1] & PHP_INT_MAX) % ($this->size - 1);
for ($i = 0; $i < $this->hashes; $i++) {
yield ($first + $i * $second) % $this->size;
}
}
}
There is only one hash. The 128 bits of xxh128 give two numbers h1 and h2, and the k
positions are calculated from them: (h1 + i · h2) % m for i = 0 to k−1. The false
positive rate stays the same as with k real hash functions, as the measurement above
shows.
The two filters taking turns build on it:
final class SeenUrls
{
private BloomFilter $current;
private BloomFilter $previous;
private int $count = 0;
public function __construct(
private readonly int $perFilter,
private readonly float $falsePositiveRate,
) {
$this->current = BloomFilter::for($perFilter, $falsePositiveRate);
$this->previous = BloomFilter::for($perFilter, $falsePositiveRate);
}
/** Adds the URL and says whether it was (maybe) seen before. */
public function seenBefore(string $url): bool
{
if ($this->current->mightContain($url) || $this->previous->mightContain($url)) {
return true;
}
if ($this->count === $this->perFilter) {
$this->previous = $this->current;
$this->current = BloomFilter::for($this->perFilter, $this->falsePositiveRate);
$this->count = 0;
}
$this->current->add($url);
$this->count++;
return false;
}
}
And this is how the server decides whether to cache:
$seen = new SeenUrls(10_000_000, 0.005); // once at startup
// per request:
if ($cache->has($url)) {
return $cache->get($url);
}
$response = $origin->fetch($url);
if ($seen->seenBefore($url)) {
$cache->put($url, $response); // second request: cache it now
}
return $response;
The filter itself comes ready-made in Redis. RedisBloom ships with Redis 8, and BF.ADD
checks and adds in a single command: it answers 1 if the URL was new and 0 if it may
already have been there.
redis-cli BF.RESERVE seen:current 0.005 10000000 NONSCALING
redis-cli BF.ADD seen:current /img/1.jpg # 1 = new
redis-cli BF.ADD seen:current /img/1.jpg # 0 = maybe seen before
redis-cli BF.EXISTS seen:previous /img/1.jpg # 1 = maybe in the old filter
The file is cached if BF.ADD returns 0 or BF.EXISTS returns 1.
With NONSCALING, BF.ADD answers ERR non scaling filter is full as soon as the filter
has reached its planned size. That is the signal to switch: RENAME seen:current seen:previous replaces the old filter, then BF.RESERVE creates a new empty one. If
several processes share the filters, these two commands belong in a Lua script, so that
two processes do not switch at the same time.
What happens after a restart?
If the filter is gone, every URL is new again. Each file is then cached one request later than usual, and that is all. Whatever is already in the cache stays there.
It is still worth saving the filter. It is just a bit array, 12 MB for 10 million URLs at 1 %. That loads in milliseconds.
- In Redis the filter is a key like any other and is saved if Redis saves at all. Out
of the box Redis writes snapshots (RDB) by the rule
save 3600 1 300 100 60 10000: after an hour at the latest if anything changed, after five minutes with 100 changes, after one minute with 10,000. The append-only file (AOF) is off. If Redis runs as a pure cache withsave "", nothing is left after a restart, and in the Docker image the file lives under/data, so without a volume it goes away with the container. - In your own program you write the bytes out regularly and load them at startup:
file_put_contents('/var/lib/cdn/seen.bloom', $filter->bits());
// m and k as when it was created, here for 10 million entries at 1 %
$filter = new BloomFilter(95_850_584, 7, file_get_contents('/var/lib/cdn/seen.bloom'));
Whatever was added after the last save is missing after a crash. In the CDN that only means those URLs get cached one request later.
It is different when something relies on the NO, for example because the filter sits in front of a database. Then the last snapshot is not enough:
- With
appendonly yesandappendfsync everysecyou lose at most the last second. - You are only completely safe if, at startup, you add whatever came in since the last
save (
WHERE created_at >= …), or rebuild the filter. Hashing is the cheapest part of that: the PHP code above adds a million URLs in 1.1 seconds.
While it is being rebuilt, the filter must not answer until it is finished. A half-filled filter says NO to entries that exist. This is how to do it right:
- Mark the filter as "not ready". As long as it is, every lookup goes straight to the database. That is slower, but never wrong.
- From now on, write new entries to the filter as well. Only then start the rebuild, or an entry that arrives during it slips through.
- Read all existing entries and add them. Adding one twice does no harm; the bit is simply already 1.
- Mark the filter as "ready".
Limits
- A Bloom filter cannot list anything and cannot delete anything. If an element is deleted from the real data, the filter keeps saying "maybe", and the element still counts towards how full it is. If a lot gets deleted, rebuild it from the current data at some point.
- Its size has to be planned up front. If the set grows, you need two filters taking turns
as above, a new filter, or a scalable Bloom filter that adds more layers. Redis does
that on its own unless you pass
NONSCALINGtoBF.RESERVE. But then the memory grows without end as well. - It only knows the answers NO and "maybe". Wherever a "maybe" is not enough, someone who knows the exact answer has to check behind it.
