Deduplicate streaming records

Many streaming sources deliver the same event more than one time. For example, a web server with network issues might resend the same log entry, or a sensor might send a duplicate reading. With a Delta Lake sink, Structured Streaming provides exactly-once processing. See Delta Lake table streaming reads and writes. Exactly-once processing doesn't remove duplicates that the source itself produces.

This page compares the ways to remove duplicate records from a stream, shows when to use each, and explains how the deduplication operators keep and evict state.

Choose between deduplication and SCD Type 1

Two kinds of workloads filter repeated records from a stream:

  • Deduplication: An upstream source produces duplicate events, for example because a producer retries a write that already succeeded. You want each event to appear one time.
  • Slowly changing dimensions (SCD) Type 1: For each key, such as a user ID or product ID, you want to keep only the latest value of other columns, such as a user's current address or a product's current price.

This page covers deduplication. For SCD Type 1, see Change data capture and snapshots and The AUTO CDC APIs: Simplify change data capture with pipelines.

Choose a deduplication method

The right method depends on whether occasional late duplicates are acceptable and on how many unique keys the stream has.

Method Duplicates removed State size Use when
dropDuplicatesWithinWatermark Records with the same key whose event time is within the watermark delay of the first record's event time. Bounded by the watermark. Streams where duplicates arrive within the watermark delay of each other.
dropDuplicates with the event-time column Records whose key columns and event time are both identical. Bounded by the watermark. Duplicates are exact copies of the original record, such as resent records from non-idempotent retries.
dropDuplicates without the event-time column All records with the same key, at any time. Grows with every new key. State isn't evicted. You need every duplicate removed, and the number of unique keys is small and bounded.
Sink-based deduplication All records with the same key, at any time. Stored in the target table, not in streaming state. You need every duplicate removed, and the number of unique keys is unbounded.

Deduplicate records within a watermark

Use dropDuplicatesWithinWatermark when duplicates arrive within the watermark delay of each other. It works in Structured Streaming and in Lakeflow pipelines. For pipeline examples, see Optimize stateful processing with watermarks. You must define a watermark on the stream. Without one, the query fails to start.

The operator keeps each key in state until the watermark reaches the event time of the key's first record plus the watermark delay, then evicts it. To deduplicate on an id column with a 30-second watermark delay, use the following code:

Python

(spark.readStream
  # ...
  .withWatermark("timestamp", "30 seconds")
  .dropDuplicatesWithinWatermark(["id"])
)

Scala

spark.readStream
  // ...
  .withWatermark("timestamp", "30 seconds")
  .dropDuplicatesWithinWatermark(Seq("id"))

In the following examples, records are shown as (id, timestamp). With these settings, after the stream receives (foo, 10), it drops (foo, 20) and (foo, 30) as duplicates. The key foo expires when the watermark reaches 40, the first record's event time plus the delay. If a micro-batch that evicts state with a watermark of at least 40 completes before (foo, 80) arrives, foo has been evicted from state, and the stream keeps (foo, 80) as a new record. Evicting keys keeps state from growing without limit.

Set the watermark delay to cover the expected difference in event time between an original record and its duplicates. For example, if your source documents that 99% of duplicates have an event time within 30 seconds of the original record's event time, a 30-second delay removes about 99% of duplicates. The operator considers only the columns you pass to it, so records with the same id and different event times are duplicates.

For details on when keys are evicted, see How streaming deduplication works.

Drop exact duplicate records

dropDuplicates treats every column you pass as part of the deduplication key. To let the operator evict state, define a watermark and pass the watermarked event-time column as one of the key columns:

Python

(spark.readStream
  # ...
  .withWatermark("timestamp", "30 seconds")
  .dropDuplicates(["id", "timestamp"])
)

Scala

spark.readStream
  // ...
  .withWatermark("timestamp", "30 seconds")
  .dropDuplicates(Seq("id", "timestamp"))

Because the event time is part of the key, (foo, 10) and (foo, 20) are different records, and the stream keeps both. Only a second (foo, 10) is a duplicate. Use this method when duplicates are exact copies of the original record, which happens when a component in your data architecture retries writes without idempotency.

If you call dropDuplicates on a stream without passing the watermarked event-time column, the operator doesn't evict state. State then grows with every new key, which can degrade query performance and cause out-of-memory errors. If the stream defines a watermark, the operator still drops records that arrive behind the watermark, including the first record for a key it hasn't seen. See Watermarks and late records. When you want to deduplicate on a subset of columns that excludes the event time, use dropDuplicatesWithinWatermark.

Remove all duplicates with a bounded set of keys

dropDuplicatesWithinWatermark doesn't remove duplicates that arrive after a key is evicted. With a 30-second watermark delay, the stream keeps both (foo, 10) and (foo, 80) when a micro-batch that evicts state with a watermark of at least 40 completes before (foo, 80) arrives. If your workload needs every duplicate removed, and the total number of unique keys is small and bounded, such as country IDs or product IDs, call dropDuplicates with only the key columns:

Python

(spark.readStream
  # ...
  .dropDuplicates(["id"])
)

Scala

spark.readStream
  // ...
  .dropDuplicates(Seq("id"))

The operator keeps every unique id in the state store for the life of the query. This approach deduplicates with low latency, at the cost of state store size and memory. Don't use it when the number of unique keys grows without limit.

Remove all duplicates with an unbounded set of keys

Some tables must contain no duplicates, even though the number of unique keys is unbounded. For example, a table of credit card purchases used to train a fraud detection model can't contain duplicate purchases, and new purchase IDs arrive continuously. For these workloads, use the target table as the source of truth for which records have already been written, instead of keeping keys in streaming state.

Deduplicate with AUTO CDC in pipelines

In Lakeflow pipelines, use the AUTO CDC APIs with the deduplication columns as keys and a column that orders the records, such as an ingestion timestamp, as the sequencing column. AUTO CDC upserts by key. With SCD Type 1, the target table holds at most one row per key. SCD Type 2 keeps a history of changes for each key. See The AUTO CDC APIs: Simplify change data capture with pipelines.

Deduplicate with MERGE in foreachBatch

With a Delta Lake sink, use foreachBatch to run an insert-only MERGE for each micro-batch. The WHEN NOT MATCHED THEN INSERT clause writes only records whose keys aren't already in the target table. MERGE doesn't deduplicate records within the micro-batch itself, so deduplicate each micro-batch before you merge it. For examples, see Data deduplication when writing into Delta Lake tables and Upsert from streaming queries using foreachBatch.

With a non-Delta Lake sink, use the sink's connector in foreachBatch or foreach to write a record only if it doesn't already exist. For example, with an online transaction processing (OLTP) database, insert a row only when its key isn't present. An append-only sink can't check for existing keys, so use a sink that supports MERGE or conditional inserts. See Use foreachBatch to write to arbitrary data sinks.

Deduplicate a table with a batch query

To remove duplicates from an existing table with a batch query, keep one row per key. The following queries keep the most recent row for each id in an events table, based on the event_time column.

To keep the most recent row with max_by, run the following query:

SELECT latest.*
FROM (
  SELECT max_by(struct(*), event_time) AS latest
  FROM events
  GROUP BY id
);

To keep the most recent row with a window function, run the following query:

SELECT *
FROM events
QUALIFY row_number() OVER (PARTITION BY id ORDER BY event_time DESC) = 1;

When two rows for the same id have the same event_time, both queries keep one of them, and which one is kept isn't deterministic.

How streaming deduplication works

This section describes how dropDuplicates and dropDuplicatesWithinWatermark keep and evict state in queries that don't use real-time mode. Read it when you need to know exactly which duplicates a query removes.

Real-time mode handles late records and state cleanup differently from the micro-batch behavior that this section describes.

Watermarks and late records

The watermark of a stream is the event time before which the stream expects no new records. Structured Streaming computes it at the end of each micro-batch as the largest event time seen so far minus the watermark delay. The next micro-batch uses that watermark to evict state. withWatermark("timestamp", "10 minutes") sets a watermark delay of 10 minutes. The watermark itself is a timestamp that advances as data arrives.

For example, if the largest event time seen is 250 seconds and the watermark delay is 100 seconds, the watermark is 150 seconds.

Deduplication operators drop a record as late when its event time is at or before the late-record watermark, which is the watermark that the previous micro-batch used to evict state. They count late records in the stateOperators.numRowsDroppedByWatermark metric. Structured Streaming doesn't write late records to a dead-letter queue.

The late-record watermark lags the eviction watermark by one micro-batch. For example, with a watermark delay of 100 seconds, suppose micro-batch N is the first micro-batch of the stream:

  • Micro-batch N contains records at 250 and 140 and processes both. After it completes, the watermark moves to 150.
  • Micro-batch N+1 evicts state with a watermark of 150. Its late-record watermark is still the initial watermark, so it doesn't drop a record at 140 as late.
  • Micro-batch N+2 has a late-record watermark of 150, so it drops records at or before 150 as late.

See Apply watermarks to control data processing thresholds.

Compare the deduplication operators

Behavior dropDuplicates dropDuplicatesWithinWatermark
Requirement for evicting state Define a watermark, and pass the watermarked event-time column as a key column. Define a watermark. The query fails to start without one.
When a key is evicted When the watermark reaches the event time stored in the key. When the watermark reaches the event time of the first record with that key plus the watermark delay.
Columns in the deduplication key All columns you pass. To evict state, the key must include the event-time column. All columns you pass. The event-time column doesn't need to be one of them.

The following table shows which pairs of records each operator treats as duplicates, for records with an id and a timestamp:

Records dropDuplicates(["id", "timestamp"]) dropDuplicatesWithinWatermark(["id"])
(foo, 10) and (foo, 10) Duplicates. The id and timestamp are the same. Duplicates. The id is the same.
(foo, 10) and (bar, 10) Different. The id values differ. Different. The id values differ.
(foo, 9) and (foo, 10) Different. The timestamps differ. Duplicates. The id is the same.

How state is evicted

Each key in state has an eviction time. dropDuplicates uses the event time stored in the key itself, and dropDuplicatesWithinWatermark stores an expiration time with the key. Suppose a record has an event time of 10 and the stream has a watermark delay of 15:

  • dropDuplicates evicts the record when the watermark reaches 10, the record's event time.
  • dropDuplicatesWithinWatermark evicts the record when the watermark reaches 25, the record's event time plus the watermark delay. A later duplicate doesn't change the eviction time.

Eviction runs at the end of each micro-batch, after the operator processes the micro-batch's input records. A key that expires in a micro-batch still drops duplicates in that micro-batch. When the watermark advances and no new data arrives, Structured Streaming runs a no-data micro-batch to evict expired state. The stateOperators.numRowsRemoved metric counts evicted keys, and stateOperators.customMetrics.numDroppedDuplicateRows counts dropped duplicates. See Monitoring Structured Streaming queries on Azure Databricks.

Example: Evict state with dropDuplicates

This example uses a 10-second watermark delay and deduplicates on the id and timestamp columns:

(spark.readStream
  # ...
  .withWatermark("timestamp", "10 seconds")
  .dropDuplicates(["id", "timestamp"])
)

The following table shows how the query processes four micro-batches. Each state entry shows the key and its eviction time. The eviction watermark is the watermark that the micro-batch uses to evict state, computed at the end of the previous micro-batch. The late-record watermark is the watermark that the previous micro-batch used to evict state. The table assumes that new data is available when micro-batch 0 ends, so micro-batch 1 runs before any no-data micro-batch.

Micro-batch Eviction watermark Late-record watermark Input records Result State at end of micro-batch
0 0 0 (a, 12), (a, 15), (b, 13) All three records are new and are added to state. No keys are evicted. The watermark advances to 15 minus 10, which is 5. (a, 12) evicts at 12, (a, 15) at 15, (b, 13) at 13
1 5 0 (a, 3), (c, 26), (a, 12) (a, 3) isn't late, because 3 is after the late-record watermark of 0. It's a new key, so the query emits it and adds it to state. (c, 26) is new and added to state. (a, 12) is a duplicate and dropped. At the end of the micro-batch, (a, 3) is evicted because 3 is at or before the watermark of 5. The watermark advances to 26 minus 10, which is 16. (a, 12) evicts at 12, (a, 15) at 15, (b, 13) at 13, (c, 26) at 26
2 (no-data micro-batch) 16 5 None (a, 12), (a, 15), and (b, 13) are evicted because their eviction times are at or before 16. (c, 26) evicts at 26
3 16 16 (b, 13) (b, 13) is late, because 13 is at or before the late-record watermark of 16, and is dropped. The key (b, 13) was evicted in micro-batch 2, so without the late-record filter the query would emit it again. The watermark stays at 16. (c, 26) evicts at 26

Example: Evict state with dropDuplicatesWithinWatermark

This example uses the same input and watermark delay. It deduplicates on id only:

(spark.readStream
  # ...
  .withWatermark("timestamp", "10 seconds")
  .dropDuplicatesWithinWatermark(["id"])
)

Each key's eviction time is the event time of its first record plus the 10-second delay. The table uses the same columns and assumptions as the previous example, and it assumes the query processes records in the order listed. Structured Streaming doesn't guarantee processing order within a micro-batch, so the first record for a key, and the key's eviction time, can differ.

Micro-batch Eviction watermark Late-record watermark Input records Result State at end of micro-batch
0 0 0 (a, 12), (a, 15), (b, 13) (a, 12) adds a to state with eviction time 12 + 10 = 22. (a, 15) is a duplicate and dropped, and the eviction time of a doesn't change. (b, 13) adds b with eviction time 23. The watermark advances to 15 minus 10, which is 5. The largest event time includes records dropped as duplicates. a evicts at 22, b at 23
1 5 0 (a, 3), (c, 26), (a, 12) (a, 3) isn't late, because 3 is after the late-record watermark of 0. It's a duplicate of a and dropped. (c, 26) adds c with eviction time 26 + 10 = 36. (a, 12) is a duplicate and dropped. No keys are evicted because every eviction time is after 5. The watermark advances to 16. a evicts at 22, b at 23, c at 36
2 (no-data micro-batch) 16 5 None No keys are evicted because every eviction time is after 16. a evicts at 22, b at 23, c at 36
3 16 16 (b, 13) (b, 13) is late, because 13 is at or before the late-record watermark of 16. The late-record filter drops it before the duplicate check, so it counts in stateOperators.numRowsDroppedByWatermark, not in customMetrics.numDroppedDuplicateRows. The watermark stays at 16. a evicts at 22, b at 23, c at 36

Why the guarantee applies in one direction

dropDuplicatesWithinWatermark drops every duplicate whose event time is within the watermark delay of the first record's event time, either as a duplicate or as late data. It might also drop duplicates with later event times.

For example, with a watermark delay of 100 seconds, a record at event time 250 stays in state until the watermark reaches 350. The watermark reaches 350 only after a micro-batch whose largest event time is 450 or more. If that micro-batch contains records at 450 and 500 with the same key, the operator drops both, because the watermark advances only after the micro-batch completes. Both records are more than 100 seconds after the first record, and the operator still drops them as duplicates.

Because of this behavior, don't use dropDuplicatesWithinWatermark to emit at most one record for each key in a fixed time interval. For example, if your query must keep both (foo, 250) and (foo, 450), implement the interval logic with transformWithState. See Build a custom stateful application with transformWithState.