Let’s Get Certified
Module 11 / 13 · Structured Streaming

Bound deduplication with event time

Predict which duplicates and late records a stateful streaming query can recognize.

Bound deduplication with event time

Work through the decision

A station sends the same event ID at 10:00 and 10:03. An unrelated event at 10:30 later advances observed event time. The team wants duplicate suppression with a ten-minute lateness allowance. Why does adding event time to the duplicate key change the result?

Check your reasoning

With the pair (ID, timestamp) as the key, the two timestamps are distinct. To deduplicate on ID across nearby event times on a compatible Spark release, apply withWatermark to the event-time column and use dropDuplicatesWithinWatermark on ID. Choose a delay large enough to cover the expected difference between copies. A watermark follows observed event-time progress rather than a wall-clock timer.

Watch the source lesson at 2:07:09

Compare the choices

Event-time watermark
Define a lateness delay on an event-time column so eligible operators can finalize results or evict state as observed event time advances. Beyond the guarantee, arrival alone cannot determine acceptance.
Within-watermark key deduplication
Use dropDuplicatesWithinWatermark with a watermark and the business ID when duplicates can have different event times inside the delay bound.
Unbounded key history
A streaming deduplication keyed only by ID without state eviction may retain keys indefinitely. Estimate growth and decide whether durable uniqueness belongs downstream.
Event-time window aggregation
Assign events to time windows from their event timestamps and aggregate by window and optional key. Define window length, slide and acceptable lateness.

Test the decision

A query without a watermark may need to retain all historical keys. With bounded state, very late records can be dropped, and the query does not promise all-time uniqueness. For windowed counts derive a proper timestamp, select the needed columns, group by event-time window and key, and choose a compatible output mode and sink.

Choose a deduplication horizon

Measure the largest event-time difference between legitimate repeats of one ID. Choose a watermark delay exceeding that difference and check the resulting state size under representative traffic. The operator requires a streaming DataFrame with an event-time watermark. Advancing wall-clock time alone does not advance the event-time watermark.

Apache Spark · dropDuplicatesWithinWatermark

Practice the guide skills

  1. Project station and fare, group events into event-time windows and predict when a window becomes eligible for final output. Watch 2:07:09 · Continue at 2:08:31
  2. Replay an ID with a changed timestamp and contrast unbounded key tracking with watermark-bounded deduplication. Watch 2:10:42 · Continue at 2:11:03

Official objectives for this lesson

Lab · Replay duplicate and late events

Use a Python 3 virtual environment with JDK 17 or 21 available. Install PySpark with python -m pip install pyspark==4.0.1. Save the code as lab.py and run python lab.py. Run a local Structured Streaming query over a temporary JSON directory. Predict which IDs the memory sink will retain after each arrival. The checkpoint, input and in-memory table are disposable.

import json
from pathlib import Path
from tempfile import TemporaryDirectory
from pyspark.sql import SparkSession

spark = (SparkSession.builder.master("local[2]").appName("ReplayEvents")
         .config("spark.sql.shuffle.partitions", "2")
         .config("spark.sql.session.timeZone", "UTC").getOrCreate())
try:
    with TemporaryDirectory() as tmp:
        inbox = Path(tmp) / "inbox"
        inbox.mkdir()
        stream = (spark.readStream.schema("event_id string, event_time timestamp")
                  .json(str(inbox)).withWatermark("event_time", "10 minutes")
                  .dropDuplicatesWithinWatermark(["event_id"]))
        query = (stream.writeStream.format("memory").queryName("replay_result")
                 .outputMode("append").option("checkpointLocation", tmp + "/checkpoint")
                 .start())
        try:
            batches = [[("A", "10:00")], [("A", "10:03"), ("B", "10:04")],
                       [("C", "10:30")], [("late", "10:01")]]
            for number, batch in enumerate(batches, 1):
                rows = [{"event_id": key, "event_time": "2026-10-09T" + clock + ":00Z"}
                        for key, clock in batch]
                staged = Path(tmp) / "next.json"
                staged.write_text("\n".join(json.dumps(row) for row in rows))
                staged.rename(inbox / f"part-{number}.json")
                query.processAllAvailable()
                ids = spark.table("replay_result").select("event_id").orderBy("event_id")
                print(number, ",".join(row.event_id for row in ids.collect()))
        finally:
            query.stop()
finally:
    spark.stop()
Check the result
1 A
2 A,B
3 A,B,C
4 A,B,C

The second A is a repeat inside the delay even though its event timestamp changed. C advances the maximum event time. After Spark advances the watermark, the final 10:01 record is too late for this run. Change its time to 10:28 and run again. A watermark bounds how long keys are remembered, so this design cannot promise uniqueness across all history.

Related lesson · Auto Loader, COPY INTO, and Lakeflow Connect

Knowledge check

Bound deduplication with event time quiz

Answer 3 questions. Check each answer for an explanation.

Worked example · Bound deduplication with event time