What you will be able to do
- Explain how a watermark bounds state for windowed aggregations, stream-stream joins and deduplication, and what happens to late records
- Choose append, update or complete output mode for a given query shape and sink, and predict what each emits per trigger
- Write a foreachBatch function that handles empty batches, consumes the whole batch and uses batchId for idempotent, exactly-once writes
- Describe what a checkpoint stores and decide which query changes can restart from an existing checkpoint
Key concept
Watermark — A lateness threshold declared on an event-time column. The engine tracks the latest event time it has seen, and once a window, join key or dedup entry falls further behind than the threshold, that state is finalized and can be dropped.
1.Why stateful queries need a watermark
A stateless streaming query only has to remember which source rows it has already processed. A stateful query also carries intermediate results from one micro-batch to the next, so it can update its answer incrementally instead of recomputing everything. Streaming aggregation, distinct, dropDuplicates, stream-stream joins and custom stateful applications all work this way. The cost is that state keeps growing: every new window, join key or distinct record adds an entry, and if nothing removes old entries the query ends up with memory errors and rising latency.
A watermark is what removes those old entries. You declare it with withWatermark, passing a timestamp column and a lateness threshold. The state manager tracks the most recent timestamp it has seen in that column. Once a state entity, such as a window, falls further behind that timestamp than the threshold allows, the query stops processing it and drops it. Records that arrive within the threshold are always processed. Records that arrive later might still be processed, but nothing guarantees it, so treat the threshold as the point where late data can be lost.
from pyspark.sql.functions import window
(df
.withWatermark("event_time", "10 minutes")
.groupBy(
window("event_time", "5 minutes"),
"id")
.count()
)With only a duration, window("event_time", "5 minutes") creates non-overlapping 5-minute tumbling windows, not sliding ones. The engine keeps each count in state until the end of its window is 10 minutes older than the latest event_time it has seen. Refer to columns by name ("event_time" or col("event_time")) in groupBy() and window() so the event-time marker carries through.
Choosing the threshold means trading latency against tolerance for late data. A short watermark keeps less state and lets results out sooner, but it drops more late records. A long watermark accepts records that arrive much later, at the price of more state in memory and a longer wait before results are written.
Checkpoint 1 of 9· Fill the gap
This streaming query counts events per id in 5-minute windows. Without the missing call, a new state entry is added for every window and old ones are never removed. Which call bounds the state so that old windows can be finalized and dropped?
from pyspark.sql.functions import window
(df
. ? ("event_time", "10 minutes")
.groupBy(
window("event_time", "5 minutes"),
"id")
.count()
)withWatermark takes an event-time column and a lateness threshold. The state manager tracks the latest event_time it has seen and drops a window once the window's end is more than 10 minutes older than that time. Without it, the aggregation state keeps growing.
Source: docs.databricks.com2.Watermarks on stream-stream joins and deduplication
In a join between two streams, the state is the set of unmatched keys on each side. For an inner join, a watermark on each input is recommended but not required. Without one, the query tries to join every key from both sides on every trigger, and performance degrades as state grows. For an outer join, a watermark is mandatory. An unmatched row is written with nulls for the missing side, and because stream-stream joins only support append mode, that row is not written until the lateness threshold has passed.
input_stream1 = ... # delays up to 1 hour
input_stream2 = ... # delays up to 2 hours
(input_stream1.withWatermark("eventTime1", "1 hour")
.join(
input_stream2.withWatermark("eventTime2", "2 hours"),
joinCondition)
)When several inputs each have a watermark, the engine tracks each one separately and then picks a single global watermark. By default it uses the minimum, so the global watermark advances only as fast as the slowest stream. If one upstream source stalls, output is delayed but no data is wrongly marked late. Setting spark.sql.streaming.multipleWatermarkPolicy to max uses the fastest stream's watermark instead. Latency drops, but data from the slower streams gets dropped, so use it with care.
Deduplication is stateful too. distinct keeps every unique record in state, so without a watermark its state grows without limit. dropDuplicatesWithinWatermark deduplicates on chosen columns, such as a guid, even when other fields like arrival time differ between the copies. It cannot run without a watermark. To make sure every duplicate is caught, set the threshold larger than the biggest time gap you expect between two copies of the same event. This matters because the engine's exactly-once guarantee covers its own processing only and does not remove duplicates that already exist in the source.
Checkpoint 2 of 9· Check yourself
A data engineer writes a left outer join between two streaming DataFrames and declares no watermark on either input. What happens?
For outer joins a watermark is mandatory. Stream-stream joins support only append mode, so the engine can write a null-padded row only once the lateness threshold shows that no match can still arrive. The 'recommended but not required' rule applies to inner joins.
“For outer joins, watermarking is mandatory. When a record is unmatched, the query writes a null value for that key.”Source: docs.databricks.com
Checkpoint 3 of 9· Check yourself
Two streams, each with its own withWatermark, are joined using default settings. One stream's upstream source stops sending data for an hour. How does the query behave?
By default the engine uses the minimum of the input watermarks as the single global watermark, so it advances only as fast as the slowest stream. Following the fastest stream happens only if spark.sql.streaming.multipleWatermarkPolicy is set to max, which can drop data from slower streams.
“The global watermark safely moves at the pace of the slowest stream and delays the query output when necessary.”Source: docs.databricks.com
Sources1
3.Output modes: append, update and complete
The output mode decides which rows a stateful operator emits on each trigger. A row from an aggregation can change from one trigger to the next as more data arrives for its window. The three modes differ in whether they wait for a row to be final, emit every change, or emit everything. For stateless queries all three behave the same, and only queries with aggregations need an output mode set at all.
| Output mode | What is emitted per trigger | What happens to old state |
|---|---|---|
| Append (default) | Only rows that will not change again, written after the watermark passes the window | Dropped after the threshold passes |
| Update | Every row that changed during the trigger, even if it may change again | Dropped after the threshold passes |
| Complete | Every row the operator has ever produced; the target table is rewritten each trigger | Never dropped |
After that first batch, state holds [2pm, 3pm] at $25 and [3pm, 4pm] at $30. Update mode emits both rows, because both changed, and complete mode emits every row. Then a $20 record at 3:20pm arrives. The watermark moves to 3:05pm, which is past the end of the [2pm, 3pm] window, so append mode finally emits that window at $25. Update mode emits only [3pm, 4pm], which changed from $30 to $50. Complete mode again emits everything. In general, append mode holds every result back by at least the watermark delay, and update mode writes a row each time its value changes, which can be expensive if the sink charges per write.
Complete mode ignores the watermark. Since it has to re-emit every row the operator has ever produced, it can never evict aggregation state. A long-running windowed aggregation in complete mode therefore grows its state store, and the checkpointed copy of it, indefinitely, even with withWatermark in the plan. Complete mode works only with streaming aggregations and performs poorly as data grows. For complete-mode results with incremental processing, Databricks recommends materialized views. There are exactly three output modes. Continuous is a processing mode, not an output mode.
Query shape and sink limit which modes you can use. Stream-stream joins support only append, and output mode has no effect on deduplication. When several stateful operators are chained, for example a windowed aggregation feeding a join, only append mode is supported. Sinks matter as well. Kafka accepts all three modes. Delta Lake, which backs every Unity Catalog managed table, accepts append and complete but not update, so .outputMode("update").toTable(...) against a managed table fails. As a rule of thumb, use append when each downstream write triggers a single action, such as a notification, and update when consumers need the freshest value, such as a live dashboard.
Checkpoint 4 of 9· Match them up
A windowed aggregation has withWatermark set. Match each output mode to what it emits on each trigger and what happens to old aggregation state.
Tap a term, then the definition that fits it.
Append and update both evict old state once the watermark threshold passes. They differ in when rows are emitted: append waits until a row is final, and update emits each change. Complete mode has to re-emit everything, so it never evicts state and ignores the watermark.
“Complete | Aggregation state isn't dropped. The query rewrites the target table for each trigger.”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A team runs the following Structured Streaming query:
agg = (df.withWatermark("event_time", "15 minutes")
.groupBy(window("event_time", "5 minutes"))
.count())
agg.writeStream \
.outputMode("complete") \
.format("delta") \
.option("checkpointLocation", chk_path) \
.toTable("orders.window_counts")
After running for several weeks, the checkpoint's state store directory keeps growing and the cluster shows increasing memory pressure. What is the most likely cause?
Correct answer: A — Complete output mode rewrites the entire result table on every trigger and keeps all aggregation state indefinitely, so the 15-minute watermark never triggers state eviction under this output mode.
- A. In complete output mode Structured Streaming re-emits the full result table on every trigger, so the engine must retain every aggregation group it has ever produced rather than dropping groups once they fall behind the watermark. Watermarks only enable state eviction in append and update mode, which explains the unbounded growth here.
- B. A shorter watermark relative to the window size makes Spark discard late data sooner, not reopen closed windows; Structured Streaming never re-creates a window once its close time has passed the watermark. This describes a data-correctness risk (dropped late events), not the memory-growth symptom in the scenario.
- C. Delta table sinks do not disable state store compaction, and Structured Streaming manages state store file compaction and cleanup automatically inside the checkpoint location without requiring a manual
VACUUMon that path. This option describes a mechanism that does not exist in the streaming state store lifecycle. - D. Calling
window()with a single duration argument creates a tumbling window equal to that duration with no separate slide interval, so it does not default to a 1-minute sliding window. This mischaracterizes the API's default behavior and is not the source of the growth described.
Checkpoint 6 of 9· Exam question
Which Structured Streaming output mode rewrites the entire result table to the sink on every trigger, making it unsuitable for a large, unbounded aggregation whose full state must be retained indefinitely?
Correct answer: C — Complete
- A. Append mode only writes new rows that will never change again, such as finalized windows once the watermark has passed, and it does not rewrite the full result table on each trigger.
- B. Update mode writes only the rows whose aggregate value changed since the last trigger, which is more efficient than a full rewrite but is not what this description asks for.
- C. Complete mode rewrites the entire result table to the sink after every trigger, which requires retaining full aggregation state indefinitely and matches the behavior described.
- D. Continuous is a low-latency processing mode, not an output mode, so it does not fit alongside append, update, and complete as an answer to this question.
4.foreachBatch for MERGE, multiple sinks and idempotent writes
foreachBatch gives you update-like behavior on a Delta sink. streamingDF.writeStream.foreachBatch(fn) calls fn once per micro-batch with two arguments: a regular DataFrame holding that batch's output, and the batch's unique ID. Inside the function you can run batch-only operations, most importantly MERGE INTO. This is how a streaming aggregation gets upserted into a Delta table, and it is the required route for any Delta merge from a stream. The same pattern lets you write to stores that have no streaming sink, using their batch writers.
A plain foreachBatch is at-least-once. If a batch fails partway and is retried, the function runs again with the same batchId, and an append would then write duplicates. Use that ID to make writes idempotent. For Delta tables, set the txnAppId and txnVersion write options with txnVersion bound to batchId, and Delta will skip a version it has already committed. For OLTP databases, APIs or queues, you have to build the idempotency yourself: running the same batchId again must produce the same result.
def process_batch(output_df, batch_id):
# Process valid DataFrames only
if not output_df.isEmpty():
# business logic
pass
streamingDF.writeStream.foreachBatch(process_batch).start()Several operational rules follow from how the function is called:
- Empty batches do happen. For example, an
OPTIMIZEon a Delta source with no files to process still advances the offset log, and code that assumes rows can make the query fail. - When the stream has a stateful operator such as
dropDuplicatesWithinWatermark, the function must consume the whole DataFrame. A function that only callsshow(2)makes the query fail on the next batch. - Writing to several sinks inside one function runs those writes one after another, which adds latency to every batch. Separate streaming writers parallelize better.
foreachBatchneeds micro-batch execution and does not work in continuous processing mode, where you useforeach()instead.
Handle errors by failing fast. Let logic, schema and non-retryable errors propagate so the query fails, and let the orchestrator, such as Lakeflow Jobs, retry the whole batch. A homemade retry loop inside the function can leave half-written output. A try/except that only prints the error is worse: it hides the failure and may leave the batch partly consumed. Catch only transient sink errors, such as timeouts or HTTP 429.
Checkpoint 7 of 9· Fill the gap
A stream reads from a Delta table, and its foreachBatch function crashes right after an OPTIMIZE runs on the source with no files to process. The micro-batch it received had no rows. Which DataFrame method completes this guard so the business logic runs only when the micro-batch has rows?
def process_batch(output_df, batch_id):
# Process valid DataFrames only
if not output_df. ? ():
# business logic
pass
streamingDF.writeStream.foreachBatch(process_batch).start()foreachBatch can be called with an empty DataFrame. For example, an OPTIMIZE with no files to process still advances the offset log. Checking isEmpty() skips the business logic for those batches, so code that expects rows does not make the query fail. The batch passed to the function is a regular DataFrame, so isStreaming does not tell you whether it has rows.
Source: docs.databricks.comSources4
5.Checkpoints and exactly-once recovery
After a restart, a query resumes from the checkpoint. That directory, set with the checkpointLocation option before the query starts, holds four things:
- Offsets: which source offsets each micro-batch processed, so the query picks up exactly where it stopped.
- Commits: which micro-batches the sink has committed, the basis of exactly-once output.
- State: for aggregations, joins, deduplication and custom operators, the state store contents and the state schema.
- Metadata: the unique query ID. Configuration is stored in the offset log.
On restart, the engine finds the last committed batch, reloads state, and replays from the recorded offsets.
(df.writeStream
.option("checkpointLocation", "/Volumes/catalog/schema/volume/path")
.toTable("catalog.schema.table")
)The checkpoint defines the query's identity. Two queries must never share a location. If you delete the directory or point the query at a new one, it starts fresh: no offsets, no state. If you leave out the option on the display() or memory sink, a temporary checkpoint is created automatically, and it provides no fault tolerance.
Restored state assumes the query has the same shape as before. Changes that leave the stateful plan alone are generally safe. Changes to sources, stateful operators or the sink generally need a new checkpoint. Some sink switches are allowed case by case, but treat a change of sink type as needing a fresh checkpoint.
| Change | Same checkpoint? |
|---|---|
| Add or remove a filter | Generally safe |
| Change the trigger interval | Generally safe |
| Add, change or remove a rate limit such as maxOffsetsPerTrigger | Generally safe |
| Projection change with the same output schema | Allowed |
| Add or remove a grouping key or aggregate in a streaming aggregation | Not allowed: new checkpoint |
| Change the stream-stream join type (inner vs outer) or equi-join columns | Not allowed: new checkpoint |
| Change the number or type of input sources, or the subscribed Kafka topic | New checkpoint required |
| Change the output sink type | Generally requires a new checkpoint |
| Change spark.sql.shuffle.partitions on a stateful query | No effect: the count is fixed when the checkpoint is created |
The partition rule catches people out. A stateful query keeps the shuffle partition count it had when its checkpoint was created, so raising spark.sql.shuffle.partitions later does nothing until you start with a new checkpoint location. On Databricks Runtime 18 LTS and above, on-demand state repartitioning removes this limit. The state store scheme also cannot change between restarts, and queries using dropDuplicates() or dropDuplicatesWithinWatermark() can fail to restart if you move them between incompatible compute access modes.
Checkpoint 8 of 9· Match them up
An engineer changes a running stateful streaming aggregation and then restarts it. Match each change to what happens on restart.
Tap a term, then the definition that fits it.
The checkpoint holds the query's offsets, commits and state, so changes that leave the stateful plan alone, such as the trigger interval, are safe. Changing grouping keys breaks the restored state schema. The shuffle partition count is fixed when the checkpoint is created, so raising it has no effect until the query starts from a new location, and a new location means no offsets and no state.
“Changing spark.sql.shuffle.partitions has no effect on a streaming query that already has a checkpoint”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A Structured Streaming job has been running for weeks against the checkpoint location s3://data/chk/orders-agg. It reads from a Delta table with readStream, computes a windowed aggregation grouped by a fixed set of grouping columns, and writes the results to a Kafka topic. The team wants to ship a code update without deleting or resetting that checkpoint. Which two of the following changes can be deployed safely against the existing checkpoint, without breaking state recovery on restart? (Select 2)(Select 2)
Correct answers: A, B — Adding a .filter() call before the aggregation to drop rows where amount is null, leaving the grouping columns and aggregation function unchanged.; Changing the trigger from Trigger.ProcessingTime("1 minute") to Trigger.ProcessingTime("30 seconds"), keeping the aggregation logic unchanged.
- A. Adding a stateless row filter upstream of the aggregation does not change the grouping keys or aggregates of the stateful operator, so the existing checkpoint's state store schema still matches. Databricks documents that "Addition / deletion of filters is allowed."
- B. Adjusting the processing-time trigger interval only changes how often micro-batches fire; it does not alter the stateful operator's schema or the input source, so it is safe to change without resetting the checkpoint. Databricks lists changes in the trigger interval as permitted between restarts from the same checkpoint.
- C. Adding a grouping column changes the schema of the stateful aggregation operator, so the state stored in the checkpoint no longer matches the new query plan and the query cannot resume from it. Databricks documents that "Any change in number or type of grouping keys or aggregates is not allowed."
- D. Moving from a Kafka sink to a file sink is one of the sink changes the checkpoint cannot recover into. Databricks documents that "Kafka sink to file sink is not allowed" against an existing checkpoint, so this deployment would fail or corrupt the exactly-once bookkeeping and needs a new checkpoint location.
- E. Swapping in a different upstream table with an unrelated schema changes the input side of the query that the checkpoint's offset log was tracking, which breaks the correspondence needed to resume processing correctly. Databricks documents that changes to the subscribed content of a source are generally not allowed because the results are unpredictable.
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Streaming queries accumulate state data over time. Watermarks automatically remove old state data to prevent memory errors and increased processing latency.”
↩︎ Why stateful queries need a watermark“Queries might still process records that arrive outside the threshold, but this isn't guaranteed.”
↩︎ Why stateful queries need a watermark“The event_time column is used to define a 10 minute watermark and a 5 minute tumbling window.”
↩︎ Why stateful queries need a watermark“For outer joins, watermarking is mandatory.”
↩︎ Watermarks on stream-stream joins and deduplication“By default, Structured Streaming uses the minimum as the global watermark.”
↩︎ Watermarks on stream-stream joins and deduplication“this configuration drops data from the slowest streams”
↩︎ Watermarks on stream-stream joins and deduplication“You must specify a watermark to use the dropDuplicatesWithinWatermark method”
↩︎ Watermarks on stream-stream joins and deduplication“Structured Streaming guarantees exactly-once processing but doesn't deduplicate records from data sources.”
↩︎ Watermarks on stream-stream joins and deduplication“Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
↩︎ Output modes: append, update and complete“Joins between multiple streams only support append mode.”
↩︎ Output modes: append, update and complete“Watermarks control the threshold for when a query stops processing a state entity.”
↩︎ Key concept“Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
↩︎ Exam trap 1“For outer joins, watermarking is mandatory. When a record is unmatched, the query writes a null value for that key.”
↩︎ Checkpoint“The global watermark safely moves at the pace of the slowest stream and delays the query output when necessary.”
↩︎ Checkpoint“Complete | Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
↩︎ Checkpoint - 2.
“Stateful operations include streaming aggregation, distinct, dropDuplicates, stream-stream joins, and custom stateful applications.”
↩︎ Why stateful queries need a watermark“Only the append output mode is supported.”
↩︎ Output modes: append, update and complete“The number of shuffle partitions is fixed at the time the checkpoint is created.”
↩︎ Checkpoints and exactly-once recovery“The number of shuffle partitions is fixed at the time the checkpoint is created.”
↩︎ Exam trap 4“Changing spark.sql.shuffle.partitions has no effect on a streaming query that already has a checkpoint”
↩︎ Checkpoint - 3.
“Delta Lake, which backs all Unity Catalog managed tables, supports append and complete modes but not update mode.”
↩︎ Output modes: append, update and complete“Complete mode only works with streaming aggregations.”
↩︎ Output modes: append, update and complete“your records have at least a 1-hour delay before being emitted downstream”
↩︎ Output modes: append, update and complete“Delta Lake, which backs all Unity Catalog managed tables, supports append and complete modes but not update mode.”
↩︎ Exam trap 2“The streaming aggregation operator does not emit anything downstream.”
↩︎ Prediction - 4.
“You must use foreachBatch for Delta Lake merge operations in Structured Streaming.”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“you can use the batchId provided to the function as way to deduplicate the output and get an exactly-once guarantee”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“binding txnVersion to batchId, to guarantee idempotency and protect data correctness on retries”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“foreachBatch() might receive an empty DataFrame, and your code must handle this scenario.”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“If you do not consume the entire DataFrame, the streaming query will fail with the next batch.”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“Using foreachBatch to write to multiple sinks serializes the execution of streaming writes, which can increase latency for each micro-batch.”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“foreachBatch() does not work with the continuous processing mode”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“Databricks recommends that you allow the streaming query to fail fast and instead rely on the orchestration layer”
↩︎ foreachBatch for MERGE, multiple sinks and idempotent writes“foreachBatch() provides only at-least-once write guarantees.”
↩︎ Exam trap 3 - 5.
“Commits: A record of which micro-batches have been committed to the sink, enabling exactly-once semantics.”
↩︎ Checkpoints and exactly-once recovery“Each query must have a different checkpoint location.”
↩︎ Checkpoints and exactly-once recovery“When you delete the files in a checkpoint directory or change to a new checkpoint location, the next run of the query begins fresh.”
↩︎ Checkpoints and exactly-once recovery“Changes that are generally safe include adding or removing filters, changing rate limits, trigger intervals”
↩︎ Checkpoints and exactly-once recovery“Changes that generally require a new checkpoint include the number or type of input sources”
↩︎ Checkpoints and exactly-once recovery“Any change in number or type of grouping keys or aggregates is not allowed.”
↩︎ Checkpoints and exactly-once recovery