Structured Streaming: Advanced
A stateful operator needs rows from earlier micro-batches to answer the current one. A running count per city needs the count so far, dropDuplicates needs every ID it has seen, and a stream-stream join needs the unmatched rows from both sides. Spark keeps that memory in a state store: a versioned key-value map that each stateful operator holds once per shuffle partition.
per_city = trips.groupBy("city").count()per_city.collect()
In the streaming plan, 2 operators wrap that shuffle's reducer side. Call query.explain() on a running aggregation and you find StateStoreRestore, which reads each key's old count from the store, and StateStoreSave, which writes the new one. In batch 41, the task for partition 2 loads version 41 of the store for operator 0, partition 2, applies the batch's updates, and commits version 42. A coordinator on the driver tracks which executor has each store loaded, and the scheduler treats that executor as the preferred location for the partition's next task. If the task waits out the locality timeout and runs elsewhere, the new executor reloads the store from the checkpoint.
Where the bytes sit, batch by batch
The default provider keeps each partition's map in executor heap, as a hash map of UnsafeRow keys and values. Each commit writes only the keys that batch changed or removed, to a file named for the new version, N.delta, under the checkpoint directory. A background maintenance task, which runs every 60 seconds by default, folds the deltas into a full N.snapshot once 10 of them have piled up since the last snapshot.
| Checkpoint path | Written when | Holds |
|---|---|---|
| offsets/41 | Batch 41 starts | Source offsets batch 41 reads |
| state/0/2/40.snapshot | Maintenance, after 10 deltas | Every key of operator 0, partition 2 |
| state/0/2/41.delta | Batch 40 commits | Keys batch 40 changed |
| state/0/2/42.delta | Batch 41 commits | Keys batch 41 changed |
| commits/41 | Batch 41 finishes | Marker that batch 41 is done |
To run batch 42 after a restart, Spark loads 40.snapshot. It then replays 41.delta and 42.delta on top, so recovery reads 1 full copy of the state plus a few small files. Files for the last 100 batches are kept by default (spark.sql.streaming.minBatchesToRetain), and maintenance deletes older ones.
What the checkpoint freezes
The number of state partitions is whatever spark.sql.shuffle.partitions held when the query first started, and Spark writes that value into the checkpoint. Change the setting later and a restart keeps the recorded value, because each key's state sits in the files of the partition its hash chose. The provider class is recorded the same way. Both are first-start decisions: a small stream left at the default 200 partitions runs 200 stateful tasks per batch, each opening its own store, for as long as that checkpoint lives.
When the heap gives out: RocksDB
RocksDB checkpoints incrementally too. At each commit it uploads only the sorted files written since the previous upload, plus a small zip listing the files that make up that version. With changelog checkpointing, available since Spark 3.5, a commit writes only a log of changed keys and moves file uploads to the background, which shortens every batch's commit. Its memory lives outside the heap, so budget it in spark.executor.memoryOverhead.
- State as UnsafeRow objects in executor heap
- Commit writes a delta file of changed keys
- Snapshot built in the background every 10 deltas
- GC time grows with the number of keys
- State in native memory and local disk
- Commit uploads new sorted files, or a changelog
- Heap holds only the batch's working set
- State can grow past executor memory
query.lastProgress['stateOperators'] reports numRowsTotal and memoryUsedBytes for each stateful operator. A row count that climbs on every batch and never falls means nothing is freeing state.A per-city count first started with spark.sql.shuffle.partitions at 200. Months later the team sets it to 24 and restarts from the same checkpoint. What happens?
The watermark equals the largest event time seen so far, minus the delay. Spark computes it at the end of each micro-batch, taking the maximum across all partitions, and applies it during the next batch. It never moves backwards, and until the first batch finishes there is none, so the first batch drops nothing.
Which late rows are dropped
| Batch | Arriving events | Watermark in use | What happens | Watermark after |
|---|---|---|---|---|
| 0 | 12:02, 12:07, 12:14 | none | Windows 12:00 to 12:10 (count 2) and 12:10 to 12:20 (count 1) open | 12:04 |
| 1 | 12:21, 12:03 | 12:04 | 12:03 kept, since its window ends at 12:10; window 12:20 to 12:30 opens | 12:11 |
| 2 | none (no-data batch) | 12:11 | Window 12:00 to 12:10 ends before 12:11: written with count 3, then removed | 12:11 |
| 3 | 12:08, 12:13 | 12:11 | 12:08 dropped, its window is gone; 12:13 joins window 12:10 to 12:20 | 12:11 |
What the watermark frees
- ▸Rows within the delay of the newest event time are always kept.
- ▸In a windowed aggregation, Spark compares the window's end to the watermark, whether it is deciding to drop a row or to free state.
- ▸With several watermarked inputs, the global watermark is the lowest of them, set by
spark.sql.streaming.multipleWatermarkPolicy=min. - ▸Rows dropped as late are counted in
numRowsDroppedByWatermarkin the query's progress. - ▸When the watermark advances, Spark runs a no-data batch to apply it without waiting for new rows.
Windows are 10 minutes long, the delay is 10 minutes, and the watermark stands at 14:27. Which arriving row does Spark drop?
The cell replays a delivery log in arrival order. For each event it takes the newest event time received so far minus the delay, and flags the event if its own time sits at or behind that line. That is the test a watermarked dropDuplicates applies, since it has no window to check. If you change delay_seconds from 600 to 60 and rerun the cell, more events fall behind; count how many.
from pyspark.sql import Window
from pyspark.sql import functions as F
delay_seconds = 600
events = (
spark.table("app_event_deliveries")
.withColumn("event_time", F.to_timestamp("event_ts"))
.withColumn("arrival_time", F.to_timestamp("received_ts"))
.filter(F.col("event_time").isNotNull() & F.col("arrival_time").isNotNull())
)
seen_before = (
Window.orderBy("arrival_time", "delivery_id")
.rowsBetween(Window.unboundedPreceding, -1)
)
flagged = (
events
.withColumn("newest_seen", F.max("event_time").over(seen_before))
.withColumn(
"behind_line",
F.coalesce(
F.col("event_time").cast("long")
<= F.col("newest_seen").cast("long") - delay_seconds,
F.lit(False),
),
)
.select("delivery_id", "event_name", "event_time", "arrival_time", "behind_line")
.orderBy("arrival_time", "delivery_id")
)
flagged.show()The cell moves the line after every row, but Spark moves the watermark only at the end of a batch and applies it in the next one. Each flag therefore marks the earliest point at which Spark could drop that event: an event that arrives in the same batch as the newer event is still kept, so Spark drops the same rows or fewer. The cell also tests each event's own time, the rule for dropDuplicates; a windowed count tests the end of the event's window instead.
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)matched = requests.join(accepts,(requests.request_id == accepts.req_ref)& (accepts.acc_min >= requests.req_min)& (accepts.acc_min <= requests.req_min + 10),)matched.collect()
State that only grows
Two watermarks and a time range
The equality finds the partner, and the range tells Spark when a stored row can no longer find one. A query with 2 watermarked inputs has a single global watermark, by default the minimum of the 2; call it G. Spark treats any acceptance still to come as carrying an accept_time after G, so a stored request is deleted once G passes request_time plus 10 minutes. Any request still to come carries a request_time after G, so a stored acceptance is deleted once G passes its own accept_time.
| Quantity | Value | Why |
|---|---|---|
| Request watermark | newest request minus 5 min | Delay set on requests |
| Acceptance watermark | newest acceptance minus 15 min | Delay set on acceptances |
| G | 15 min behind | The lower of the 2, streams in step |
| A request is held | 25 min | Until G passes request_time + 10 min |
| An acceptance is held | 15 min | Until G passes accept_time |
| Request rows held | 4.5 million | 3,000 a second for 1,500 seconds |
Requests carry a 5-minute delay, acceptances a 15-minute delay, and someone deletes the upper bound so the join keeps only accept_time >= request_time. What happens to state?
Outer joins wait on the watermark
- Watermark both inputs, even on an inner join
- Bound the partner's time from both sides in the condition
- Set each delay from measured lateness, then work out state lifetime
- Watch numRowsTotal for the join after every change
- Ship an inner stream-stream join with no watermarks
- Write a one-sided range, which frees only 1 side's state
- Pad one stream's delay far past the other's
- Expect outer-join NULL rows before the watermark passes
| Source | Option | What it caps |
|---|---|---|
| Files | `maxFilesPerTrigger` | New files read per batch |
| Offset-based message log | `maxOffsetsPerTrigger` | Offsets per batch, split across the log's partitions by backlog |
| Offset-based message log | `minOffsetsPerTrigger` with `maxTriggerDelay` | A minimum batch size, waited for up to a time limit, since Spark 3.3 |
| Rate, for testing | `rowsPerSecond` | Rows generated each second |
Pricing the catch-up
Take the request stream from the message log, 3,000 rows a second on a 10-second trigger. A normal batch carries 30,000 rows and finishes in 6 seconds, about 0.2 milliseconds a row. A 30-minute outage leaves 5.4 million rows waiting, so the first uncapped batch after the restart is 180 times normal size. With maxOffsetsPerTrigger at 150,000, each batch looks like this:
| Each capped batch | Value |
|---|---|
| Rows read | 150,000 |
| Duration at 0.2 ms a row | 30 seconds |
| New rows arriving meanwhile | 90,000 |
| Backlog drained | 60,000 |
| Batches to clear 5.4 million | 90 |
Choosing the number
A stream averages 3,000 rows per second on a 10-second trigger, and each row costs about 0.2 milliseconds. After an outage, which maxOffsetsPerTrigger value never clears the backlog?
trigger(availableNow=True), added in Spark 3.3, drains everything waiting in several batches that respect the source's cap, then stops. The older trigger(once=True) reads it all in 1 batch and ignores the cap.The spark.streaming.backpressure.enabled setting belongs to Spark's older streaming API and changes nothing in Structured Streaming.
The cell splits a message table into capped batches in message order. Set cap to the rows you would allow per trigger and compare how many batches result and which messages each one covers.
from pyspark.sql import Window
from pyspark.sql import functions as F
cap = 5
backlog = spark.table("stream_msgs").filter(F.col("msg_id").isNotNull())
in_order = Window.orderBy("msg_id")
batches = (
backlog
.withColumn("batch_id", F.floor((F.row_number().over(in_order) - 1) / cap))
.groupBy("batch_id")
.agg(
F.count("*").alias("rows_in_batch"),
F.min("msg_id").alias("first_msg"),
F.max("msg_id").alias("last_msg"),
)
.orderBy("batch_id")
)
batches.show()What continuous mode gives up
- ▸Map-like operations only. You can use most SQL functions along with
select,filterormap. Anything that needs a state store, such as an aggregation or a join, is unsupported, and that includes deduplication. - ▸Sources: the message-log source and the rate source. Sinks: the message-log sink; the memory and console sinks also work but are meant for testing.
- ▸At-least-once delivery: after a failure, rows since the last committed epoch are written again.
- ▸One core per input partition for the life of the query, or it stops making progress.
- ▸No task retry: a failed task stops the query, and you restart it from the checkpoint.
A stateless filter feeds an alerting service that tolerates duplicate alerts and must react within 20 milliseconds. The source log has 12 partitions and the query gets 8 executor cores. What happens in continuous mode?
Matching the mode to a latency budget
| Latency budget | Query shape | Choose | What you pay |
|---|---|---|---|
| Minutes | Any | Micro-batch, trigger every 1 to 5 minutes | Little: fewer batches, fewer small files |
| 1 to 10 seconds | Aggregations, joins, dedup | Micro-batch, default trigger | The toll on every batch |
| 100 ms to 1 second | Stateless | Micro-batch, tuned: few shuffle partitions, fast checkpoint storage | Tuning effort, more frequent commits |
| Under 100 ms | Stateless, map-only | Continuous | At-least-once, manual restarts, pinned cores |
| Under 100 ms | Stateful | Neither: Spark's floor is above it | A different serving design |
Measure the toll before arguing about it. Each entry in query.recentProgress carries durationMs, where addBatch is the time spent running the batch's job and triggerExecution covers the whole batch, log writes included. If a stream on a 1-second trigger shows 400 milliseconds of triggerExecution outside addBatch, 40 percent of every second goes to bookkeeping.
A fraud check must flag a card within 50 milliseconds when its spend over the last 10 minutes passes a limit. Which plan fits?
> An ad platform credits each click to the impression that led to it, if the click comes within 30 minutes, and bills advertisers from the matched rows every minute. Impressions arrive at 20,000 a second, and mobile apps upload clicks in bursts that run up to an hour late.
click_time BETWEEN impression_time AND impression_time + INTERVAL 30 MINUTES give Spark a deletion rule for each side; a one-sided range would leave impressions in state forever.maxOffsetsPerTrigger sits above a normal batch and below the largest batch that ran without spill, so the burst after a source outage drains as a run of ordinary batches.Where streaming state lives, when Spark stops waiting for late rows, and how to keep a stream standing under load.
- Category
- Spark
- Difficulty
- advanced
- Duration
- 15 minutes
- Challenges
- 13 hands-on challenges
Topics covered: The State Store, Watermarks, Stream-Stream Joins, Backpressure, Micro-Batch vs Continuous
Lesson Sections
- The State Store (concepts: Structured Streaming)
The operator sits after a shuffle, so its state is split exactly like the shuffle output. The animation runs the batch form of a per-city count on 2 input partitions and 3 shuffle partitions. Track where each city lands: in a streaming query, the reducer task that receives a key is also the task that owns that key's state. Where the bytes sit, batch by batch What the checkpoint freezes When the heap gives out: RocksDB Heap state holds up until garbage collection takes over. Every stored key and
- Watermarks (concepts: Structured Streaming)
A window from 12:00 to 12:10 can always receive one more row: a phone that went offline can upload a 12:04 event an hour later. Without a rule for when to stop waiting, a windowed count keeps every window it ever opened, and its state grows until the executors run out of memory. A watermark is that rule, a moving event-time line behind which Spark treats data as finished. Which late rows are dropped For a windowed aggregation the test runs on the row's window, and the row's own timestamp only pi
- Stream-Stream Joins (concepts: Structured Streaming)
Joining 2 streams means neither side is ever complete. A ride request in batch 12 may meet its driver's acceptance in that same batch or 2 batches later in batch 14, and some requests never meet one. So Spark buffers both inputs: each new request is matched against every stored acceptance with the same key and then stored itself, and each new acceptance does the same against stored requests. One join keeps 4 state stores per shuffle partition, 2 per side: one counts the rows under each key and o
- Backpressure (concepts: Structured Streaming)
By default a micro-batch reads everything the source has received since the last committed offset. While input is steady that is a normal-sized batch, but after an outage or a spike the next batch inherits the whole backlog at once. One giant batch shuffles more data than the executors can hold, so it spills to disk or fails. Because a batch commits all or nothing, a failure discards the work and Spark retries the same giant batch. Structured Streaming leaves the intake rate to you: you set a ce
- Micro-Batch vs Continuous (concepts: Structured Streaming)
Every micro-batch pays a fixed toll before it touches a row. The driver first writes the batch's offsets to the write-ahead log, then plans and schedules a job. Stateful tasks load and commit their stores, and after the sink finishes the driver writes a marker to the commit log. Spark's documentation puts the micro-batch floor at about 100 milliseconds end to end, and a query with a stateful shuffle and object-store checkpoints usually needs a second or more per batch. Continuous processing, add