Structured Streaming Basics: Watermarks, Checkpoints and Output Modes
The three concepts that make Spark Structured Streaming behave predictably — explained with the failure modes you hit when you skip them.
TL;DR
- Structured Streaming treats a stream as an unbounded table — the same DataFrame API you already know, re-run incrementally on new data.
- A watermark tells Spark how late an event is allowed to be before it's dropped from stateful aggregations — without one, Spark has to keep state forever.
- A checkpoint is how a stream resumes correctly after a restart — losing it, or moving it between unrelated queries, is one of the most common ways to corrupt stream state.
- Output mode (
append,update,complete) determines what gets written on each micro-batch, and the wrong choice either errors immediately or silently writes the wrong thing. - Most "my streaming job is stuck" problems trace back to one of these three concepts being misconfigured, not to Spark itself being broken.
The problem
NorthBridge Retail Group wanted near-real-time inventory counts on its warehouse scanner feed instead of the existing fifteen-minute batch job. The first attempt took the existing batch PySpark code, swapped spark.read for spark.readStream, and pointed it at the same aggregation logic. It ran. It also never stopped growing state, because nobody told it when an event could be considered "final" — a scanner event from a device with a flaky network connection could arrive minutes late, and without a watermark, Spark kept every open aggregation window in memory indefinitely, waiting for data that might never come.
A week later, the job crashed an executor on an out-of-memory error, and the on-call engineer's first instinct was to make the cluster bigger. That bought a few more days. The actual fix was three lines: a watermark, a restructured checkpoint path, and an output mode that matched what the sink could actually accept. None of this is exotic — it's the baseline vocabulary Structured Streaming expects you to already have before you write your first writeStream.
Key concepts
| Concept | What it means | Why it matters here |
|---|---|---|
| Micro-batch processing | Structured Streaming runs your query repeatedly on small batches of new data, not truly row-at-a-time | Lets you reuse the DataFrame API unchanged — a streaming query and a batch query can share the same transformation code |
| Event time vs. processing time | Event time is when something happened; processing time is when Spark saw it | Late-arriving data (network delays, batched device uploads) means these two clocks disagree, sometimes by minutes |
| Watermark | A threshold saying "don't wait for event times older than max-seen-time minus N" | Bounds how long Spark keeps state for a window open, so memory doesn't grow forever |
| Checkpoint | A directory storing offsets and state so a restarted stream picks up exactly where it left off | Point two different queries at the same checkpoint path and you corrupt both |
| Output mode | append (only new finalized rows), update (changed rows), complete (entire result every batch) |
Some sinks and some aggregations only support specific modes — this is a frequent source of startup errors |
The watermark trails the maximum event time seen so far by a fixed lag — here, 10 minutes.
Step-by-step implementation
Step 1 — Read the stream and define the watermark before any aggregation
# Environment: Databricks Runtime 15.x LTS, PySpark 3.5, Structured Streaming
from pyspark.sql import functions as F
scans_stream = (
spark.readStream
.format("delta")
.option("ignoreChanges", "true")
.load("/mnt/bronze/warehouse_scans")
)
scans_watermarked = scans_stream.withWatermark("scan_event_time", "10 minutes")withWatermark has to come before the windowed aggregation that uses it, and it operates on event time — a column in the data — not on processing time (the clock on the cluster). Ten minutes here means: once Spark has seen an event timestamped at 10:30, it will wait until its internal clock shows events have progressed to 10:40 before finalizing and clearing state for any window that ends at or before 10:30.
Step 2 — Window the aggregation and pick an output mode that matches it
inventory_counts = (
scans_watermarked
.groupBy(
F.window("scan_event_time", "5 minutes"),
"warehouse_id",
"sku",
)
.agg(F.sum("quantity_delta").alias("net_quantity_change"))
)
query = (
inventory_counts.writeStream
.format("delta")
.outputMode("update")
.option("checkpointLocation", "/mnt/checkpoints/warehouse_inventory_counts")
.trigger(processingTime="1 minute")
.start("/mnt/silver/inventory_counts")
)update mode here writes only the windows whose aggregate changed since the last micro-batch, which is what a Delta sink needs for this kind of running count — complete mode would try to rewrite the entire result set every batch, which doesn't scale once there are more than a handful of open windows.
Step 3 — Give every stream its own, dedicated checkpoint path
# Two streams reading the SAME source but doing DIFFERENT aggregations
# must use DIFFERENT checkpoint directories — never share one.
query_by_sku = (
inventory_counts.writeStream
.option("checkpointLocation", "/mnt/checkpoints/inventory_by_sku")
.start("/mnt/silver/inventory_counts")
)
alerts = (
scans_watermarked
.groupBy(F.window("scan_event_time", "1 minute"), "warehouse_id")
.agg(F.count("*").alias("scan_count"))
.writeStream
.option("checkpointLocation", "/mnt/checkpoints/scan_rate_alerts") # distinct path
.outputMode("update")
.start("/mnt/silver/scan_rate_alerts")
)The checkpoint directory is tied to one specific query's logic and offsets — treat it as owned exclusively by that query, the same way you'd treat a database's write-ahead log as belonging to that one database instance.
From production: gotchas and lessons
-
Symptom: Executor memory usage climbed steadily over days until the job was killed. Cause: No watermark on a windowed aggregation, so Spark retained state for every open window indefinitely, waiting for data that would never arrive. Fix: Added
withWatermarkwith a threshold based on the actual observed lateness of the source (checked via the scanner devices' upload logs). -
Symptom: After restarting a stream following a code change, it reprocessed data from scratch instead of resuming. Cause: The checkpoint directory had been deleted as part of a cleanup script that didn't know it was load-bearing. Fix: Moved checkpoint paths under a protected prefix excluded from cleanup jobs, and documented the directory's purpose directly in the pipeline code.
-
Symptom: A
writeStreamcall failed immediately with an unsupported-output-mode error. Cause:appendmode was used with a non-watermarked aggregation —appendcan only emit rows once Spark is sure they're final, which for an aggregation requires a watermark. Fix: Added the watermark, which madeappendmode valid, or switched toupdatemode where finality wasn't actually required downstream. -
Symptom: Two streams reading the same bronze table started producing inconsistent results after a deployment. Cause: Both queries had been pointed at the same checkpoint path by a copy-pasted config, so each was silently interfering with the other's offsets. Fix: Gave each query its own checkpoint directory, named for the query it belonged to.
-
Symptom: A trigger set to run "as fast as possible" (no trigger interval) kept the cluster at high utilization even during low-traffic hours. Cause: Default (unset) trigger behavior processes micro-batches back to back with no gap. Fix: Set an explicit
trigger(processingTime="1 minute")matched to the business latency requirement, which also smoothed out cluster cost.
Performance and cost notes
Watermark duration is a direct trade-off between correctness and state size — a longer watermark tolerates later data but keeps more windows open in memory for longer, which costs both memory and (on autoscaling clusters) compute. Base the watermark on data you've actually measured (how late do events really arrive, at the 99th percentile, not the median) rather than a round number picked for convenience. Trigger interval is a similar trade-off against cost: on Databricks, a continuously running cluster billed by the minute costs the same whether your trigger fires every 10 seconds or every 5 minutes, so match the interval to the business latency requirement, not to "as fast as possible."
When not to use this
If the business requirement is genuinely "refresh every 15 minutes is fine," a scheduled batch job is simpler to operate, debug, and reason about than a streaming job — don't take on streaming's operational complexity (checkpoints, watermarks, long-running clusters) for a latency requirement a batch job already meets. Structured Streaming earns its complexity when the gap between data arriving and data being usable has to be measured in seconds or low minutes, not when "near real time" really means "a bit more often than before."
Checklist
- Watermark duration set from measured, real-world lateness, not a guess
- Output mode matches what the aggregation and the sink both support
- Every distinct streaming query has its own, dedicated checkpoint path
- Trigger interval matched to the actual business latency requirement
- Checkpoint directories excluded from any general-purpose cleanup or retention jobs
Practice
Further reading
Keep going
PySpark Window Functions with Practical Examples
Running totals, rankings, lag/lead comparisons, and moving averages in PySpark — what a window actually is under the hood and where it gets expensive.
Testing PySpark Code with pytest
A test pyramid that actually fits a Spark pipeline — fast unit tests for transform logic, a shared local SparkSession, and a pattern for Delta-backed integration tests.
PySpark UDF vs Pandas UDF vs Built-in Functions: Pick the Right One
A field guide to when built-ins, Pandas UDFs and plain Python UDFs actually make sense, with the serialization cost that explains the gap between them.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)