transformWithState
| Also known as | Arbitrary State API v2, TWS |
|---|---|
| Field | Stream processing |
| Key parts | Stateful processor, state variables (value, list, map), timers, TTL, time mode, output mode, optional initial state |
| Open source implementations | Structured Streaming in Apache Spark 4.0 and later (Scala, Java, Python) |
| Related | mapGroupsWithState and flatMapGroupsWithState, Watermark, State store |
StatefulProcessor, TimeMode) carry the @Evolving annotation at v4.3.0, not @Experimental.[1]In Structured Streaming, transformWithState is the operator for arbitrary stateful processing: user code, written as a stateful processor class, receives the rows for each grouping key, keeps any number of typed state variables for that key across micro-batches, registers timers and emits zero or more output rows.[2] It was added in Apache Spark 4.0.0 as the "Arbitrary State API v2".[3] The Spark documentation calls it the next-generation replacement for mapGroupsWithState and flatMapGroupsWithState in Scala and Java and for applyInPandasWithState in Python; those older operators are still supported and are not deprecated.[2]
What transformWithState is for
Built-in stateful operators such as streaming aggregation, deduplication and stream-stream joins cover common patterns, and Spark manages their state. Some logic does not fit them: sessionization with custom rules, downtime detection, fraud scoring over a user's history, or emitting an alert when nothing has arrived for a key. For these, Structured Streaming offers arbitrary stateful operators, where user code decides what to store, when to emit and when to forget.[4] transformWithState is the second generation of that API. The guide says that since Spark 4.0 users are encouraged to build complex stateful applications on it rather than on the older operators.[4]
How it works
A query groups a streaming Dataset or DataFrame by key and passes a stateful processor to transformWithState. The processor is a class that extends StatefulProcessor and implements these methods:[2][5]
init, called once to declare state variables through the processor's handle.handleInputRows, called with the key and an iterator of that key's new rows; it returns output rows.handleExpiredTimer, called once for each timer that has fired; by default it returns nothing.handleInitialState, available onStatefulProcessorWithInitialState, called once per key of an optional initial-state DataFrame before any input is processed.close, for cleanup.
State variables
State is declared as named variables, not as a single object per key. There are three types: ValueState (one value), ListState (appends are cheap) and MapState (point lookups by a user key are cheap). A processor can declare several of each, and each has its own encoder.[2] Variables can be added between runs of the same query, and removed with deleteIfExists in init. With the Avro state encoding (spark.sql.streaming.stateStore.encodingFormat set to avro), the schema of a variable's value can evolve by adding, removing, reordering or widening fields.[2]
Timers and TTL
The time mode is chosen per query: TimeMode.None(), TimeMode.ProcessingTime() or TimeMode.EventTime().[6] In processing-time or event-time mode, the processor can register, list and delete any number of timers per key; timers are checkpointed and can fire after a restart.[2] In event-time mode, timers fire as the watermark passes them.
Each state variable can have a time-to-live (TTL) through TTLConfig. Values are not returned after the TTL has passed and are eventually removed; every update resets the TTL. TTL works only with TimeMode.ProcessingTime.[2][7]
State store requirement
transformWithState runs only on the RocksDB state store. In a streaming query, the operator checks spark.sql.streaming.stateStore.providerClass and fails with the error STORE_BACKEND_NOT_SUPPORTED_FOR_TWS unless it is RocksDBStateStoreProvider.[8] The default provider in Spark 4.3.0 is still the HDFS-backed state store, so the setting must be changed before the query first starts; the provider cannot be changed between restarts of a query.[9] The operator stores its several variables as column families in one RocksDB instance.[3]
Debugging and testing
The state data source can read a transformWithState query's state one variable at a time (option stateVarName) and list registered timers (option readRegisteredTimers). TwsTester, in Scala and Python, runs a stateful processor without a streaming query for unit tests; it does not model TTL or automatic watermark advancement.[2]
Language and Spark Connect support
| API | Language | Data passed to the processor | Added in | Spark Connect support |
|---|---|---|---|---|
KeyValueGroupedDataset.transformWithState |
Scala, Java | Typed objects (encoders) | 4.0.0[3][10] | 4.1.0[11] |
GroupedData.transformWithStateInPandas |
Python | pandas DataFrames | 4.0.0[12] | 4.1.0[13] |
GroupedData.transformWithState |
Python | Row objects |
4.1.0[14] | 4.1.0[15] |
In Spark 4.0.0 the Spark Connect Scala client declared transformWithState but threw UnsupportedOperationException, and the Python Connect client had no transformWithStateInPandas; both work over Connect from 4.1.0.[16][17] The guide suggests the pandas variant for most Python users and the Row variant for high key cardinality, where conversion to pandas costs more.[2]
From Spark 4.3.0 the Scala and Java API can run with the real-time trigger (SPARK-57228); the two Python APIs are not supported in Real-time Mode.[2][18] transformWithState also runs in batch queries (SPARK-46865 for Scala, SPARK-50428 for Python).[3]
Comparison with mapGroupsWithState
| transformWithState | mapGroupsWithState / flatMapGroupsWithState | |
|---|---|---|
| Added in | Spark 4.0.0[3] | Spark 2.2.0[19] |
| User code | A class with init, handleInputRows, handleExpiredTimer and other methods[5]
|
One function of key, values and a GroupState[20]
|
| State per key | Any number of named value, list and map variables[2] | One state object[20] |
| Timers | Many timers per key, listed and deleted by the processor[2] | One timeout per key[20] |
| Automatic expiry | TTL per state variable (processing time)[2] | None; the function removes state itself, usually on timeout |
| State schema evolution | Supported for values with Avro encoding[2] | Not offered |
| State store | RocksDB only[8] | HDFS-backed (default) or RocksDB |
| Python API | transformWithStateInPandas (4.0.0), transformWithState (4.1.0)[12]
|
applyInPandasWithState (3.4.0)[12]
|
| Deprecated? | No | No; see mapGroupsWithState and flatMapGroupsWithState |
Example
A running count per word in Scala, for Spark 4.0 or later. words is a streaming Dataset[String] and spark.implicits._ is imported.
import org.apache.spark.sql.Encoders
import org.apache.spark.sql.streaming._
class RunningCount extends StatefulProcessor[String, String, (String, Long)] {
@transient private var count: ValueState[Long] = _
override def init(outputMode: OutputMode, timeMode: TimeMode): Unit = {
count = getHandle.getValueState[Long]("count", Encoders.scalaLong, TTLConfig.NONE)
}
override def handleInputRows(
key: String,
rows: Iterator[String],
timerValues: TimerValues): Iterator[(String, Long)] = {
val updated = (if (count.exists()) count.get() else 0L) + rows.size
count.update(updated)
Iterator((key, updated))
}
}
spark.conf.set("spark.sql.streaming.stateStore.providerClass",
"org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider")
val counts = words
.groupByKey(identity)
.transformWithState(new RunningCount, TimeMode.None(), OutputMode.Update())
See also
- mapGroupsWithState and flatMapGroupsWithState
- Structured Streaming
- Watermark
- Exactly-once semantics
- Spark Connect
References
- ↑ SPARK-46815: Structured Streaming - Arbitrary State API v2. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ 2.00 2.01 2.02 2.03 2.04 2.05 2.06 2.07 2.08 2.09 2.10 2.11 2.12 2.13 Structured Streaming Programming Guide: transformWithState (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 3.0 3.1 3.2 3.3 3.4 Spark Release 4.0.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 4.0 4.1 Structured Streaming Programming Guide: APIs on DataFrames and Datasets (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 5.0 5.1 StatefulProcessor.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ TimeMode.java (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ TTLConfig.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 8.0 8.1 TransformWithStateExecBase.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ SQLConf.scala (v4.3.0), spark.sql.streaming.stateStore.providerClass. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ SPARK-50770: Removing package scope for transformWithState operator APIs. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ SPARK-50855: Spark Connect Support for TransformWithState In Scala. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ 12.0 12.1 12.2 group_ops.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ SPARK-50856: Spark Connect Support for TransformWithStateInPandas In Python. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ SPARK-51814: Introduce a new API transformWithState in PySpark. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ SPARK-51827: Support Spark Connect in new API transformWithState in PySpark. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ connect/KeyValueGroupedDataset.scala (v4.0.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 4.3.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 2.2.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 20.0 20.1 20.2 GroupState.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.