CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 1 · Lesson 12/45

    Structured Streaming state: watermarks, output modes, foreachBatch and checkpoints

    Apply Structured Streaming stateful-processing semantics, including watermarks, output modes, foreachBatch, and checkpoints for fault-tolerant exactly-once state recovery.

    18 min read
    1.92% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    A 10-minute watermark on a count per id over 5-minute tumbling windowspython
    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()
    )

    Sources12

    2.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.

    Each input stream gets its own lateness thresholdpython
    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?

    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?

    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.

    How each output mode behaves for an aggregation with a watermark
    Output modeWhat is emitted per triggerWhat happens to old state
    Append (default)Only rows that will not change again, written after the watermark passes the windowDropped after the threshold passes
    UpdateEvery row that changed during the trigger, even if it may change againDropped after the threshold passes
    CompleteEvery row the operator has ever produced; the target table is rewritten each triggerNever 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.

    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?

    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?

    Sources132

    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.

    Guard against empty micro-batches before running business logicpython
    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 OPTIMIZE on 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 calls show(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.
    • foreachBatch needs micro-batch execution and does not work in continuous processing mode, where you use foreach() 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()

    Sources4

    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.

    Always set an explicit checkpoint location, one per querypython
    (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.

    Restarting from an existing checkpoint after a code change
    ChangeSame checkpoint?
    Add or remove a filterGenerally safe
    Change the trigger intervalGenerally safe
    Add, change or remove a rate limit such as maxOffsetsPerTriggerGenerally safe
    Projection change with the same output schemaAllowed
    Add or remove a grouping key or aggregate in a streaming aggregationNot allowed: new checkpoint
    Change the stream-stream join type (inner vs outer) or equi-join columnsNot allowed: new checkpoint
    Change the number or type of input sources, or the subscribed Kafka topicNew checkpoint required
    Change the output sink typeGenerally requires a new checkpoint
    Change spark.sql.shuffle.partitions on a stateful queryNo 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.

    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)

    0 of 2 selected

    Sources52

    Sources

    (5)

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

    1. 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. 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. 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. 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. 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

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