The one-line mental model
Structured Streaming treats a stream as a table that keeps growing, and every question you will face in production reduces to three choices: which output mode describes your result, how long watermarks keep state alive, and which trigger decides when work happens.
You will be able to reason about late data without hand-waving, pick an output mode that Spark will actually accept for your aggregation, size a checkpoint so a restart resumes exactly where it stopped, and explain to an interviewer why a streaming query silently produced duplicate rows after a redeploy.
Prerequisites
- !Spark DataFrame API: transformations, actions and lazy evaluation
- !Batch window functions and the difference between event time and processing time
What You'll Learn
- 1Match output modes to query types and know what each mode recomputes
- 2Tune watermark delay against state size and late-data loss
- 3Choose triggers for backfill, continuous low latency and scheduled micro-batches
- 4Design checkpoints so restarts are safe and offsets are never lost
Why the table metaphor changes your code
In the classic streaming model you wrote imperative callbacks: receive a record, mutate a variable, emit a result. Structured Streaming inverts that. You declare a query over an unbounded table, Spark plans it through the same Catalyst optimizer as a batch query, and the runtime repeatedly runs that plan over new slices of input called micro-batches. The practical consequence is that batch expertise transfers directly: joins, window functions, aggregations and dropping columns all behave as they do in batch, and the engine handles offset tracking and fault tolerance for you.
The second consequence is that a query is a long-lived object with state. It holds aggregation state, it holds a position in every input topic, and it holds a schema that must stay compatible with whatever the source now emits. That is why most streaming incidents are not logic bugs: they are schema drift breaking a running query, a checkpoint written by a different version of the code, or state that grew because no watermark told Spark when to forget. Designing the query means designing its lifecycle, not just its transformations.
Output modes and what each one actually costs
An output mode tells Spark which rows from the result table are eligible to leave the engine on each trigger. Choosing one that does not match your query type fails fast at start-up, so it is worth knowing the rule rather than guessing.
| Output mode | Rows emitted each trigger | Valid for | State and cost profile |
|---|---|---|---|
| Append | Only rows that will never change | Stateless filters, projections, inner stream-stream joins | Lowest: no state, no recomputation |
| Update | Rows inserted or changed since the last trigger | Aggregations, including most session and window queries | Medium: state grows until watermarks expire it |
| Complete | The entire result table every trigger | Small aggregates such as per-category counts | Highest: full result rewritten each batch |
The classic interview trap is requesting append mode for a groupBy without a watermark. Append mode promises that emitted rows are final, but an aggregation over event time can always receive a late record that changes a past bucket, so Spark rejects the combination rather than lying to you. Add a watermark, and the query becomes append-eligible once each window is past its deadline, which is exactly how nightly reports are produced from continuous input.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder \
.appName("click-aggregation") \
.config("spark.sql.streaming.schemaInference", "true") \
.getOrCreate()
raw = spark.readStream.format("kafka") \
.option("kafka.bootstrap.servers", "broker1:9092,broker2:9092") \
.option("subscribe", "clicks") \
.option("startingOffsets", "earliest") \
.option("maxOffsetsPerTrigger", 500000) \
.load()
clicks = raw.select(
F.col("key").cast("string").alias("user_id"),
F.from_json(F.col("value").cast("string"), schema).alias("data"),
F.col("timestamp").alias("ingest_time")
).select("user_id", "data.*", F.col("data.ts").alias("event_time"))
hourly = clicks \
.withWatermark("event_time", "20 minutes") \
.groupBy(F.window("event_time", "1 hour"), "campaign") \
.agg(F.count("*").alias("clicks"), F.countDistinct("user_id").alias("users"))
query = hourly.writeStream \
.format("delta") \
.outputMode("update") \
.option("checkpointLocation", "s3://checkpoints/click-hourly") \
.option("path", "s3://warehouse/click_hourly") \
.trigger(processingTime="1 minute") \
.start()
query.awaitTermination()
Event time, watermarks and what you give up
Event time is when the thing happened; processing time is when Spark saw it. Users care about event time, so aggregations should group on it, but event time guarantees that late records will arrive, out of order, forever. A watermark is the compromise: it declares that records with an event time older than the maximum observed time minus the delay are no longer interesting, and it gives Spark permission to drop their state.
Tuning the delay is a direct trade-off measured in two currencies. Too short and you silently discard legitimate late data, which shows up as undercounted dashboards that nobody can explain. Too long and every window keeps state for the whole delay period, multiplying shuffle write volume and executor memory. A useful starting point is the observed tail of your end-to-end latency: measure how late records usually are at the ninety-ninth percentile, add headroom, and revisit after each major traffic change. Watermarks only advance when new data arrives, so an idle topic freezes state cleanup entirely, which is worth remembering before you blame a memory leak.
Windowing strategies for real traffic
Spark offers three window shapes and the choice is a business decision before it is a technical one. Tumbling windows are fixed and non-overlapping, which makes them trivially parallel and the default for reporting periods. Sliding windows overlap by a fixed step, so a record belongs to several buckets and each bucket is computed independently. Session windows are the interesting case: they grow with activity and close after a gap, which is what product analytics actually wants when it asks how long a user stayed.
# Tumbling: fixed, non-overlapping, ideal for hourly reporting
tumbling = clicks \
.withWatermark("event_time", "20 minutes") \
.groupBy(F.window("event_time", "1 hour"), "campaign") \
.agg(F.count("*").alias("clicks"))
# Sliding: 1 hour window advancing every 15 minutes, five copies per record
sliding = clicks \
.withWatermark("event_time", "20 minutes") \
.groupBy(F.window("event_time", "1 hour", "15 minutes"), "campaign") \
.agg(F.avg("value").alias("avg_value"))
# Session: gap-based, requires a watermark for state to be reclaimed
sessioned = clicks \
.withWatermark("event_time", "30 minutes") \
.groupBy(F.session_window("event_time", "30 minutes"), "user_id") \
.agg(F.count("*").alias("events_in_session"))
Every record in a sliding window lands in five buckets, so state and shuffle volume scale with the overlap ratio; that is a cost you pay for smoother metrics. Session windows are stateful in the strict sense that a session can keep extending, so without a watermark the state store never shrinks and the query eventually dies with an out-of-memory error on the executor.
Triggers: deciding when work happens
The trigger is the scheduling policy of your query, and it is the fastest lever you have for latency and cost.
| Trigger | Behaviour | Typical use |
|---|---|---|
| Default (unset) | Starts the next batch as soon as the previous finishes | Maximum throughput when latency does not matter |
processingTime="30 seconds" | One batch per interval, late arrivals land in later batches | Scheduled near-real-time dashboards |
once=True | Drains everything available, then stops | Simple one-shot backfill |
availableNow=True | Drains in bounded batches, then stops cleanly | Recurring backfill, large catch-up after downtime |
continuous="1 second" | Approximate, sub-second per-record latency | Telemetry where seconds matter more than exactness |
availableNow replaced most uses of once in practice, because once tries to materialise the entire backlog in a single batch and can exhaust memory after an outage, while availableNow processes the backlog in chunks with normal batch sizing and then exits with a successful status. Continuous processing remains experimental and only supports a limited set of operations, so it is chosen for latency, not for correctness of complex aggregations.
Checkpointing, offsets and exactly-once output
A checkpoint directory is the memory of your query. It stores the offsets read from each source partition, the state of every aggregation, and the commit metadata that makes the sink idempotent. Restart with the same checkpoint and Spark resumes exactly where it stopped; point the query at a different checkpoint and it starts over from startingOffsets, which is the most common way a redeploy silently duplicates days of data.
# Restart safety: same checkpoint, same query logic, no duplicates
query = hourly.writeStream \
.format("delta") \
.outputMode("update") \
.option("checkpointLocation", "s3://checkpoints/click-hourly") \
.trigger(availableNow=True) \
.start()
query.awaitTermination()
# Operational inspection: what is this query actually doing?
print(query.status)
print(query.lastProgress)
print(query.exception())
Exactly-once semantics require all three parts to hold: at-least-once reads from the source, offset commits recorded in the checkpoint, and an idempotent or transactional sink. Writing to plain parquet with mode("append") breaks the third leg, because a replayed batch appends its files a second time. Table formats with transaction logs such as Delta or Iceberg restore it, because the batch id is part of the transaction and a duplicate commit is rejected.
State, skew and failures you will meet in production
Three operational problems account for most paging alerts. State grows without bound when a watermark is missing or too long, and the symptom is executor memory pressure that appears days after deployment rather than at start-up. Skew appears when one key, such as a single high-traffic account, dominates an aggregation, so one task runs for minutes while the rest idle; the fix is salting the key or enabling adaptive execution to reshuffle. And schema evolution breaks running queries when a producer adds a required field, which is why schemas should be registered centrally and read by both sides rather than inferred from the first batch.
Recovery is mechanical if you have been disciplined: delete nothing, restart with the identical checkpoint, and let Spark rewind to the last committed offsets. If the query logic itself changed in a way that alters state schema, plan a migration: stop the query, clear or migrate the state directory deliberately, and accept a bounded reprocess with a documented start time. Silent clearance of a checkpoint is the one action that turns a small code change into an incident.
Common Mistakes
Requesting append mode for an aggregation with no watermark
Fix: Use update mode, or add a watermark so Spark knows when each window is final
Reusing a checkpoint directory after changing query logic
Fix: Treat checkpoints as versioned artefacts: migrate or rebuild state deliberately, never casually
Writing to a non-transactional sink and calling the pipeline exactly-once
Fix: Write to a table format with a transaction log so replayed batch ids are rejected
Setting an aggressive watermark to save memory during a load spike
Fix: Measure the late-data tail first, then tune; lost records never return
Best Practices
- Set maxOffsetsPerTrigger so a backlog cannot produce one enormous batch
- Monitor state store size, batch duration and input lag as first-class metrics
- Pin the schema in a registry instead of relying on schemaInference
- Prefer trigger availableNow for catch-up work after downtime
- Keep the checkpoint on durable, versioned storage separate from output data
Interview Questions
Q1: Why can't a streaming aggregation without a watermark use append mode?
Append mode guarantees emitted rows never change, but without a watermark Spark cannot know a window is final, so the combination is rejected at query start.
Q2: What does a watermark actually store?
It tracks the maximum event time seen per key plus the configured delay, and it is used both to expire state and to decide whether an incoming late record is still accepted.
Q3: How does a query recover after an executor fails?
Offsets and state live in the checkpoint; Spark restarts the affected stage, re-reads input from the last committed offsets, and writes through an idempotent sink.
Q4: Difference between once and availableNow triggers?
once runs the whole backlog as one batch and risks OOM, while availableNow drains it in normal-sized batches and then terminates successfully.
Key Takeaways
- Output mode must match the query: append for final rows, update for evolving aggregates, complete for tiny result tables
- Watermarks trade late-data accuracy against state size, and they only advance when data flows
- Sliding and session windows multiply state; tumbling windows are the cheap default
- The checkpoint holds offsets, state and commit metadata, which is what makes restarts safe
- Exactly-once needs source offsets, checkpointed commits and a transactional sink together