One API, two execution modes
Structured Streaming treats a stream as an unbounded table and executes it as a sequence of micro-batches: each batch is an ordinary Spark SQL query over the data that arrived since the previous commit. That framing is why your batch transformations transfer unchanged, why the same optimiser and codegen apply, and why reasoning about a streaming job is mostly reasoning about batch jobs with a commit protocol attached.
Checkpointing ties the two halves together. The query records the offset range it processed and the state store contents in a checkpoint directory, and commits the sink atomically. Restart from that directory and the query resumes exactly where it left off; lose it and the query must start over, which is why a checkpoint is a first-class artefact in deployment rather than an implementation detail.
By the end of this lesson you should be able to pick a trigger for a latency budget, explain what a watermark commits you to, and say precisely which failures your sink recovers from and which require human intervention.
Triggers decide your latency, cost, and correctness
The trigger is the schedule on which Spark collects a batch. Default processing mode reads whatever is available immediately, which gives the lowest latency but ties batch frequency to source speed. A fixed interval decouples them: the query waits the full period, coalesces everything that arrived, then runs one query. Available-now triggers micro-batch as fast as the cluster allows, which suits backfills. Continuous mode processes row by row with limited operations and is the exception rather than the default.
| Trigger | Batch cadence | Latency | Fit |
|---|---|---|---|
| Default (as fast as possible) | On availability | Sub-second to seconds | General streaming |
| Fixed interval, 30 seconds | Every 30s | Bounded, predictable | Cost-controlled pipelines |
| Fixed interval, 15 minutes | Every 15m | Minutes | Hourly-style marts |
| Once | Single batch then stop | n/a | Backfills and migrations |
| Available-now with a stop | Repeated until stopped | Seconds | Reprocessing a bounded range |
| Continuous, 1 millisecond | Continuous | Millisecond | Narrow operation set only |
The interval is also a cost dial. Fewer, larger batches mean fewer scheduling overheads and better parquet file sizes, but each batch holds more state and delays feedback. A practical starting point is thirty seconds for operational dashboards and five to fifteen minutes for downstream marts, adjusted once you have measured batch durations rather than guessed at them.
Event time, watermarks, and late data
Processing time is when Spark saw the record; event time is when it happened. Streaming correctness depends on choosing the right one, and almost every real source delivers records out of order. A watermark is the promise you make about how late is acceptable: Spark tracks the maximum event time seen minus a delay threshold, and any record older than that is dropped from aggregation while state older than it is reclaimed.
Output mode determines what the sink receives, and the three modes are not interchangeable. Append mode emits a row only once its window is final, which requires a watermark. Update mode emits each intermediate value as it changes, which suits tables and dashboards. Complete mode rewrites the entire result every batch, which is viable only when the result set is small enough to rewrite.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.streaming import Trigger
spark = (
SparkSession.builder
.appName("clickstream-agg")
.config("spark.sql.shuffle.partitions", "64")
.getOrCreate()
)
clicks = (
spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "broker-1:9092")
.option("subscribe", "click-events")
.option("startingOffsets", "latest")
.option("maxOffsetsPerTrigger", "500000")
.load()
.select(
F.from_json(F.col("value").cast("string"), "user_id STRING, page STRING, ts TIMESTAMP").alias("e"),
F.col("timestamp").alias("ingest_ts"),
)
.select("e.*", F.col("ingest_ts").alias("_ingest"))
)
windowed = (
clicks
.withWatermark("ts", "20 minutes")
.groupBy(F.window("ts", "5 minutes", "1 minute"), "page")
.agg(
F.count("*").alias("hits"),
F.countDistinct("user_id").alias("visitors"),
)
)
query = (
windowed.writeStream
.outputMode("update")
.option("checkpointLocation", "s3://checkpoints/click-agg")
.trigger(Trigger.ProcessingTime("30 seconds"))
.format("parquet")
.option("path", "s3://lake/mart/page_hits/")
.option("checkpointLocation", "s3://checkpoints/click-agg")
.start()
)
query.awaitTermination()
Note the three settings that carry the weight. The twenty-minute watermark means records arriving more than twenty minutes after the maximum event time are discarded rather than silently corrupting a published window. maxOffsetsPerTrigger bounds how much data one batch may consume, which is your protection against a source backlog turning into an out-of-memory batch. And the tumbling window with a one-minute slide costs extra state, because each event now belongs to five windows rather than one.
Recovering exactly-once from a checkpoint
Delivery guarantees come from the combination of offset tracking and an idempotent or transactional sink. Kafka source offsets advance in the checkpoint only when a batch commits, and the batch commits only when the sink confirms. If the driver dies between write and commit, the same offsets are reprocessed â so the sink must tolerate rewrites.
| Source and sink | Failure window | Result after restart |
|---|---|---|
| Kafka to parquet, same checkpoint | Driver crash mid-batch | Same offsets replayed, duplicate files possible |
| Kafka to Kafka with transactional producer | Any point | Offsets and output commit together |
| Kafka to Delta with rename-and-commit | Any point | Batch replay converges to one table state |
| File source with offset log | Crash after read | Ranges re-read, sink must be idempotent |
The table is the honest version of the "exactly once" claim. Structured Streaming guarantees exactly-once commit semantics for offsets; whether end-to-end results are exactly once depends on the sink. Partitioned parquet written with a deterministic path per batch, or an upsert keyed on the window and page, makes replay harmless. Appending to a single unpartitioned file with no key does not.
# Idempotent sink pattern: write to a staging path, then commit atomically.
from pyspark.sql import functions as F
import shutil, os
def write_idempotent(batch_df, batch_id, dest):
staging = f"{dest}/_staging/{batch_id}"
final = f"{dest}/batch_id={batch_id}"
batch_df.write.mode("overwrite").parquet(staging)
if os.path.exists(final):
shutil.rmtree(final) # replay of the same batch converges
os.rename(staging, final)
(
windowed.writeStream
.outputMode("update")
.option("checkpointLocation", "s3://checkpoints/click-agg-commit")
.foreachBatch(lambda df, bid: write_idempotent(df, bid, "s3://lake/mart/page_hits/"))
.start()
.awaitTermination()
)
The invariant to remember: the checkpoint says "these offsets are done", so anything that happened for those offsets must be repeatable. Idempotency is not an optimisation in streaming, it is a precondition for restarting at all.
Where state lives and why it grows
Stateful operators â aggregations, deduplications, stream-stream joins â keep per-key state in an RocksDB-backed store on the executor, backed up to a state changelog in the checkpoint. Three forces grow it: high-cardinality keys, windows with long retention, and watermarks set so generously that old keys are never expired.
Growth is observable before it is fatal. The streaming UI reports state operator size and numRowsInStateStore; a steady upward trend with a flat input rate means keys are never released, usually because the watermark column has nulls, defaults, or a clock skew that keeps event time stuck. Aggregations that only need approximate answers can use Bloom filters or approximate counts to shrink state dramatically.
Skew affects streams exactly as it affects batch: one hot key makes one task slow, and since batches commit as a unit, that task sets the batch duration. Salting the key before aggregation, raising parallelism, or splitting the hot key's work across subtasks are the available remedies.
Failure modes worth rehearsing
Deploy the restart drill before you need it. Stop the query, delete nothing, restart from the checkpoint, and verify that the sink shows no duplicates and the offsets resume. Then test the ugly cases: a source outage longer than your watermark, a schema change that makes previously valid JSON unparseable, and a downstream filesystem permission change that fails writes mid-batch.
Schema evolution deserves particular attention. A new field in the source JSON either fails the parse and stalls the batch or is silently dropped, depending on your options, and both are better than an implicit cast that produces nulls nobody notices. Declare the schema explicitly, validate on read, and route unparseable records to a quarantine path rather than killing the pipeline.
â ī¸A checkpoint is not a backup
Deleting or losing a checkpoint does not merely restart the query â it changes the offsets the query believes it has processed, which can skip data or replay days of history. Version it, protect it, and never point a query at a checkpoint created for a different source or a different state schema.
Common Mistakes
Relying on default trigger with an unbounded source and no maxOffsetsPerTrigger
Fix: Set a processing interval and a per-trigger offset cap so batches stay bounded
Setting no watermark and wondering why state grows without limit
Fix: Watermark on the event-time column with a delay that matches your real lateness distribution
Assuming an unpartitioned file sink is exactly-once
Fix: Use an idempotent or transactional sink, or key the output so replays converge
Changing a stateful operator's schema and reusing the old checkpoint
Fix: Start a new checkpoint location and backfill, because state schema changes are not compatible
Best Practices
- Keep checkpoints in versioned storage with lifecycle rules that never expire active queries
- Bound each batch with maxOffsetsPerTrigger and monitor batch duration against the trigger interval
- Validate and quarantine bad records instead of letting one malformed row stall a batch
- Prefer append or update modes with an explicit watermark over complete mode on large results
- Rehearse restarts in staging so recovery is a runbook entry rather than an incident
Interview Questions
Q1: What is a watermark in Structured Streaming?
The maximum observed event time minus a configured delay; it bounds how late data may arrive and when state for a window may be dropped.
Q2: Difference between append, update, and complete output modes?
Append emits rows once final, update emits each change to a row, complete rewrites the whole result every batch.
Q3: Why can two batches process the same records?
A crash between sink write and offset commit replays the range, so the sink must be idempotent for end-to-end exactly-once.
Q4: How do you stop state from growing forever?
Watermark on event time, bound window retention, and keep key cardinality under control; monitor numRowsInStateStore for trend.
Key Takeaways
- A streaming query is a sequence of batch queries committed through a checkpoint
- The trigger sets latency and cost; maxOffsetsPerTrigger sets the safety bound per batch
- Watermarks trade late-data correctness against state size, and the delay should be measured rather than guessed
- Exactly-once depends on the sink as much as on the engine, so make writes idempotent
- State growth and skew are visible in the streaming UI long before they become failures