You need per-key logic that built-in operators can't express: "alert when a device goes quiet for 15 minutes", sessions with custom end rules, or a state machine per order. transformWithState does it, but most production problems come from four early choices: state type, expiry method, state encoding and key design. This post makes those choices first, then builds the operator.
If dropDuplicatesWithinWatermark, a windowed aggregation or a stream-stream join does the job, use that instead.
Decide before the first run
| Decision | Choose | Why it is hard to change |
|---|---|---|
| Grouping key | The narrowest key that holds all related events | State is stored by key; a new key means new state |
| Shuffle partitions | Size for peak state and throughput | Fixed in the checkpoint when the query starts |
| Encoding | avro if the state schema may ever change | Set it before the first batch |
| Time mode | ProcessingTime or EventTime | Decides whether you get TTL or watermark timers |
| Row or pandas API | Row API unless you need pandas logic | Real-time mode doesn't support transformWithStateInPandas |
Set the configuration in code, next to the query:
spark.conf.set("spark.sql.streaming.stateStore.encodingFormat", "avro")
spark.conf.set("spark.sql.shuffle.partitions", "64")
RocksDB is the default provider from DBR 17.3 LTS. On earlier runtimes, set it as well:
spark.conf.set(
"spark.sql.streaming.stateStore.providerClass",
"com.databricks.sql.streaming.state.RocksDBStateStoreProvider")
Choose the state type
- ValueState: one small record per key. Every update rewrites the whole value.
- ListState: append-mostly buffers.
appendValueavoids rewriting the list. - MapState: many sub-keys under one grouping key. It reads and writes one entry at a time.
A common mistake is a ValueState holding a large array or map. Each event then deserializes and rewrites everything, and cost grows with the key's history. Use ListState or MapState.
TTL or timers
| Need | Use |
|---|---|
| Forget idle state without output | TTL on the state variable |
| Emit a row when something expires | Timer |
| Expiry driven by event time | EventTime timers; TTL isn't available in this mode |
| Expiry per sub-key | MapState with TTL, which applies per map key |
TTL evicts silently and doesn't call handleExpiredTimer. It restarts when a value is updated. For ListState, only put resets TTL for the whole list.
Warning
With no TTL and no timer that clears it, state lives forever. Built-in watermark eviction doesn't clean up custom state for you.
Build the operator
This processor emits a row when a device has been silent for 15 minutes. It stores the pending timer so that each batch replaces the old timer instead of adding one.
from typing import Iterator
from pyspark.sql import Row
from pyspark.sql.streaming import StatefulProcessor, StatefulProcessorHandle
from pyspark.sql.types import (
StructType, StructField, LongType, StringType)
IDLE_MS = 15 * 60 * 1000
SAFETY_TTL_MS = 7 * 24 * 60 * 60 * 1000
state_schema = StructType([
StructField("events", LongType()),
StructField("timer_ms", LongType()),
])
output_schema = StructType([
StructField("device_id", StringType()),
StructField("status", StringType()),
StructField("events", LongType()),
])
class IdleDevice(StatefulProcessor):
def init(self, handle: StatefulProcessorHandle) -> None:
self.handle = handle
self.st = handle.getValueState(
"device_state", state_schema, ttlDurationMs=SAFETY_TTL_MS)
def handleInputRows(self, key, rows, timerValues) -> Iterator[Row]:
n = sum(1 for _ in rows)
events, old_timer = (0, None)
if self.st.exists():
events, old_timer = self.st.get()
if old_timer is not None:
self.handle.deleteTimer(old_timer)
fire_at = timerValues.getCurrentProcessingTimeInMs() + IDLE_MS
self.handle.registerTimer(fire_at)
self.st.update((events + n, fire_at))
return iter([])
def handleExpiredTimer(self, key, timerValues, expiredTimerInfo) -> Iterator[Row]:
if self.st.exists():
events, _ = self.st.get()
self.st.clear()
yield Row(device_id=key[0], status="IDLE", events=events)
def close(self) -> None:
pass
Start the query with a fixed name and checkpoint:
result = (events
.groupBy("device_id")
.transformWithState(
statefulProcessor=IdleDevice(),
outputStructType=output_schema,
outputMode="Append",
timeMode="ProcessingTime"))
(result.writeStream
.queryName("idle_device")
.outputMode("append")
.option("checkpointLocation", "/Volumes/prod/ops/checkpoints/idle_device_v1")
.trigger(processingTime="30 seconds")
.toTable("prod.ops.device_status"))
Points that bite later:
- Register timers in
handleInputRowsorhandleExpiredTimer, never ininit. - Read time from
timerValues. The system clock differs across executors and breaks replays. - Timers are unique per key and timestamp. Registering a new time doesn't cancel the old one, so skipping
deleteTimergives one timer per batch per active key. - The safety TTL must be longer than the timer, or the state can vanish before the timer reads it.
- Processing-time timers are checked when a batch runs, so precision is limited by the trigger interval.
Migrate existing state
To move from another stateful operator, read the old state and pass it as initialState, grouped by the same key:
seed = (spark.read.table("prod.ops.device_seed") # device_id, events
.groupBy("device_id"))
# add initialState=seed to transformWithState(...)
# and implement:
# def handleInitialState(self, key, initialState, timerValues) -> None:
# fire_at = timerValues.getCurrentProcessingTimeInMs() + IDLE_MS
# self.handle.registerTimer(fire_at)
# self.st.update((initialState["events"], fire_at))
Initial state is accepted only on the first start of a new checkpoint. Register timers for seeded keys too. A key that never receives another event has no other chance to expire. A uniform timeout fires every seeded key in the same batch, so add a jitter if the seed is large.
Change the state schema safely
With Avro encoding, evolution happens when you deploy new code and restart.
| Change | Result |
|---|---|
| Add a field | Old rows read None; handle it in code |
| Remove or reorder fields | Allowed; matching is by name |
Widen int to long or double, and similar | Allowed |
| Rename a field | Treated as remove plus add. Values are lost with no error |
| Narrow a type | Not supported |
| Change map key names or types | Not supported |
| Add a state variable | Allowed, doesn't need Avro |
| Remove a state variable | Allowed; call deleteIfExists("name") in init |
Values are tuples in field order in Python, so adding a field breaks code that unpacks a fixed number of values. Update the unpacking in the same deployment.
Defaults are 16 evolutions per state variable and 128 per query. Group several field changes into one restart, because they count as one evolution.
Caution
To rename a field without losing data, add the new field, write both, and backfill the new one when each key is next updated. Remove the old field only once idle keys have expired or been migrated.
Test before deployment
- Copy a production checkpoint with the stream stopped, or use a test stream's checkpoint.
- Run the new code against the copy and a test sink with
trigger(availableNow=True). - Read the result with
spark.read.format("state-metadata").load(path)and compare the variables and partition counts. - Check the output for keys whose old values should appear.
Watch these in production
query.lastProgress reports the operator in stateOperators:
p = query.lastProgress
for op in p["stateOperators"]:
cm = op.get("customMetrics", {})
print(op["operatorName"], op["numRowsTotal"], op["commitTimeMs"],
{k: cm.get(k) for k in ("numRegisteredTimers", "numExpiredTimers",
"timerProcessingTimeMs",
"numValuesRemovedDueToTTLExpiry")})
| Symptom | Likely cause | Fix |
|---|---|---|
| Registered timers grow faster than active keys | Old timers not deleted | Store and delete the pending timer |
timerProcessingTimeMs spikes hourly | Timers aligned to one timestamp | Add jitter |
| State grows, TTL removals are zero | TTL missing or refreshed constantly | Check each variable |
| One slow task | Hot key | Split the key or filter default values |
Metric names vary by version; check your build's output.
Prevent it next time
- Turn on Avro encoding and version the checkpoint path from day one.
- Require an expiry decision for every state variable in code review.
- Keep state schemas in one module and block renames in review.
- Load-test with the production number of keys, not just the event rate.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get