Video in progress

You need to remove duplicates from events arriving in a stream, but you can't store all IDs forever. Which algorithm and guarantee do you choose?

First I agree on the guarantee with the business: "exact dedup within an N-hour window" or "approximate, with a small error". For exact, a key-value store with a TTL (Redis SET NX EX, RocksDB) and a time window. For approximate, Bloom filters rotated over time. The most reliable is to make the consumer idempotent, so that dedup becomes an optimization.

📖 Answer

Where do duplicates come from? A producer retried, a Kafka consumer re-received a message whose offset wasn't committed after a rebalance, a mobile app sent the request twice when the network dropped. Duplicates usually arrive a few seconds or minutes after the original. That matters: you don't need infinite memory, you need a window.

The exact, windowed variant: SET event:{id} 1 NX EX 86400. NX gives an atomic "exists or not" check. Memory: 100 million events a day × ~80 bytes of Redis overhead ≈ 8 GB. Expensive, but exact. Local RocksDB with a TTL is cheaper, but when partitions are reassigned, the state also has to move (a Kafka Streams state store does exactly this).

The approximate variant: Bloom filters split by time slice: a separate filter per hour, the last 24 are kept, and the oldest is dropped. A lookup checks all of them. Memory is several times smaller. But a false positive means a real event gets thrown away as a "duplicate". In an analytics counter, a 0.1% loss can often be tolerated. In payments, absolutely not.

If the producer assigns a monotonic sequence number per partition, it's enough to store only the "last seen number", which is O(number of producers) memory. Kafka's idempotent producer works exactly like that.

An idempotent consumer. In the DB, UNIQUE (event_id) and INSERT … ON CONFLICT DO NOTHING, or an upsert by business key. In this case the dedup layer only reduces load, and correctness is guaranteed in the DB. For payments and balances, this is the only variant I trust.

How I choose the window length: I measure the distribution of the delay between a duplicate and its original in real data. If p99.99 is 40 minutes, 24 hours is excessive and 1 hour is a gamble. For a duplicate that arrives outside the window, I add a metric and an alert; it shows "where the guarantee ends".