CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 5 · Lesson 28/32

    Streaming deduplication with dropDuplicates and watermarks

    Perform Streaming Deduplication in Structured Streaming, both with and without watermark usage.

    16 min read
    2.5% of exam
    8 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Explain why dropDuplicates and distinct keep state on a streaming DataFrame, and what happens to that state without a watermark
    • Define an event-time watermark with withWatermark and choose a delay threshold by weighing late-data tolerance against state size
    • Write a watermarked dropDuplicates that puts the event-time column in the key, with the watermark declared before the dedup call
    • Choose dropDuplicatesWithinWatermark when duplicate events carry different timestamps, and pick dedup columns from the source's uniqueness contract

    Key concept

    Event-time watermark — A moving cutoff in event time: the latest event time the query has seen, minus a delay you declare. Data older than the cutoff counts as too late, so a stateful operator such as deduplication can discard state for keys behind it instead of keeping them forever.

    1.Why deduplicating a stream means remembering keys

    Duplicates in a stream usually come from the source, not from Spark. Many message queues only guarantee at-least-once delivery, so a retry by the producer or a replay by the queue can deliver the same event to your query twice. Exactly-once semantics stop Spark's own replays from processing a record twice, but they do nothing about a record the source sent twice. Structured Streaming processes each record exactly once and does not deduplicate the source data, so removing those duplicates is your job.

    On a static DataFrame, distinct() and dropDuplicates() see the whole dataset and compare its rows in one pass. A stream never gives you the whole dataset. A duplicate of an event processed in the first micro-batch can arrive in the hundredth, so the operator has to remember every key it has already let through, across triggers. That memory is state. On a stream, distinct and dropDuplicates are therefore stateful operators, in the same group as streaming aggregation and stream-stream joins, and the keys they have seen are stored as described in Stateful operators and the StateStore.

    That state is tied to the query's checkpoint. The checkpoint is the only thing that carries deduplication state across a restart (Checkpoints and write-ahead logs). If you restart the query with a new checkpoint location, it starts from scratch with no record of the keys it saw before. Duplicates of events from before the restart then pass straight through.

    Checkpoint 1 of 8· Check yourself

    A streaming query reads from a message queue that guarantees at-least-once delivery. The query has no dedup operator and writes to a sink. A producer retry delivers the same event to the queue twice. What happens?

    Sources123

    2.dropDuplicates without a watermark: exact, but state never shrinks

    The dropDuplicates signature: subset names the columns that define a duplicate, and defaults to all columnspython
    dropDuplicates(subset: Optional[List[str]] = None)

    Without a watermark, dropDuplicates keeps every key forever. On a batch DataFrame it just drops duplicate rows. On a streaming DataFrame it keeps everything it has seen across triggers as intermediate state, and nothing tells it when an old key can be forgotten. The upside is exact deduplication over the whole life of the query: an ID first seen on day one is still rejected on day thirty.

    The cost of that exactness grows every day. The state grows without limit. On a long-running query the end point is an out-of-memory error, and latency rises well before that. distinct() behaves the same way and tracks every unique record, because it compares all columns. In both cases the state holds one entry per key, so its size depends on how many distinct keys the stream can produce. A fixed set of a few thousand device IDs stays small. An open-ended ID space such as click IDs or payment IDs keeps growing.

    Checkpoint 2 of 8· Check yourself

    Your team runs dropDuplicates(["payment_id"]) on a payments stream with no watermark. Payment IDs never repeat across legitimate payments, so new IDs arrive constantly. After a month, what is true of the dedup state and the results?

    Sources415

    3.Watermarks: a moving cutoff in event time

    A watermark lets a stateful query decide when old state can go. You declare it on a streaming DataFrame with withWatermark, passing the column that holds each row's event time and a lateness threshold. Watermarks exist only in Structured Streaming. The event-time column must be a timestamp field, so you cannot watermark an ID column or a string.

    The two arguments of withWatermark(eventTime, delayThreshold)
    ParameterTypeMeaning
    eventTimestrName of the column that contains the event time of the row
    delayThresholdstrMinimum time to wait for late data, relative to the latest record processed, written as an interval such as "1 minute" or "5 hours"

    The current watermark is the maximum event time seen across all partitions, minus the threshold. Suppose the newest event_time seen so far is 12:40 and the delay is 20 minutes. The watermark is then 12:20, and a row stamped 12:10 is behind it. Coordinating this value across partitions is expensive, so Spark only guarantees that the actual watermark is at least the threshold behind the newest event time. The watermark moves when data with newer event times arrives. It does not follow the wall clock. A filter such as event_time > current_timestamp() - interval 20 minutes compares against processing time, which is a different measure. That filter also does not stop a later dropDuplicates from keeping every key.

    Choosing the threshold means trading completeness against state size. A short watermark keeps less state and lowers latency, but it tolerates little late data. A long watermark tolerates a lot of late data, but it holds more state and waits longer. The right value depends on how your data actually arrives, so test and monitor it rather than guessing.

    A watermark does not choose the output mode. The query keeps the output mode it was written with. In Complete mode, aggregation state is never dropped, watermark or not.

    Checkpoint 3 of 8· Check yourself

    Across all partitions, the newest event_time a query has seen is 09:50. It declared withWatermark("event_time", "15 minutes"). The wall clock now reads 10:30, and no new rows arrive for the next 20 minutes. Where is the watermark during that quiet period?

    Sources612

    4.dropDuplicates with a watermark: event time belongs in the key

    Declare the watermark first, then deduplicate. The dedup operator can only use a watermark that is already defined on its input, so withWatermark comes before distinct or dropDuplicates in the chain. A withWatermark placed after the dedup call leaves the dedup step unbounded, just as if no watermark existed.

    A one-hour watermark declared before distinct(): duplicates within the hour are removed, and older dedup state is droppedpython
    streamingDf = spark.readStream. ...  # columns: eventTime, id, value, ...
    
    # Apply watermark before distinct operation
    (streamingDf
      .withWatermark("eventTime", "1 hour")
      .distinct()
    )

    In that example, the query removes duplicates that arrive within an hour of the newest eventTime, and it drops the dedup state once the threshold passes. Here distinct() compares all columns, so eventTime is part of what defines a duplicate. With dropDuplicates, you choose the subset of columns yourself, and the same pattern applies: list the watermarked event-time column in the subset next to the ID. Each stored key then carries an event time, so once the watermark has moved more than the delay past it, that key's state can be removed.

    Take a clickstream with click_id, event_time and page_url, where a duplicate never arrives more than 20 minutes after the original. A re-delivered click carries the same event_time, so the pair still identifies it: clicks_df.withWatermark("event_time", "20 minutes").dropDuplicates(["click_id", "event_time"]). Three tempting alternatives fail. Swapping the two calls leaves the dedup unbounded. Watermarking click_id fails because a watermark needs a timestamp column. Filtering on current_timestamp() uses processing time and leaves state unbounded.

    Size the delay from how late duplicates actually arrive compared with the original event. The watermark also affects what reaches the output: data older than the watermark is dropped, which rules out any chance of a duplicate getting through. If the delay is shorter than the real gap between original and duplicate, the original's key has already been removed when the duplicate arrives, and the duplicate is missed.

    Checkpoint 4 of 8· Fill the gap

    The input has the columns eventTime, id and value. Which column must the watermark use so that distinct() can drop old dedup state?

    streamingDf = spark.readStream. ...  # columns: eventTime, id, value, ...
    
    # Apply watermark before distinct operation
    (streamingDf
      .withWatermark(" ? ", "1 hour")
      .distinct()
    )

    Checkpoint 5 of 8· Exam question

    A clickstream pipeline ingests events with columns click_id, event_time, and page_url. The business guarantees that a duplicate click_id never arrives more than 20 minutes after the original event. An engineer wants to deduplicate on click_id while bounding the size of the dedup state store using this known delay. Which code correctly implements this?

    Checkpoint 6 of 8· Exam question

    Which two statements accurately describe how dropDuplicates behaves when used on a streaming DataFrame with a watermark defined on the event-time column included in the dedup key list? (Choose 2 answers)(Select 2)

    0 of 2 selected

    Sources14

    5.dropDuplicatesWithinWatermark for events with a unique ID

    dropDuplicates treats rows as duplicates only if they match on every column in the subset. That makes the event-time-in-the-key pattern useless when duplicates carry different timestamps. A retry stamped a few seconds later has a different key, so it is kept. Removing the timestamp from the key fixes the match but loses the bounded state. dropDuplicatesWithinWatermark solves this. You deduplicate on the identity columns alone, and the watermark on the time column still controls how long state is kept.

    Deduplicating on a guid while a 10-hour watermark on eventTime bounds the statepython
    streamingDf = spark.readStream. ...
    
    # deduplicate using guid column with watermark based on eventTime column
    (streamingDf
      .withWatermark("eventTime", "10 hours")
      .dropDuplicatesWithinWatermark(["guid"])
    )

    The method has two hard requirements: it works only on a streaming DataFrame, and the input must already have a watermark set with withWatermark. Its guarantee is stated in terms of the watermark: events are deduplicated as long as the earliest and latest copies are closer together in time than the delay threshold. Duplicates further apart than that may still get through. So set the threshold above the largest timestamp difference you expect between duplicates. Data older than the watermark is dropped, as with watermarked dropDuplicates.

    The three streaming dedup operators compared
    OperatorWhat counts as a duplicateWatermarkState over time
    distinct()Rows equal on all columnsOptionalGrows indefinitely without one; dropped after the threshold with one
    dropDuplicates(subset)Rows equal on the chosen columnsOptionalGrows indefinitely without one; bounded when the watermarked event-time column is in the subset
    dropDuplicatesWithinWatermark(subset)Rows equal on the chosen columns, even when event time differsRequired via withWatermarkBounded by the watermark delay threshold

    Which columns to deduplicate on is a separate decision, and getting it wrong silently deletes real data. Use the columns that uniquely identify an event, taken from the source's uniqueness contract rather than from what looks distinct in a sample. Sometimes no single column is unique. A click sequence number may be unique only within its session, so the key is the session ID plus the sequence number. Deduplicating on just the timestamp, or on columns that can legitimately repeat, drops genuine events. A user who clicks the same ad twice produces two real clicks, and deduplicating on user and ad throws the second one away.

    A two-column identity: the click sequence number is unique only within its sessionpython
    spark.readStream.table("clicks_bronze")
            .withWatermark("click_ts", "5 minutes")
            .dropDuplicatesWithinWatermark(["session_id", "click_seq_num"])

    Checkpoint 7 of 8· Fill the gap

    The clicks_bronze producer promises that click_seq_num is unique only within a session. A user can click the same ad (ad_id) more than once in a session, and retried clicks can carry a shifted click_ts. Which column completes the dedup key so that retries are removed and no genuine click is lost?

    from pyspark import pipelines as dp
    
    @dp.table(name="clicks_deduped")
    def clicks_deduped():
        return (
            spark.readStream.table("clicks_bronze")
            .withWatermark("click_ts", "5 minutes")
            .dropDuplicatesWithinWatermark(["session_id", " ? "])
        )

    Checkpoint 8 of 8· Exam question

    A payments pipeline receives events with columns payment_id, submitted_at, and amount. A known issue with an upstream non-idempotent writer means the same logical payment can be re-emitted with a slightly different submitted_at timestamp on retry, so submitted_at cannot safely be part of the dedup key. The team still wants watermark-based state cleanup using submitted_at. Which approach fits this requirement?

    Sources718

    Sources

    (8)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Structured Streaming guarantees exactly-once processing but doesn't deduplicate records from data sources.”
      ↩︎ Why deduplicating a stream means remembering keys
      “The distinct operation tracks every unique record in state. Without a watermark, state grows indefinitely and can cause memory issues.”
      ↩︎ dropDuplicates without a watermark: exact, but state never shrinks
      “Specify a watermark on a timestamp field to bound state and remove old records after the threshold passes.”
      ↩︎ Watermarks: a moving cutoff in event time
      “Longer watermarks have a high tolerance for late data.”
      ↩︎ Watermarks: a moving cutoff in event time
      “Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
      ↩︎ Watermarks: a moving cutoff in event time
      “The query drops state information for deduplication after the threshold passes.”
      ↩︎ dropDuplicates with a watermark: event time belongs in the key
      “To guarantee queries drop all duplicates, set the watermark threshold to be greater than the maximum timestamp difference between duplicate events.”
      ↩︎ dropDuplicatesWithinWatermark for events with a unique ID
      “Structured Streaming guarantees exactly-once processing but doesn't deduplicate records from data sources.”
      ↩︎ Exam trap 1
      “Apply watermark before distinct operation”
      ↩︎ Exam trap 3
      “Use dropDuplicatesWithinWatermark to remove duplicates on any field, even when fields differ across duplicate records, such as event time or arrival time.”
      ↩︎ Exam trap 4
      “Use dropDuplicatesWithinWatermark to remove duplicates on any field, even when fields differ across duplicate records, such as event time or arrival time.”
      ↩︎ Prediction
    2. 2.
      “because many message queues have at-least once guarantees, duplicate records should be expected when reading from one of these message queues.”
      ↩︎ Why deduplicating a stream means remembering keys
      “testing and monitoring your processing is important to determine an optimal threshold.”
      ↩︎ Watermarks: a moving cutoff in event time
    3. 3.
      “Stateful operations include streaming aggregation, distinct, dropDuplicates, stream-stream joins, and custom stateful applications.”
      ↩︎ Why deduplicating a stream means remembering keys
      “you must restart it from scratch with a new checkpoint location to change the state store.”
      ↩︎ Why deduplicating a stream means remembering keys
    4. 4.
      “For a streaming DataFrame, it will keep all data across triggers as intermediate state to drop duplicates rows.”
      ↩︎ dropDuplicates without a watermark: exact, but state never shrinks
      “You can use withWatermark to limit how late the duplicate data can be and the system will accordingly limit the state.”
      ↩︎ dropDuplicates with a watermark: event time belongs in the key
      “In addition, data older than watermark will be dropped to avoid any possibility of duplicates.”
      ↩︎ dropDuplicates with a watermark: event time belongs in the key
    5. 5.
      “Without a watermark, state grows unbounded as the pipeline accumulates data for every possible key, eventually causing out-of-memory errors on long-running pipelines.”
      ↩︎ dropDuplicates without a watermark: exact, but state never shrinks
    6. 6.
      “The current watermark is computed by looking at the MAX(eventTime) seen across all of the partitions in the query minus a user specified delayThreshold.”
      ↩︎ Watermarks: a moving cutoff in event time
      “the actual watermark used is only guaranteed to be at least delayThreshold behind the actual event time.”
      ↩︎ Watermarks: a moving cutoff in event time
      “A watermark tracks a point in time before which we assume no more late data is going to arrive.”
      ↩︎ Key concept
      “The current watermark is computed by looking at the MAX(eventTime) seen across all of the partitions in the query minus a user specified delayThreshold.”
      ↩︎ Exam trap 2
      “The current watermark is computed by looking at the MAX(eventTime) seen across all of the partitions in the query minus a user specified delayThreshold”
      ↩︎ Checkpoint
    7. 7.
      “This only works with streaming DataFrame, and watermark for the input DataFrame must be set via withWatermark.”
      ↩︎ dropDuplicatesWithinWatermark for events with a unique ID
      “Events are deduplicated as long as the time distance of earliest and latest events are smaller than the delay threshold of watermark.”
      ↩︎ dropDuplicatesWithinWatermark for events with a unique ID
    8. 8.
      “Choose those columns from the source's uniqueness contract, not from what looks distinct in sample data.”
      ↩︎ dropDuplicatesWithinWatermark for events with a unique ID
      “The identity can span several columns when no single column is unique on its own.”
      ↩︎ dropDuplicatesWithinWatermark for events with a unique ID
      “A user clicking the same ad twice is a common example: deduplicating on the user and the ad silently drops the second click.”
      ↩︎ Exam trap 5

    Spotted a mistake, or was something unclear? Tell us.