← Building blocks

Drop duplicate events

Data processing & searchsenior

At-least-once delivery double counts clicks, views and payments.

Say it like this

The click stream is at-least-once, so every event carries a unique id and the counter drops ids it has seen within a window longer than the retry window, which keeps the counts honest without making the producers exactly-once.

Basic solution

Carry a unique event id and keep a window of seen ids; or make the aggregate idempotent (set semantics).

Redis SET NX with TTLBloom filtersKafka exactly-once with transactions

Claim the event id before applying it

Retries and replays deliver the same event id twice. The consumer claims the id atomically in a seen-set with a TTL longer than any retry path; only a successful claim applies the event.

How it works

  1. The producer attaches a unique event id when the event is created, before the first send: a UUIDv7, or a hash of the natural key such as request id plus alias. Every retry of that event carries the same id.
  2. Before applying an event, the consumer tries to claim its id in a seen-set: in Redis, SET id NX EX window, which succeeds only if the id was not already present and gives it an expiry; in a stream processor, a lookup and insert in the task's local state store.
  3. If the claim fails because the id was already there, the consumer drops the event and increments a duplicates metric. If the claim succeeds, the consumer applies the event (increments the count, writes the row) and the id stays recorded until it expires.
  4. The window must be longer than the longest path a duplicate can take: the producer's retry limit, plus the broker's redelivery delay, plus the time a crashed consumer might spend replaying from its last checkpoint. That is usually minutes in practice, so 24 hours is the usual safe choice.
  5. For aggregates that are naturally unaffected by repeats, skip the seen-set entirely: adding a visitor id to a set of visitors per alias, or to a HyperLogLog of them, twice gives the same result as adding it once.
  6. Kafka's exactly-once transactions make a consumer's reads and its writes to other topics commit together, which removes duplicates between topics. They stop at the broker boundary: a write to an external database still needs the idempotent claim above.

Two places duplicates come from

  • Producer retries: the first send succeeded but the acknowledgement was lost in a timeout, so the producer sent again.
  • Consumer reprocessing: the consumer applied the event, then crashed before committing its offset, so after restart it reads the same event again. Both cases deliver the same event id, which is why the id is assigned once at the source.

Worked example

Click counts for the URL shortener

  • 345M click events per day; observed duplicate rate about 0.5 percent from redirect-service retries and consumer restarts, so 1.7M duplicates per day inflating popular links by up to a few percent during incidents.
  • Event id: the redirect service generates a UUIDv7 per redirect and puts it in the event before the first publish; retries reuse it.
  • Seen-set in Redis: SET click:{id} NX EX 86400. 345M keys per day x roughly 60 bytes = 21 GB resident at any time for a 24-hour window. Shard across 4 Redis nodes by id; at 4,000 writes per second average and 40K at peak the atomic SET NX costs well under a millisecond each.
  • Cheaper alternative for the same guarantee: the aggregation job keeps the seen-set in its own RocksDB state keyed by partition, so no network call per event and the state is checkpointed with the offsets. Memory is similar but local.
  • Where dedup is free: unique visitors per alias use a HyperLogLog of visitor ids, so a duplicated click adds the same visitor again and the estimate does not move. Total clicks, which are a plain counter, need the seen-set.
  • Window check: producer retries last at most 30 seconds; consumer replay after a crash covers at most the last checkpoint interval of 5 minutes; a broker redelivery during a rebalance is seconds. A 24-hour window is a thousand times the worst case, and the memory cost is acceptable.
  • Monitoring: the dropped-duplicate counter should sit around 0.5 percent; a jump to 10 percent means a producer is looping, a drop to zero means the seen-set is broken.

Variants and when each wins

Seen-set with TTL (Redis SET NX)

  • One Redis key per event id with an expiry, claimed atomically before the event is applied. It wins for counters and side effects because it is exact within the window; the cost is one network call per event and memory proportional to the events in the window.

Seen-set in consumer state (Kafka Streams, Flink)

  • The same claim, but kept in the stream task's local state store and checkpointed together with the consumer offsets. It wins when a stream processor already exists, because there is no extra store and the dedup state survives restarts exactly in step with the offsets.

Idempotent aggregates

  • Metrics shaped so repeats change nothing: sets, HyperLogLogs, maximum and minimum, upserts keyed by event id. It wins whenever the metric allows it, because no seen-set is needed at all.

Bloom filter seen-set

  • A Bloom filter in place of the exact set, at a tenth of the memory. It wins only for metrics that tolerate slight under-counting, because a false positive drops a genuine event.

Kafka exactly-once transactions

  • Consumer offsets and the records a consumer produces commit atomically. It wins for removing duplicates between topics; it does not cover writes to external databases, which still need idempotent writes.

Recommendation: make the aggregate idempotent where possible; otherwise a seen-set in the stream processor state, or Redis SET NX with a 24-hour window when there is no stream job.

Failure modes

Window shorter than the retry path

  • Duplicates reappear exactly after the TTL passes. It happens because a consumer was down for 3 hours and replayed on restart, but the seen-set entries had a TTL of 1 hour and were already gone. Size the window from the worst-case replay, which is the consumer outage you are prepared to tolerate, not from the typical retry.

Event id assigned on retry

  • The dedup never catches anything even though duplicates are visible in the counts. It happens because the producer generated a new UUID on each attempt, so retries look like new events. Assign the id once when the event is created, before the first send, and log it so you can verify.

Seen-set lookup not atomic with the apply

  • Duplicates still slip through under load. It happens because the consumer ran a GET and then a SET as two separate commands, so two consumers could both see the id as absent and both apply the event. Use SET NX as a single atomic claim and apply the event only when the claim succeeds.

Seen-set store down

  • Consumers either stall completely or start double counting. It happens because Redis is unreachable and the consumer either waits forever for it or skips the check. Decide per metric whether to fail open (count now, risk over-counting) or fail closed (buffer the event, risk delay), and alert on dedup store errors.

Dedup across shards misses

  • Duplicates survive after the topic is repartitioned. It happens because the seen-set lives in each task's local state, and the retried event landed on a different partition whose task had never seen the id. Partition by the same key the event id is derived from so retries land on the same task, or use a shared seen-set.

Interviewer follow-ups

Answer out loud before you open each one.

Why is exactly-once delivery not the answer?

A broker can guarantee exactly-once between its own topics, but the consumer still writes to an external store, and that write plus the offset commit are two systems. Idempotent application at the consumer is what gives exactly-once effect; delivery stays at-least-once.

How do you pick the dedup window?

Take the longest path a duplicate can travel: producer retry limit, broker redelivery, and the maximum time a consumer could be down before replaying from its last checkpoint. Multiply by a safety factor and round up; 24 hours is common because consumer outages of hours happen.

What is the memory cost of a seen-set and how do you reduce it?

Roughly events in the window times bytes per key, so 345M events at 60 bytes is 21 GB. Reduce it by shortening the window where the replay bound allows, using a Bloom filter when under-counting is acceptable, or making the aggregate idempotent so no seen-set is needed.

How does this relate to idempotency keys on an API?

It is the same mechanism on the read side of a queue: a unique key per logical operation, an atomic claim, and a stored outcome. The API version stores and returns the response; the stream version just drops the event. Both need the key assigned once at the source.

Connections

In study paths
Making retries safe
Built on
Hash table · Bloom filter
Pairs with
Make retries safe · Decouple producer from consumer · Compute over events as they arrive · Count big things with small memory · Publish events reliably with the write
Used in
URL Shortener (TinyURL / bit.ly) · Notification System · Video Streaming Platform (YouTube / Netflix)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRedirect service, AggregatorCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon Kinesis Data Streamsclicks topicPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar
Amazon ElastiCacheSeen-setMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon DynamoDBCounts storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra