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?
Exactly-once stops Spark from processing a record twice during its own replays. A record the source sent twice is still two separate records, so they stay in the stream until you remove them with dropDuplicates or dropDuplicatesWithinWatermark.
“Structured Streaming guarantees exactly-once processing but doesn't deduplicate records from data sources.”Source: docs.databricks.com
2.dropDuplicates without a watermark: exact, but state never shrinks
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?
Without a watermark nothing tells streaming dropDuplicates when it can forget a key. It keeps every key it has seen, so deduplication stays exact for the life of the query, while the state grows with the number of distinct keys. An open-ended ID space like payment IDs makes that growth unbounded.
“For a streaming DataFrame, it will keep all data across triggers as intermediate state to drop duplicates rows.”Source: docs.databricks.com
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.
| Parameter | Type | Meaning |
|---|---|---|
| eventTime | str | Name of the column that contains the event time of the row |
| delayThreshold | str | Minimum 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?
The watermark is the maximum event time seen across all partitions minus the delay threshold. Spark only guarantees it is at least that far behind. It moves when newer event times arrive, not when the wall clock moves, so it stays at or before 09:35 while no data comes in.
“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”Source: docs.databricks.com
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.
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()
)A watermark has to be declared on a timestamp column that holds each row's event time. It is placed before distinct(), so the dedup operator can drop a key's state once the watermark has moved past that key's event time. An ID or value column cannot carry a watermark.
Source: docs.databricks.comCheckpoint 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?
Correct answer: A — clicks_df \
.withWatermark("event_time", "20 minutes") \
.dropDuplicates(["click_id", "event_time"])
- A. This is correct: calling
withWatermarkon the event-time column beforedropDuplicates, and including that same event-time column in the dedup key list, lets the engine bound state using the watermark and expire keys once the watermark passes their event time by more than the declared delay. - B. Calling
withWatermarkafterdropDuplicatesdoes not bound the dedup state, because the watermark must be established before the stateful operation so the engine can use it to decide when state is safe to evict. The state store still grows without bound here. - C. The watermark must be defined on an event-time column, not on the
click_ididentifier column, andclick_idneeds to appear in the dedup key list for identifier-based deduplication to work as intended. This swaps the two columns' roles incorrectly. - D. Filtering on
current_timestamp()compares against processing time, not the watermark mechanism, and does not tell the stateful dedup operator when it is safe to drop old keys, so the state store still keeps everyclick_idindefinitely. - E. Filtering after
dropDuplicatesnarrows the output rows but does not give the deduplication operator any watermark information, so the underlying dedup state continues to grow without a bound regardless of the later filter.
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)
Correct answers: A, B — Once the watermark advances past a record's event time by more than the declared delay, the state kept for that record becomes eligible for removal from the state store.; The watermark delay should be chosen based on how late duplicate events are expected to arrive relative to the original event, since a shorter delay risks missing valid duplicates.
- A. This is correct: the engine uses watermark progress to identify state that is no longer expected to see new duplicates and removes it, which is exactly how watermark-based dedup bounds the state store size over time.
- B. This is correct: the watermark delay directly controls the tradeoff between state size and correctness, so it should be set long enough to cover realistic duplicate arrival lateness or genuine duplicates arriving after the watermark passes will be treated as new records.
- C. The watermark column must be an event-time column of a timestamp type, not an arbitrary string, and Spark tracks lateness using actual timestamp values rather than string or ingestion-order comparisons.
- D. Attaching a watermark does not force downstream aggregations into complete mode; output mode is chosen independently by the query, and watermarks are commonly paired with append or update mode instead.
- E. The dedup operator relies on the declared watermark based on event time in the data, not on wall-clock processing time, which is precisely what allows it to correctly handle data that arrives out of order or with processing delays.
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.
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.
| Operator | What counts as a duplicate | Watermark | State over time |
|---|---|---|---|
| distinct() | Rows equal on all columns | Optional | Grows indefinitely without one; dropped after the threshold with one |
| dropDuplicates(subset) | Rows equal on the chosen columns | Optional | Grows 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 differs | Required via withWatermark | Bounded 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.
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", " ? "])
)The source's uniqueness contract makes session_id plus click_seq_num the event identity, so that pair goes in the key. Using ad_id would drop a real second click on the same ad. Using click_ts would let retries with a shifted timestamp through, and the watermark on click_ts already bounds the state.
Source: docs.databricks.comCheckpoint 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?
Correct answer: A — payments_df \
.withWatermark("submitted_at", "10 hours") \
.dropDuplicatesWithinWatermark(["payment_id"])
- A. This is correct:
dropDuplicatesWithinWatermarkis designed exactly for this case, where the event-time column cannot be part of the identifier because retries change it. It deduplicates purely onpayment_idwhile still using the watermark onsubmitted_atto bound and clean up state. - B. Including
submitted_atin the key list fordropDuplicatesmeans two retries of the same payment with different timestamps are treated as distinct records and both pass through, which defeats the stated goal sincesubmitted_atcannot reliably identify duplicates here. - C. Establishing the watermark after
dropDuplicatesdoes not give the dedup operator any lateness information to use for state cleanup, so this does not bound state regardless of which columns are chosen as the key. - D. Grouping and aggregating by
payment_idcomputes an aggregate value rather than filtering out duplicate rows, and it also places the watermark call after a stateful operation, so it does not perform row-level deduplication as required. - E. Keying
dropDuplicatesonsubmitted_atalone deduplicates by timestamp rather than by payment identity, so two different payments that happen to share a timestamp would be incorrectly collapsed into one record.
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.
“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.
“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.
“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.
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/dropDuplicatesWithinWatermarkOfficial docs
“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.
“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