mapGroupsWithState and flatMapGroupsWithState
| Also known as | Arbitrary stateful operations (version 1); [flat]MapGroupsWithState; applyInPandasWithState in Python
|
|---|---|
| Field | Stream processing |
| Key parts | Grouping key, user function, GroupState object, GroupStateTimeout, output mode, optional initial state
|
| Open source implementations | Structured Streaming in Apache Spark 2.2 and later (Scala, Java); applyInPandasWithState in Python from 3.4
|
| Related | transformWithState, Watermark, State store |
In Structured Streaming, mapGroupsWithState and flatMapGroupsWithState are the original operators for arbitrary stateful processing: they call a user function for each grouping key with that key's new values and a GroupState object that holds the key's state between micro-batches.[2] They were added to Apache Spark in version 2.2.0 for the Scala and Java Dataset API, and Spark 3.4.0 added the Python counterpart applyInPandasWithState.[3][4] Spark 4.0 introduced transformWithState as their successor, but as of Spark 4.3.0 none of these operators is deprecated.[1]
Status
Whether these operators are "deprecated" is a common question, and the primary sources answer it the same way: they are not.
- Code (4.0.0 to 4.3.0): The
mapGroupsWithStateandflatMapGroupsWithStatemethods ofKeyValueGroupedDataset, in the shared API, the classic implementation and the Spark Connect client, have no@deprecatedannotation, and the PySparkapplyInPandasWithStatedocstring has no deprecation notice.[5][6] - Release notes: The Spark 4.0.0, 4.1.0, 4.2.0 and 4.3.0 release notes do not deprecate them.[7][8][9][10] The Structured Streaming migration guide lists no deprecation of them either.[11]
- Documentation: The Spark 4.3.0 programming guide describes them as the "legacy" operators and says that since Spark 4.0 users are encouraged to use
transformWithState.[1] The transformWithState guide calls that operator their "next generation replacement".[12] - Stability: From Spark 2.2.0 to 3.5, the
GroupStateinterface was annotated@Experimentaland@Evolving. Spark 4.0.0 removed@Experimental(SPARK-50770), so in Spark 4.x it carries only@Evolving.[13][14][2]
In short: the operators are supported and maintained in Spark 4.3.0 and existing queries keep working. New stateful applications are pointed to transformWithState.
How it works
A query groups a Dataset with groupByKey and passes a function to one of the two operators. For each key that has new data in a trigger, Spark calls the function with the key, an iterator over the new values and the key's GroupState. The function reads the state with get, getOption or exists, changes it with update, and deletes it with remove. For a batch Dataset, the function is called once per group with empty state, which makes the operators the same as mapGroups and flatMapGroups.[2]
The two operators differ in their output:[2]
- mapGroupsWithState returns exactly one record per call, and the query must use the Update output mode. Aggregations are not allowed in the same query.[1]
- flatMapGroupsWithState returns any number of records, including none, and takes an output mode parameter, Append or Update. In Append mode, aggregations are allowed after the operator.[1]
The guide also says that neither operator can be used before or after a stream-stream join.[1]
Timeouts
A query sets one timeout type for all groups with GroupStateTimeout: NoTimeout, ProcessingTimeTimeout or EventTimeTimeout. Each group then sets its own timeout with setTimeoutDuration (processing time) or setTimeoutTimestamp (event time, which needs a watermark). When the timeout passes, Spark calls the function for that group with no values and hasTimedOut set to true. A timeout never fires early, but there is no upper bound on how late it fires, because it is checked only when a trigger runs. The timeout is cleared on every call, so the function must set it again each time.[2]
Initial state
Spark 3.2.0 added overloads that take an initial state as a KeyValueGroupedDataset, to start a query with state loaded from elsewhere (SPARK-35897).[5][15]
Language and Spark Connect support
| API | Language | Added in | Spark Connect support |
|---|---|---|---|
KeyValueGroupedDataset.mapGroupsWithState, flatMapGroupsWithState |
Scala, Java | 2.2.0[3] | 3.5.0 (SPARK-43511)[16] |
GroupedData.applyInPandasWithState |
Python (pandas) | 3.4.0 (SPARK-40434)[4][6] | 3.5.0 (SPARK-43084)[17] |
Comparison with transformWithState
| mapGroupsWithState / flatMapGroupsWithState | transformWithState | |
|---|---|---|
| Added in | Spark 2.2.0[3] | Spark 4.0.0[7] |
| User code | One function of key, values and GroupState[2]
|
A stateful processor class with separate methods for input, timers, initial state and cleanup[12] |
| State per key | One object[2] | Any number of named value, list and map variables[12] |
| Timers | One timeout per key, reset on every call[2] | Many timers per key that persist until they fire or are deleted[12] |
| Automatic expiry (TTL) | No | Yes, per state variable, processing time only[12] |
| State store providers | HDFS-backed (default) or RocksDB | RocksDB only[18] |
| Real-time Mode (4.3.0) | flatMapGroupsWithState not yet supported[19]
|
Scala and Java API supported[19] |
| Deprecated? | No | No |
Example
A running count per word in Scala. words is a streaming Dataset[String] and spark.implicits._ is imported; the query must be written in Update output mode.
import org.apache.spark.sql.streaming.{GroupState, GroupStateTimeout}
val counts = words
.groupByKey(identity)
.mapGroupsWithState[Long, (String, Long)](GroupStateTimeout.NoTimeout) {
(word: String, values: Iterator[String], state: GroupState[Long]) =>
val updated = state.getOption.getOrElse(0L) + values.size
state.update(updated)
(word, updated)
}
See also
References
- ↑ 1.0 1.1 1.2 1.3 1.4 1.5 Structured Streaming Programming Guide: APIs on DataFrames and Datasets (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 GroupState.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 3.0 3.1 3.2 Spark Release 2.2.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 4.0 4.1 Spark Release 3.4.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 5.0 5.1 KeyValueGroupedDataset.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 6.0 6.1 group_ops.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 7.0 7.1 Spark Release 4.0.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 4.2.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Spark Release 4.3.0. Apache Software Foundation.Retrieved 2026-11-22.
- ↑ Structured Streaming Migration Guide (docs/streaming/ss-migration-guide.md at v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 12.0 12.1 12.2 12.3 12.4 Structured Streaming Programming Guide: transformWithState (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ GroupState.scala (v2.2.0). 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-35897: Support user defined initial state with flatMapGroupsWithState in Structured Streaming. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ SPARK-43511: Implemented State APIs for Spark Connect Scala. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ SPARK-43084: Add Python state API (applyInPandasWithState) and verify UDFs. Apache Software Foundation JIRA.Retrieved 2026-11-22.
- ↑ TransformWithStateExecBase.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-22.
- ↑ 19.0 19.1 Real-time Mode (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-22.