Sub topic 12
Counting Bloom filters
This chapter assumes you know how a standard Bloom filter inserts and queries items with k hash positions in an m-bit array. It also assumes you can read basic Python and bitwise operators. Here you will see why deletion breaks a standard filter and how a counting Bloom filter fixes that.
The deletion problem
In a standard filter, a bit set to 1 does not record which items set it. Two items can share a position. If you clear the bits of one item to delete it, you may also clear bits that belong to another item. A later query for that other item would then return False, which is a false negative. That breaks the main guarantee of the structure.
The idea: replace bits with counters
A counting Bloom filter replaces each bit with a small counter.
- To insert an item, increment the counters at its k positions.
- To delete an item, decrement the counters at its k positions.
- To query, check that all k counters are greater than zero.
A shared position now holds a count of 2 or more. Deleting one item lowers it to 1, so the other item is still found.
Implementation
This class reuses the double hashing from the earlier chapter. It stores one byte per counter, which gives a maximum count of 255.
import hashlib
import math
class CountingBloomFilter:
MAX_COUNT = 255
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.counters = bytearray(self.m)
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):
if self.counters[pos] < self.MAX_COUNT:
self.counters[pos] += 1
def might_contain(self, item):
return all(self.counters[pos] > 0 for pos in self._positions(item))
def remove(self, item):
if not self.might_contain(item):
return False
for pos in self._positions(item):
if 0 < self.counters[pos] < self.MAX_COUNT:
self.counters[pos] -= 1
return True
cbf = CountingBloomFilter(expected_items=1000, false_positive_rate=0.01)
cbf.add("apple")
cbf.add("banana")
print(cbf.might_contain("apple")) # True
cbf.remove("apple")
print(cbf.might_contain("apple")) # almost certainly False
print(cbf.might_contain("banana")) # TrueA counter that reaches the maximum stops changing. It is never decremented, because its true count is unknown. This avoids false negatives at the cost of a counter that stays stuck above zero.
Costs and common errors
- Memory. One byte per counter uses 8 times the memory of a bit. Four-bit counters are common in practice and cost 4 times as much. With 4 bits, overflow is rare for well-sized filters but still possible.
- Deleting an item that was never added. The check in
removereduces the risk, but a false positive can still pass it. Decrementing counters that belong to other items can then cause false negatives. Only delete items you know were inserted. - Duplicate inserts. Adding the same item twice increments its counters twice. You must delete it twice before it disappears.
- Overflow. If many items hit one counter, it can saturate. Size the filter for the real item count to keep this unlikely.
When to use it
Use a counting Bloom filter when the set changes over time and items leave it, such as a cache whose entries expire. If the set only grows, the standard filter is smaller and simpler. If you need deletion with less memory, the cuckoo filter covered later in this tutorial is often a better fit.
Exercise
A counting Bloom filter has 4-bit counters, so the maximum count is 15. Why should a counter that reaches 15 never be decremented, and what is the cost of that rule?
Show answer
Once a counter saturates at 15, its real count may be higher, so the filter no longer knows how many items share it. Decrementing could bring it to zero while items still depend on it, causing a false negative. Never decrementing keeps the no-false-negative guarantee. The cost is that the counter stays above zero forever, which can add false positives.
Exercise
You insert "x" once and then call remove("x") twice. The second call finds "x" absent and returns False. Under what circumstance could the second call still decrement counters, and what harm results?
Show answer
If other items have raised all k of x's counters above zero, might_contain("x") returns True, which is a false positive. The second remove then decrements those shared counters. An item that depends on them can be pushed to a zero counter, so it produces a false negative.