Essential Data Structures home

Bloom Filter

A tiny, fast way to ask "have I seen this before?" It never says no by mistake, but sometimes it says yes when the answer is no.

"ada" "bob" "cy" 0 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 "cy" hashes to bits 1, 7, and 12. Bit 12 is 0, so "cy" is definitely absent.
Illustration: each item is hashed by three functions and sets three bits. "ada" sets bits 2, 7, and 13; "bob" sets bits 4, 7, and 10. Bit 7 is shared. A query checks all three bits of the item.

What it is

A Bloom filter is a data structure for testing membership, invented by Burton Howard Bloom in 1970. It stores no items at all, only a long array of bits, all starting at zero, plus a small set of hash functions. To add an item, you hash it with each function and set the bits at the resulting positions to 1. To test an item, you hash it the same way and look at those bits: if any one of them is 0, the item was never added, and the answer is certainly no. If all of them are 1, the answer is probably yes, because those bits might have been set by other items instead.

That one-sided error is the whole bargain. A Bloom filter never gives a false negative, so a "no" is final and trustworthy. A "yes" is only a maybe, a false positive. The filter trades certainty for size: it can hold millions of items in a few megabytes, far less than a hash set holding the same items, because each item costs only a handful of bits, not the item itself.

The filter cannot tell you which items it holds, or how many, and it cannot list them back. It answers one question only: is this item possibly in the set?

How it works

Adding an item costs one hash per function, and each hash sets one bit. The number of hash functions is usually small, often between 3 and 10. If two items hash to the same bit, that bit simply stays 1; collisions do not break anything, they only raise the chance of a false positive later.

A membership test hashes the item the same way and checks each of the k bit positions. One zero bit anywhere is proof of absence, because an item that had been added would have set all k of its bits. When all k bits are 1, the item may have been added, or each bit may have been set by some other item. As more items are added, more bits turn to 1, and false positives become more likely. The false positive probability is about (1 - e^(-kn/m))^k, where n is the number of items, m is the number of bits, and k is the number of hash functions.

Deleting is not supported. Clearing a bit would be wrong, because that bit may belong to other items too. Variants exist that allow deletion, the counting Bloom filter, which stores a small counter at each position instead of a single bit, at the cost of more memory.

The size of the filter is chosen from the expected number of items and the false positive rate you can accept. For a 1 percent false positive rate, about 9.6 bits per item are enough, with 7 hash functions. For 0.1 percent, about 14.4 bits per item, with 10 hash functions.

Complexity

OperationAverageWorst case
AddO(k)O(k)
Membership testO(k)O(k)
DeleteNot supported
SpaceO(m) bits, about 10 bits per item for a 1 percent false positive rate

Here k is the number of hash functions and m is the number of bits in the array. Both are fixed when the filter is built, so add and lookup always cost the same, no matter how many items have been added.

When to use it, and when not to

Use a Bloom filter when a fast "definitely not here" answer saves expensive work, and an occasional false positive is cheap. The classic pattern is a guard in front of a slow lookup: check the filter first, and only go to disk or the network when it says maybe. Use it when memory is tight and you can accept a small, known error rate, and when the set of items only grows, never shrinks.

Do not use it when a false positive would be harmful or hard to catch, when you need to delete items, when you need to list the items, or when you need exact answers. If the set is small enough to fit in memory as a hash set, a hash set is simpler and exact. Do not use it either when the items must be counted or when two filters must be compared for equality.

Where you meet it

Databases use Bloom filters to skip disk reads: systems built on log-structured storage, such as Cassandra and RocksDB, keep a filter per file and only open the files whose filter says the key might be there. Web caches and content delivery networks use them to avoid asking an origin server for an object that is certainly not cached. Web browsers once used them to check URLs against a list of malicious sites without downloading the whole list. Bitcoin light clients use them to ask full nodes for only the transactions that might concern them. Spell checkers and web crawlers use them for the same reason a hash set is used, to test "already seen?", when the list of seen items is too large to keep in full.

In Python

import hashlib

class BloomFilter:
    def __init__(self, size, hashes):
        self.bits = bytearray(size)   # size bytes of zero bits
        self.k = hashes               # number of hash functions
        self.m = size * 8             # total bits

    def _positions(self, item):
        for i in range(self.k):
            digest = hashlib.md5(f"{i}:{item}".encode()).hexdigest()
            yield int(digest, 16) % self.m

    def add(self, item):
        for pos in self._positions(item):
            self.bits[pos // 8] |= 1 << (pos % 8)

    def __contains__(self, item):
        return all(self.bits[pos // 8] >> (pos % 8) & 1
                   for pos in self._positions(item))

seen = BloomFilter(size=128, hashes=3)   # 1024 bits, 3 hash functions
for url in ["example.com/a", "example.com/b"]:
    seen.add(url)

print("example.com/a" in seen)   # True, it was added
print("example.com/z" in seen)   # False, almost certainly
print("example.com/c" in seen)   # False, almost certainly
print("example.com/b" in seen)   # True, it was added

In short: a Bloom filter trades certainty for size. Give up exact answers and deletion, and a membership test costs a few bits per item and never misses a real member.

Sources

← Home