The State Store
Concepts covered: Structured Streaming
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.
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.
per_city = trips.groupBy("city").count()
per_city.collect()| trip_id | city |
|---|---|
| 1 | Lagos |
| 2 | Lima |
| 3 | Oslo |
| 4 | Lagos |
| 5 | Pune |
| 6 | Lima |
| 7 | Lagos |
| 8 | Oslo |
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
Heap state holds up until garbage collection takes over. Every stored key and value is an object the collector must trace, so a few million keys per executor push the GC Time figure in the Executors tab toward a large share of task time, and a full collection can stall a batch for seconds. The RocksDB provider, available since Spark 3.2, moves the map into an embedded key-value store that keeps recent data in native memory and the rest in sorted files on the executor's local disk. The heap then holds only what the current batch touches.
spark.conf.set(
"spark.sql.streaming.stateStore.providerClass",
"org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider",
)
spark.conf.set(
"spark.sql.streaming.stateStore.rocksdb.changelogCheckpointing.enabled",
"true",
)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.
- Default heap provider
- 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
- RocksDB provider
- 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
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?
- Spark rehashes every stored key into 24 partitions during the first batch after restart.
- The query keeps running with 200 state partitions, the count its checkpoint recorded.
- The query runs on 24 partitions and every city's count restarts from zero.
- The query refuses to start until the old state directory is removed by hand.
About this lesson
This section is part of the Structured Streaming: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.