Jump to content

Streaming deduplication

From Open Lakehouse Wiki
Revision as of 00:53, 25 November 2026 by Open Lakehouse Wiki sync (talk | contribs) (Sync from open-lakehouse/wiki@7c9abaa)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Streaming deduplication
Also known as Stream deduplication
Field Stream processing
Key parts Unique identifier column(s), watermark, deduplication state in the state store
Open source implementations Structured Streaming: dropDuplicates, dropDuplicatesWithinWatermark (Spark 3.5.0 and later); Delta Lake insert-only MERGE in foreachBatch
Related Watermark, Exactly-once semantics, State store, Stateful stream processing
Last verified 23 November 2026 against the Spark 4.3.0 Structured Streaming programming guide (streaming deduplication, recovery semantics) and Real-time Mode guide, python/pyspark/sql/dataframe.py at tag v4.3.0 of apache/spark, SPARK-42931, and the Delta Lake merge documentation.

In Apache Spark Structured Streaming, streaming deduplication is removing repeated records from a stream by a unique identifier, so that each event is passed on once even if the source delivers it several times. Spark keeps the identifiers it has already seen as state; dropDuplicates does this with or without a watermark, and dropDuplicatesWithinWatermark, added in Spark 3.5.0, deduplicates within the watermark delay when duplicates carry different event times.[1][2] Duplicates are common in streaming because producers and connectors retry, and at-least-once delivery means a record may arrive more than once.

How does dropDuplicates work on a stream?

On a batch DataFrame, dropDuplicates (available since Spark 1.4.0) simply drops duplicate rows. On a streaming DataFrame, it keeps the data it needs from all earlier triggers as state in order to drop duplicates in later ones.[3] The Spark guide describes two ways to use it:[1]

  • Without a watermark, there is no bound on when a duplicate may arrive, so the query keeps state for every record it has ever seen. State grows for the life of the query.
  • With a watermark, if duplicates arrive no later than a known bound, the query sets a watermark on an event-time column and deduplicates on both the identifier and the event-time column. Spark then drops state for records older than the watermark, which bounds state.

Records older than the watermark are dropped, to avoid any chance of emitting a duplicate.[3]

events = spark.readStream.table("main.iot.raw_events")   # columns: event_id, event_time, ...

# Unbounded state: every event_id is remembered
dedup_all = events.dropDuplicates(["event_id"])

# Bounded state: event_id plus event_time, cleaned by the watermark
dedup_bounded = (events
    .withWatermark("event_time", "10 seconds")
    .dropDuplicates(["event_id", "event_time"]))

What is dropDuplicatesWithinWatermark?

The bounded form of dropDuplicates works only if the event time is part of the identity of a record, so that true duplicates share it. Sometimes they do not, for example when a non-idempotent writer sets the event time at write time and a retried write gets a new one. dropDuplicatesWithinWatermark handles this case: it deduplicates on the identifier alone, within the time range of the watermark.[1]

dedup = (events
    .withWatermark("event_time", "10 hours")
    .dropDuplicatesWithinWatermark(["event_id"]))

The guarantee is that events are deduplicated as long as the distance between the earliest and the latest copy is smaller than the watermark delay, so the delay should be longer than the largest time difference expected between duplicates. A watermark is required, and the operator works only on streaming DataFrames. Data older than the watermark is dropped.[3][1]

dropDuplicates vs dropDuplicatesWithinWatermark

dropDuplicates without watermark dropDuplicates with watermark dropDuplicatesWithinWatermark
Available since Spark 1.4.0[3] Spark 1.4.0[3] Spark 3.5.0[2]
Key Identifier columns[1] Identifier and event-time columns[1] Identifier columns only[1]
State Unbounded[1] Bounded by the watermark[1] Bounded by the watermark[1]
Duplicates with different event times Removed[1] Not removed, because event time is part of the key Removed if within the watermark delay[3]
Batch DataFrames Supported[3] Supported[3] Streaming only[3]
Real-time Mode (Spark 4.3.0) Supported[4] Not supported[4]

The deduplication columns are part of the query's state schema: changing their number or type is not allowed between restarts from the same streaming checkpoint.[5] The plain distinct operation is not supported on streaming DataFrames.[6]

Deduplicating against a table

dropDuplicates only removes duplicates that the query itself sees within its state. To avoid inserting a record that is already in the target table, for example one written by an earlier query or a backfill, the Delta Lake documentation uses an insert-only MERGE inside foreachBatch, which inserts only rows whose key is not yet in the table.[7]

from delta.tables import DeltaTable

target = DeltaTable.forName(spark, "main.iot.events")

def insert_new(batch_df, batch_id):
    (target.alias("t")
        .merge(batch_df.dropDuplicates(["event_id"]).alias("s"),
               "t.event_id = s.event_id")
        .whenNotMatchedInsertAll()
        .execute())

(dedup_bounded.writeStream
    .foreachBatch(insert_new)
    .option("checkpointLocation", "/checkpoints/iot_events")
    .start())

Deduplication in the stream and an insert-only merge into the table can be combined: the first bounds the work per batch, the second protects the table across queries and restarts.

See also

References

  1. ↑ 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 Structured Streaming: Streaming Deduplication (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  2. ↑ 2.0 2.1 SPARK-42931: dropDuplicates within watermark. Apache Software Foundation JIRA.Retrieved 2026-11-23.
  3. ↑ 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 python/pyspark/sql/dataframe.py (Apache Spark v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  4. ↑ 4.0 4.1 Real-time Mode (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  5. ↑ Structured Streaming: Recovery Semantics after Changes in a Streaming Query (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  6. ↑ Structured Streaming: Unsupported Operations (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  7. ↑ Table deletes, updates, and merges: Upsert from streaming queries using foreachBatch. Delta Lake (Linux Foundation).Retrieved 2026-11-23.