Jump to content

Stateful stream processing

From Open Lakehouse Wiki
Stateful stream processing
Also known as Stateful streaming
Field Stream processing
Key parts Keyed state, timers, time-to-live (TTL), watermark, fault-tolerant state storage
Open source implementations Structured Streaming (built-in stateful operators, transformWithState), Apache Flink (keyed state, KeyedProcessFunction), Kafka Streams
Related State store, RocksDB state store, Streaming checkpoint, mapGroupsWithState and flatMapGroupsWithState
Last verified 23 November 2026 against the Spark 4.3.0 Structured Streaming programming guide (arbitrary stateful operations, unsupported operations) and transformWithState guide, SQLConf.scala at tag v4.3.0 of apache/spark, SPARK-40925, the Databricks "What is stateful streaming?" page, and the Apache Flink 2.3 "Working with State", "Process Function", "State Backends" and "State Schema Evolution" pages.

Stateful stream processing is stream processing in which the result for a record depends on information kept from earlier records, such as a running count, the last value seen for a key, or rows waiting for a join partner. The engine stores this state, usually partitioned by key, saves it to durable storage so it survives failures, and removes it when it is no longer needed. In Apache Spark Structured Streaming, state is held in a state store and used by built-in operators (aggregations, deduplication, stream-stream joins) and by the transformWithState operator for custom logic.[1][2]

What is the difference between stateless and stateful streaming?

A stateless query handles each record on its own: filters, projections, parsing, and joins with a static table. The only thing a stateless Structured Streaming query tracks is which input has been processed. A stateful query updates intermediate state in every batch.[3] State makes results possible that depend on history, but it costs memory and storage, adds checkpointing time, and fixes parts of the query for the life of its checkpoint.

What are state, timers and TTL?

State is data kept per key between records. In Spark's built-in operators, the engine decides what to keep: partial aggregates per group and window, the keys already seen for deduplication, or buffered rows for a join.[1]

A timer is a callback that the application registers for a future time, so that it can act when nothing arrives, for example to close a session or raise an alert after silence. An event-time timer fires when the watermark passes its time; a processing-time timer fires when the wall clock does.[4]

Time-to-live (TTL) makes state expire a set time after it was written, so that state for keys that go quiet does not stay forever. Both Spark and Flink measure state TTL in processing time.[2][5]

How does Structured Streaming handle state?

Most stateful Spark queries use built-in operators, and Spark manages their state. Streaming aggregations, dropDuplicates and stream-stream joins keep state per key in the state store and use the watermark to drop state that can no longer change; see Watermark, Streaming deduplication and Stream-stream join.[1]

For logic that does not fit them, Spark has arbitrary stateful operators. mapGroupsWithState and flatMapGroupsWithState date from Spark 2.2 and are now called legacy; since Spark 4.0, the guide encourages transformWithState instead.[6] In transformWithState, a stateful processor class declares named state variables of three types, ValueState, ListState and MapState, registers timers, sets optional TTL per variable and can be seeded with an initial state DataFrame. It is available in Scala, Java and Python.[2]

transformWithState timers can be listed, added and removed; a key can have several; and timers are checkpointed, so they can fire after a restart. TTL works only with TimeMode.ProcessingTime.[2] The operator requires the RocksDB state store.

Since Spark 3.4.0, a query can chain several stateful operators, for example an aggregation followed by a stream-stream join, in append mode. Late records are then filtered against the watermark of the previous micro-batch; spark.sql.streaming.statefulOperator.allowMultiple=false restores the earlier behavior with a single stateful operator.[7][8] Chaining stateful operators is not supported in update or complete output mode.[9]

How does Flink handle state?

Apache Flink's keyed state is scoped to the key of the current record and is available only on a KeyedStream, created with keyBy. The state primitives are ValueState, ListState, ReducingState, AggregatingState and MapState, each created from a state descriptor.[5]

Flink timers are registered through the TimerService of a KeyedProcessFunction. When a timer fires, onTimer runs with state scoped to the key that set the timer.[4]

Flink TTL is configured with a StateTtlConfig on any keyed state type, with per-entry TTL for list elements and map entries. The update type (by default OnCreateAndWrite) decides when the TTL is refreshed, and the visibility setting decides whether expired values that have not been cleaned up yet can still be read. Only processing-time TTL is supported.[5] Flink keeps state in a state backend: the heap-based HashMapStateBackend by default, or the EmbeddedRocksDBStateBackend.[10]

transformWithState vs Flink keyed state

Spark transformWithState Flink keyed state with KeyedProcessFunction
Programming model A StatefulProcessor class with init, handleInputRows, handleExpiredTimer, handleInitialState and close[2] A KeyedProcessFunction with processElement and onTimer[4]
Input per call All rows of a key in the micro-batch (one row in Real-time Mode)[2] One record[4]
State types ValueState, ListState, MapState[2] ValueState, ListState, ReducingState, AggregatingState, MapState[5]
Timers Processing-time and event-time, several per key, checkpointed[2] Processing-time and event-time through the TimerService[4]
TTL Per state variable, processing time only[2] Per state descriptor with StateTtlConfig, processing time only, per entry for collections[5]
Storage RocksDB state store, required[2] Heap (HashMapStateBackend, default) or RocksDB[10]
State schema changes State variables can be added or removed; value fields can evolve with Avro encoding[2] Migrated automatically when a job is restored from a savepoint with changed state types, for serializers that support it[11]

What does state cost?

State has to be stored, checkpointed and restored. Databricks advises setting the number of shuffle partitions to one to two times the number of cluster cores for stateful queries, and notes that the partition count is fixed when the checkpoint is created.[3] In open source Spark, spark.sql.shuffle.partitions and the state store provider cannot change between restarts from the same checkpoint.[12] See Streaming checkpoint for what else is fixed.

See also

References

  1. ↑ 1.0 1.1 1.2 Structured Streaming: State Store (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  2. ↑ 2.00 2.01 2.02 2.03 2.04 2.05 2.06 2.07 2.08 2.09 2.10 Structured Streaming: transformWithState (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  3. ↑ 3.0 3.1 What is stateful streaming?. Databricks.Retrieved 2026-11-23.
  4. ↑ Structured Streaming: Arbitrary Stateful Operations (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  5. ↑ SPARK-40925: Fix late record filtering to support chaining of stateful operators. Apache Software Foundation JIRA.Retrieved 2026-11-23.
  6. ↑ SQLConf.scala (Apache Spark v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  7. ↑ Structured Streaming: Unsupported Operations (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  8. ↑ Structured Streaming: Miscellaneous Notes (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.