Skip to content
Silver 7 min read · dropDuplicates 2 practice problems ↓

Deduplicating a stream

The same event often arrives twice: an app retries after a timeout, or a replay sends old messages again. Counting both makes every number wrong. This lesson shows where duplicates come from, the three ways Spark can drop them, and why only one of them is safe for a stream that runs for months.

Step 4 · Structured Streaming · Silver · Stateful streams, lesson 3 of 3

Read first: Watermarks and late data (skip if you know it)

In plain words first

A doorman checks names against a guest list, so nobody gets in twice. He could remember every name he has ever seen, which works until the list fills a library. Or he could remember tonight's names only, and forget them in the morning: a small list, and still nobody gets in twice tonight.

Spark has the same two options. Remembering every event id forever is correct but grows without end. Remembering ids only until the watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → passes them is what the doorman does: small, and good enough as long as copies arrive close together.

Where duplicates come from

  • A producerproducer: An application that writes events to a topic. Learn more → that retries after a timeout sends the same event twice, often with a slightly later timestamp.
  • A step upstream that is at-least-onceat-least-once: No event is lost, but after a failure some can be processed or written twice. Learn more → (a KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more →, a queue reader) sends messages again after a failure.
  • A sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → is backfilled while the live feed keeps running, and the two overlap.

Spark's exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → means each micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → is written once. It does not remove duplicates that are already in the input: those need a stable event id and a deduplication step. Delivery guarantees end to end follows the whole chain, from producer to reader.

Three ways to deduplicate a stream

CallComparesRemembersCatches a retry with a new timestamp?
dropDuplicates(["event_id"])The idEvery id ever seen, foreverYes
withWatermark("ts", d).dropDuplicates(["event_id", "ts"])The id and the exact timestampUntil the watermark passes the timestampNo: a different timestamp is a different row
withWatermark("ts", d).dropDuplicatesWithinWatermark(["event_id"]) (Spark 3.5+)The idUntil the watermark passes the first copy's time plus the delayYes, if it arrives in time

The first is correct but never forgets: a stream that runs for a year remembers a year of ids. The second forgets, but misses the most common duplicate, a retry stamped a few seconds later. The third is what you usually want: it compares only the id, and forgets each id once the watermark has moved past it.

Use whatever truly identifies one event as the key. If a retry keeps the original timestamp and ids can be reused (an app that restarts its counter after a reinstall), the pair (event_id, ts) is the identity, and the second form is correct and small.

Choosing the delay

A copy is caught only while its id is still remembered, so the watermark delay must cover the time between an event and its latest possible copy: the retry back-off, plus how far behind a replay can be. If replays can be hours late, a short watermark lets them through, and the safety net has to be at the sink.

Deduplicating at the sink

When the target is a table, a MERGE on the event id is a second line of defence that never forgets: whenNotMatchedInsertAll() with t.event_id = s.event_id inserts each event once, however late its copy arrives. It costs a join against the table on every batch, so partitionpartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more → or cluster the table by date and add the date to the merge condition when you can. Drop duplicates inside the batch first: MERGE fails when two source rows match the same target row.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Drop retried events from a stream without remembering every id forever.

Production patternPySpark · Drop retried events without keeping every id forever
import json, os

os.makedirs("lab/dedup/in", exist_ok=True)


def land(name, events):
    with open(f"lab/dedup/in/{name}.json", "w") as f:
        f.write("\n".join(json.dumps({"event_id": e, "event_time": f"2026-01-01 {t}"})
                           for e, t in events))


def run():
    (spark.readStream.schema("event_id STRING, event_time TIMESTAMP")
        .json("lab/dedup/in")
        .withWatermark("event_time", "10 minutes")
        .dropDuplicatesWithinWatermark(["event_id"])   # Spark 3.5+
        .writeStream.format("parquet")
        .option("path", "lab/dedup/out")
        .option("checkpointLocation", "lab/dedup/_chk")
        .trigger(availableNow=True)
        .start().awaitTermination())
    ids = [r.event_id for r in spark.read.parquet("lab/dedup/out").collect()]
    print(sorted(ids))


land("a", [("e1", "10:00:00"), ("e2", "10:01:00"), ("e1", "10:00:00")])
run()                      # the duplicate in the same batch is dropped
land("b", [("e2", "10:01:30"), ("e3", "10:05:00")])
run()                      # e2 again: a retry with a slightly later timestamp

Output from a real run

['e1', 'e2']
['e1', 'e2', 'e3']

What to notice:

  • The repeated e1 in the first file was dropped.
  • e2 came again with a timestamp 30 seconds later and was still recognised as a duplicate: only the id is compared.
  • Each id is kept only until the watermark passes it, so the state does not grow forever.

Common mistakes

  • dropDuplicates on an id without a watermark — A stream that runs for a year remembers a year of ids. Add a watermark and use dropDuplicatesWithinWatermark.
  • Adding the timestamp to the keys to keep memory small — A retry of event e1 stamped 12:00:03 instead of 12:00:00 is a different (id, ts) pair and gets through. Deduplicate on the id with dropDuplicatesWithinWatermark(["event_id"]).
  • A watermark shorter than the replay delay — With a 10-minute watermark, a copy replayed 2 hours later arrives after its id was forgotten and is written again. Size the delay from the replay delay, or MERGE at the sink.
  • Relying on exactly-once to remove input duplicates — Two copies of e1 in the input both reach the sink: exactly-once only means each micro-batch is written once. Deduplicate on a stable event id.

Key takeaways

  • Duplicates come from producer retries, at-least-once steps that resend after a failure, and backfills that overlap the live feed.
  • dropDuplicatesWithinWatermark(["event_id"]) catches retries and forgets old ids: the usual choice.
  • If a retry keeps its original timestamp and ids can be reused, (event_id, ts) is the identity, and dropDuplicates on both is correct.
  • A MERGE on the id at the sink catches copies of any age, at the cost of a join per batch.

Interview prep

THE QUESTION

"A mobile SDK retries events, so the same event_id can arrive twice, up to 10 minutes apart. How do you deduplicate in the stream?"

withWatermark on the event time with a delay of at least 10 minutes plus normal lateness, then dropDuplicatesWithinWatermark(["event_id"]). It compares only the id, so a retry with a new timestamp is caught, and each id leaves state once the watermark passes, so state stays bounded. Plain dropDuplicates(["event_id"]) would keep every id forever; adding the timestamp to the keys would bound state but miss retries. If copies can be later than the watermark, add a MERGE on event_id at the sink as a second line of defence.

Avoid: "dropDuplicates on the id" with no watermark. It works on day one and runs out of memory months later.

Follow-ups · answer out loud, then open

Follow-up"Why not add the timestamp to the dedup keys to bound the state?"
Because the typical duplicate is a retry with a slightly different timestamp. With the timestamp in the keys, the retry is a different row and gets through. dropDuplicatesWithinWatermark bounds state while comparing only the id.
Scenario"Replays from a backfill can arrive a day later. How do you avoid duplicates in the table?"
A one-day watermark would mean a day of ids in state; that may be fine, or too big. The robust answer is a MERGE on event_id at the sink, which catches any copy however late, combined with a short in-stream dedup for the common retries.
Trap"Structured Streaming is exactly-once, so my output has no duplicates."
Exactly-once is about Spark committing each batch once. Duplicates already in the input are passed through unless you remove them.

Check yourself

3 questions

Which call keeps memory small and still catches a retry stamped 5 seconds later?

Show the answer

dropDuplicatesWithinWatermark(["event_id"]) with a watermark. It compares the id only, and forgets it once the watermark passes.

What happens to state with dropDuplicates(["event_id"]) and no watermark?

Show the answer

It keeps every id forever. Without a watermark Spark cannot know an id will not appear again.

Why deduplicate a micro-batch before a MERGE?

Show the answer

MERGE fails when two source rows match one target row. A target row can be matched by only one source row per MERGE.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Streams into the lakehouse · 7 min read
Streaming into Delta tables
Write a stream into a Delta table exactly once, and read a Delta table as a stream.

Related lessons

Previous: Event-time windows

Primary sources: Streaming deduplication · dropDuplicatesWithinWatermark