Video in progress

When would you propose a Bloom filter instead of a HashSet to deduplicate billions of events, and what are its risks?

When a full HashSet doesn't fit in memory and you can tolerate a small percentage of errors in a "present" answer. A Bloom filter takes a few bits per element, but gives false positives and can't remove an element, so it is usually used as a fast filter in front of an exact check.

📖 Answer

The math: 2 billion event ids (UUIDs) per day. In a HashSet<String>, one UUID string + a Node is about 100+ bytes, so 200 GB. It doesn't fit on one host.

A Bloom filter: a bit array of m bits and k hash functions. On insert, k bits are set, and on lookup you check whether all of them are set. A "no" answer is always exact, while a "yes" can be wrong. For a 1% error probability you need about 9.6 bits per element, so about 2.4 GB for 2 billion.

BloomFilter<CharSequence> seen = BloomFilter.create(
        Funnels.stringFunnel(StandardCharsets.UTF_8), 2_000_000_000L, 0.01);

if (!seen.mightContain(eventId)) {
    seen.put(eventId);
    process(event);                  // definitely new
} else if (!store.exists(eventId)) { // probably a duplicate: exact check
    seen.put(eventId);
    process(event);
}

With this scheme the Bloom filter saves 99% of the DB queries, and exactness is preserved.

Risks, and the things that affect the decision:

  • The cost of a false positive. If you rely only on the Bloom filter, 1% of real events get dropped as "duplicates". That is unacceptable for payments or orders; for ad clicks it is probably fine.
  • No removal. For deduplication over a time window, you need to rotate several filters (one per hour) or use a counting Bloom filter.
  • You have to know the size in advance. If more elements are added than planned, the error probability rises quickly, so you need a fill-level metric.
  • Distributed state. With several instances, the filter is separate on each, so partition by key (a Kafka partition) or use RedisBloom.
  • On restart, the in-memory filter is lost, so you need a snapshot or a rebuild plan.

There are alternatives too: shorten the key to a 64-bit hash and keep it in a primitive set (the collision probability is small, but not zero), or hand deduplication to the storage layer (a unique constraint, an idempotency key). Often the most reliable solution is the last one, and the Bloom filter reduces its load.