Sub topic 11
Why you cannot delete from a Bloom filter
This chapter assumes you know how a Bloom filter inserts and queries items with k hash positions in an m-bit array, and that you are comfortable with bitwise operators in Python. It explains why deletion breaks the filter's guarantees and what a safe workaround looks like.
The tempting idea
Insertion sets k bits to 1. Deletion looks like the reverse: compute the same k positions and set them to 0. This fails because bits are shared. Any bit may have been set by several different items.
Suppose "apple" and "banana" both hash to bit 12. If you delete "apple" by clearing its bits, bit 12 becomes 0. A later query for "banana" checks bit 12, finds 0, and answers "definitely not present". That is a false negative, even though "banana" was inserted and never removed.
Why this matters
The central promise of a Bloom filter is that it never gives a false negative. Code that uses the filter often relies on this: a "no" answer lets it skip an expensive lookup safely. One careless deletion removes that guarantee for every item that shares a bit with the deleted one. You also cannot tell which items are affected, because the filter does not store the items.
Leaving the bits set is not a fix either. You cannot know whether another item still needs a bit, so the only safe choice is to never clear any bit.
Demonstrating the failure
This code adds a remove method that clears bits. It reuses the BloomFilter class from earlier in the tutorial. To make the collision certain, it uses a tiny filter.
import hashlib
import math
class BloomFilter:
def __init__(self, expected_items, false_positive_rate):
self.m = math.ceil(-expected_items * math.log(false_positive_rate) / (math.log(2) ** 2))
self.k = max(1, round((self.m / expected_items) * math.log(2)))
self.bits = bytearray((self.m + 7) // 8)
def _positions(self, item):
digest = hashlib.sha256(item.encode("utf-8")).digest()
h1 = int.from_bytes(digest[:8], "big")
h2 = int.from_bytes(digest[8:16], "big") | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def add(self, item):
for pos in self._positions(item):
self.bits[pos // 8] |= 1 << (pos % 8)
def might_contain(self, item):
return all(self.bits[pos // 8] & (1 << (pos % 8)) for pos in self._positions(item))
def unsafe_remove(self, item):
for pos in self._positions(item):
self.bits[pos // 8] &= ~(1 << (pos % 8))
# A deliberately crowded filter: 10 expected items, 50% false positive rate.
bf = BloomFilter(expected_items=10, false_positive_rate=0.5)
words = [f"word{i}" for i in range(10)]
for w in words:
bf.add(w)
bf.unsafe_remove("word0")
lost = [w for w in words[1:] if not bf.might_contain(w)]
print("Items wrongly reported as absent:", lost)The exact list depends on the hash values, but with a crowded filter it is usually not empty. Every name in it is a false negative that the deletion caused.
The standard fix: counting Bloom filters
A counting Bloom filter replaces each bit with a small counter. Insertion increments the k counters. Deletion decrements them. A query reports "maybe present" only if all k counters are above zero.
Because a shared position holds a count of 2 after both items are added, deleting one item leaves it at 1, and the other item is still found. The cost is memory. With 4-bit counters the filter is about four times larger than a plain Bloom filter.
Two cautions apply:
- Only delete items you know you inserted. Deleting an item that was never added decrements counters that belong to other items and can cause false negatives again.
- A counter that reaches its maximum value can overflow. Implementations usually make it stay at the maximum and never decrement it, which avoids false negatives but leaves a few permanently set positions.
Exercise
A Bloom filter holds "cat" and "dog", and both share one bit position. You clear all k bits of "cat". Which kind of error can now occur for "dog", and why?
Show answer
A false negative. The shared bit is now 0, so a query for "dog" sees an unset bit and reports that "dog" is definitely absent, even though it was inserted.
Exercise
Why does a counting Bloom filter handle the shared-bit case correctly, and what does it cost?
Show answer
Each position holds a count, so a shared position reads 2 after both items are added. Deleting one item reduces it to 1, which keeps the other item visible. The cost is more memory, because every bit becomes a multi-bit counter, commonly 4 bits.