What you will be able to do
- Explain what the StateStore holds for stateful streaming operators and how the checkpoint constrains it
- Define a StatefulProcessor with state variables and handleInputRows, and apply it with transformWithState
- Choose between ValueState, ListState and MapState, and between handleInputRows and handleExpiredTimer
- Relate transformWithState to the legacy operators and pick the right GroupStateTimeout
1.What stateful operators keep in the StateStore
A stateless streaming query only needs to remember which source rows it has already processed. A stateful query also needs intermediate results that carry over from one micro-batch to the next: a running count per key, the IDs already seen, or rows buffered while waiting for a join partner. The operators that need this are streaming aggregation, distinct, dropDuplicates, stream-stream joins and custom stateful applications. Each one keeps its state per key in a state store, which is saved to the query's checkpoint along with every micro-batch. (The micro-batch and checkpoint model is covered in the Structured Streaming engine.)
Because state is tied to the checkpoint, any setting that controls how the state is laid out is fixed once the query first runs. The state store provider is one example. You can switch to RocksDB with spark.sql.streaming.stateStore.providerClass set to org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider, but only before the first start. A query that began on the default provider must restart from a new checkpoint location to change it.
The shuffle partition count is fixed for the same reason, since state is split across those partitions. Checkpointing also has a cost. By default, RocksDB snapshots and uploads its data files at each checkpoint. Changelog checkpointing (spark.sql.streaming.stateStore.rocksdb.changelogCheckpointing.enabled) writes only the records that changed since the last checkpoint, which cuts checkpoint time and end-to-end latency.
You can read the state back as a batch DataFrame, which helps with debugging. The statestore reader returns key, value and partition_id columns for each operator record. With readChangeFeed set to true it also returns batch_id and change_type. That shows state being versioned micro-batch by micro-batch: each batch records update or delete changes against the previous version.
df = (spark.read
.format("statestore")
.load("/checkpoint/path"))Checkpoint 1 of 6· Check yourself
A stateful streaming query has been running on the default state store provider. You set spark.sql.streaming.stateStore.providerClass to the RocksDB provider. What do you need to do for the query to use RocksDB?
The checkpoint fixes the state store layout when the query first runs. A query that started on the default provider has to start from scratch with a new checkpoint location to switch to RocksDB.
“If a query has been started with the default management, you must restart it from scratch with a new checkpoint location”Source: docs.databricks.com
Checkpoint 2 of 6· Fill the gap
Which format name completes this batch read of a stateful query's state, so that it returns key, value and partition_id columns?
df = (spark.read
.format(" ? ")
.load("/checkpoint/path"))The statestore reader loads a query's checkpoint path as a batch DataFrame, with key, value and partition_id for each operator record. That makes it useful for debugging state.
Source: docs.databricks.com2.Defining a StatefulProcessor for transformWithState
Built-in stateful operators should come first. For aggregations, deduplication and stream-stream joins, they are the recommended choice. transformWithState is for logic they cannot express, such as keeping only the latest location per user or emitting an alert when a session goes quiet. You write that logic as a subclass of StatefulProcessor, and Spark runs it once per grouping key in each micro-batch.
A processor has three methods. init receives a StatefulProcessorHandle and uses it to create state variables. Each variable has a unique name and a schema, and Python requires the schema. handleInputRows(key, rows, timerValues) is called with the grouping key and an iterator over all of that key's rows in the current micro-batch. It reads and updates state, then yields the output rows. close handles cleanup. In the sample below, user_id is the grouping key and session_id is the key inside a MapState, so each user keeps a count per session.
class SessionTracker(StatefulProcessor):
def init(self, handle: StatefulProcessorHandle) -> None:
self.sessions = handle.getMapState("sessions", "session_id string", "count long")
def handleInputRows(self, key, rows: Iterator[Row], timerValues) -> Iterator[Row]:
for row in rows:
session_key = (row["session_id"],) # session_id is the MapState key
count = self.sessions.getValue(session_key)[0] if self.sessions.containsKey(session_key) else 0
new_count = count + 1
self.sessions.updateValue(session_key, (new_count,))
yield from []
def close(self) -> None:
pass
df.groupBy("user_id").transformWithState(SessionTracker(), ...) # user_id is the grouping keyTo apply the processor, group the streaming DataFrame and pass the processor instance together with the output schema, an output mode and a time mode. Then write the result as a stream with a checkpoint location, because that checkpoint is where the state is stored. PySpark has two variants. The row-based transformWithState passes Row iterators, as in the sample above. transformWithStateInPandas passes pandas DataFrames instead and is not supported in real-time mode. Scala has only the row-based API.
q = (
df.groupBy("user")
.transformWithStateInPandas(
statefulProcessor=SCDType1StatefulProcessor(),
outputStructType=output_schema,
outputMode="Update",
timeMode="None",
)
.writeStream.format("memory")
.queryName("scd1_output")
.option("checkpointLocation", f"/tmp/checkpoint_{uuid.uuid4()}")
.trigger(availableNow=True)
.start()
)u1 maps to SF (time 3) and u2 maps to London (time 5). Within each user's rows the processor picks the maximum time, and it updates state and emits a row only when no state exists yet or the new time is later than the stored one.
Checkpoint 3 of 6· Match them up
In the SessionTracker processor, each part has its own job. Match each part to the job it does.
Tap a term, then the definition that fits it.
init creates state through the handle, handleInputRows does the per-key work for each micro-batch, and close cleans up. The groupBy column is the grouping key that state is stored under, and the MapState key splits that state further, here by session.
“Spark passes a StatefulProcessorHandle to the init method of your StatefulProcessor. Use the handle to create state variables and interact with the state store.”Source: docs.databricks.com
Sources4
3.State variables, timers and initial state
The state type you choose determines how values are updated and expired. One processor can hold several state variables. Each variable can have its own time-to-live (TTL) in milliseconds, which keeps state from growing without limit.
| State type | Holds per grouping key | Update and TTL behaviour |
|---|---|---|
| ValueState | One value, which can be a struct or tuple | Replace the whole value; TTL resets only when the value updates |
| ListState | A list of values | Append items or a list, or overwrite with put; each item has its own TTL, and only put resets it |
| MapState | Distinct keys mapped to values, like a Python dict | Update or remove single keys; each key-value pair has its own TTL |
Timers handle logic based on time. handleInputRows runs only for keys that receive rows in the current micro-batch. handleExpiredTimer runs when a timer fires, whether or not new data arrived. Both methods can read and write state, create or delete timers, and emit rows. Only handleInputRows can iterate over the batch's rows, and only handleExpiredTimer reacts to elapsed time. A typical combination: each batch, handleInputRows updates the state and sets a timer 10 seconds ahead. If more rows arrive, it deletes that timer and sets a new one. If none arrive, handleExpiredTimer emits the stored values.
The third optional method, handleInitialState, fills state before any input rows are processed. For example, you can seed the counts from an earlier system so that a new query does not start every key at zero.
Checkpoint 4 of 6· Check yourself
Your processor must emit a user's stored values once 10 seconds pass with no new events for that user. Which method should emit those values?
handleInputRows runs only for keys that receive rows in the current micro-batch, so it can't react to silence. handleExpiredTimer runs on elapsed time whether or not new data arrived, so it can emit the stored values when the timer fires.
“Implement handleExpiredTimer to run time-based logic regardless of whether the grouping key receives new rows in a micro-batch.”Source: docs.databricks.com
Sources4
4.Legacy arbitrary stateful operators and their timeouts
Before transformWithState, arbitrary state was handled by mapGroupsWithState and flatMapGroupsWithState on grouped Datasets, and by applyInPandasWithState in Python. Each one calls a function with the key, an iterator of the key's values, and one GroupState object. The function reads the previous state from that object and writes the new state back. Like handleInitialState, these operators accept an initialState argument, so a stream started without a valid checkpoint does not have to reprocess old data.
fruitStream
.groupByKey(x => x)
.flatMapGroupsWithState(Update, GroupStateTimeout.NoTimeout, fruitCountInitial)(fruitCountFunc)The timeoutConf argument (a GroupStateTimeout) controls when an idle group's state can expire. NoTimeout keeps state until your function clears it. ProcessingTimeTimeout expires a group after a set amount of wall-clock time with no data for that group, without regard to event-time watermarks. EventTimeTimeout is driven by the watermark, so it depends on event times in the records. Processing-time timeouts also depend on micro-batches running. If spark.sql.streaming.noDataMicroBatches.enabled is false, an expired group may not produce output until new data arrives.
For new code, transformWithState replaces all of these operators. It supports several typed state variables instead of one GroupState, a TTL for each value, explicit timers, and schema evolution of state without reprocessing. The legacy operators also cannot be chained with other stateful operators in the same query. If a windowed aggregation feeds a further stateful step, that step must be transformWithState.
Checkpoint 5 of 6· Check yourself
In one streaming query, a windowed count feeds a custom step that keeps arbitrary per-key state. Which operator can do that custom step?
The legacy operators (flatMapGroupsWithState, mapGroupsWithState and applyInPandasWithState) cannot be used in queries that have more than one stateful operator. Their output mode, timeout or initial state makes no difference. transformWithState is supported in these chained queries.
“Legacy custom stateful operators (FlatMapGroupWithState and applyInPandasWithState) are not supported.”Source: docs.databricks.com
Checkpoint 6 of 6· Exam question
Which timeoutConf value should be passed to applyInPandasWithState so a group's state expires after a fixed amount of wall-clock time has elapsed since it last received data, independent of any event-time watermark in the incoming records?
Correct answer: C — GroupStateTimeout.ProcessingTimeTimeout()
- A. This disables automatic expiration entirely, so state for a group is retained indefinitely until the per-group function itself calls
state.remove(), which does not satisfy a fixed wall-clock expiration requirement. - B. This ties expiration to the watermark computed from an event-time column in the data, so how quickly state expires depends on data arrival patterns rather than a fixed span of processing time.
- C. This measures elapsed wall-clock time against the duration set with
state.setTimeoutDuration(), independent of any event-time column or watermark, which is exactly the behavior described. - D.
GroupStateTimeouthas no member with this name; the only valid timeout configurations areNoTimeout(),ProcessingTimeTimeout(), andEventTimeTimeout().
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Stateful operations include streaming aggregation, distinct, dropDuplicates, stream-stream joins, and custom stateful applications.”
↩︎ What stateful operators keep in the StateStore“The state management scheme can't be changed between query restarts.”
↩︎ What stateful operators keep in the StateStore“stateful operations that use watermarks or processing time timeouts not getting data output until new data arrives instead of immediately.”
↩︎ Legacy arbitrary stateful operators and their timeouts“The number of shuffle partitions is fixed at the time the checkpoint is created.”
↩︎ Exam trap 1“Legacy custom stateful operators (FlatMapGroupWithState and applyInPandasWithState) are not supported.”
↩︎ Exam trap 2“Changing spark.sql.shuffle.partitions has no effect on a streaming query that already has a checkpoint”
↩︎ Prediction“If a query has been started with the default management, you must restart it from scratch with a new checkpoint location”
↩︎ Checkpoint“Legacy custom stateful operators (FlatMapGroupWithState and applyInPandasWithState) are not supported.”
↩︎ Checkpoint - 2.
“changelog checkpointing only writes records that have changed since the last checkpoint to durable storage.”
↩︎ What stateful operators keep in the StateStore - 3.
“The batch ID that the state change belongs to.”
↩︎ What stateful operators keep in the StateStore - 4.
“Spark passes a StatefulProcessorHandle to the init method of your StatefulProcessor.”
↩︎ Defining a StatefulProcessor for transformWithState“For each micro batch processed, all rows for the key are available as an iterator.”
↩︎ Defining a StatefulProcessor for transformWithState“In Python, you must specify the schema. In Scala, you can pass an Encoder to specify state schema.”
↩︎ Defining a StatefulProcessor for transformWithState“Implement handleExpiredTimer to run time-based logic regardless of whether the grouping key receives new rows in a micro-batch.”
↩︎ State variables, timers and initial state“Optionally, implement handleInitialState to pre-populate state before your application processes any input rows.”
↩︎ State variables, timers and initial state“Spark passes a StatefulProcessorHandle to the init method of your StatefulProcessor. Use the handle to create state variables and interact with the state store.”
↩︎ Checkpoint - 5.
“Databricks recommends using transformWithState to build custom stateful applications.”
↩︎ Legacy arbitrary stateful operators and their timeouts