Home / Databricks on Azure

Databricks on AzureHow-toAdvanced

Inspecting Structured Streaming state on Azure Databricks with the state reader API

Read a stateful stream's checkpoint with state-metadata and statestore to see what is in state, why it keeps growing, which partitions are skewed and what changed between batches.

Deepak Bhardwaj6 min read

Applies toAzure Databricks, Databricks Runtime 14.3 LTS and later (dedicated access mode); standard access mode on newer runtimes; change feed on 16.4 LTS and later

A stateful stream (aggregation, dropDuplicates, stream-stream join, flatMapGroupsWithState or transformWithState) keeps slowing down, or its state size keeps growing. lastProgress only gives totals. The state reader API reads the checkpoint as a batch DataFrame, so you can see the actual keys and values. Use it to check whether the watermark is evicting rows, which keys are hot, and whether a code change changed the state layout.

Requirements and limits

  • Batch reads only. You cannot stream from the state source.
  • It works on checkpoints of your own Structured Streaming queries. It does not read the state of Lakeflow Declarative Pipelines (DLT), streaming tables or materialized views.
  • Supported runtime and access mode vary. Dedicated access mode works on 14.3 LTS and later. Standard access mode support came later, and the change feed option needs 16.4 LTS or later. Check the "Read Structured Streaming state information" page for your runtime.
  • The reader only reads the checkpoint and does not change it. You still need read access to the checkpoint path, which is usually a volume or an external location.

Tip

Run these reads from a separate cluster, not the cluster running the stream. Reading a large RocksDB state loads its files and uses real memory and CPU.

Step 1: list the stateful operators

cp = "/Volumes/prod/streaming/checkpoints/orders_dedup"

meta = spark.read.format("state-metadata").load(cp)
display(meta)

Or in SQL:

SELECT * FROM read_state_metadata('/Volumes/prod/streaming/checkpoints/orders_dedup');

Columns include operatorId, operatorName, stateStoreName, numPartitions, minBatchId and maxBatchId. What to look for:

Field What it tells you
operatorName Which operator holds state, for example dedupe, stateStoreSave (aggregation) or symmetricHashJoin
numPartitions The shuffle partition count fixed when the checkpoint was created. Changing spark.sql.shuffle.partitions later does not change it
minBatchId/maxBatchId Which batches you can still read. Older versions are cleaned up

If the operator IDs or names differ from what your current code produces, the code change altered the stateful part of the plan. That is the usual reason a restarted stream fails with a state schema error.

Step 2: read the state rows

state = (spark.read.format("statestore")
         .option("operatorId", 0)          # from state-metadata
         .load(cp))

state.printSchema()   # key: struct, value: struct, partition_id: int
print(state.count())

To read the state as of a specific committed batch, which avoids racing the running query, pin the batch:

state_at = (spark.read.format("statestore")
            .option("operatorId", 0)
            .option("batchId", 41250)
            .load(cp))

For stream-stream joins, each side has its own stores. Choose a side with joinSide:

left = (spark.read.format("statestore")
        .option("operatorId", 0)
        .option("joinSide", "left")
        .load(cp))

Operators with more than one store, such as transformWithState with several state variables, need storeName or the operator-specific options. Get the store names from state-metadata.

Step 3: answer the usual questions

Is the watermark actually evicting state?

For a windowed aggregation, the key contains the window. If the oldest windows are far behind the current watermark, eviction is not happening:

from pyspark.sql import functions as F

(state
  .select(F.col("key.window.start").alias("win_start"),
          F.col("key.window.end").alias("win_end"))
  .agg(F.min("win_start").alias("oldest"), F.max("win_end").alias("newest"),
       F.count("*").alias("rows"))
  .show(truncate=False))

Compare oldest with the watermark reported in the query progress:

q = [s for s in spark.streams.active if s.name == "orders_agg"][0]
print(q.lastProgress["eventTime"])      # includes "watermark"
print(q.lastProgress["stateOperators"]) # numRowsTotal, memoryUsedBytes, ...
Finding Cause Fix
Old windows remain and the watermark is far ahead Output mode or operator does not evict, for example complete mode Use append or update with a watermark on the event-time column used in the window
Watermark is stuck in the past One input partition has no new data, or its timestamps are bad (for example 1970-01-01 or far-future values) Filter bad timestamps before withWatermark. Check spark.sql.streaming.multipleWatermarkPolicy
dropDuplicates state grows forever Deduplication without a watermark, or the key does not include the event-time column Use dropDuplicatesWithinWatermark or add the event-time column to the key, with a watermark
Join state grows on one side Join condition has no time-range constraint Add an event-time range condition plus watermarks on both sides

Which partitions are skewed?

(state.groupBy("partition_id").count()
      .orderBy(F.desc("count")).show(10))

If one partition has 10–50 times the median row count, its tasks will be the slow ones in every micro-batch. You cannot repartition existing state. Fixing it means a new key design and a new checkpoint.

Which keys are hot?

(state.select("key.*", "value.*")
      .orderBy(F.desc("count"))     # use a field from your value struct
      .limit(20).show(truncate=False))

Hot keys are often a default value such as customer_id = 'UNKNOWN' or NULL that collects every orphan event. Route those rows away before the stateful operator.

Step 4: see what changed between batches

On runtimes that support it, read the state change feed to see the inserts, updates and deletes per batch:

changes = (spark.read.format("statestore")
           .option("operatorId", 0)
           .option("readChangeFeed", "true")
           .option("changeStartBatchId", 41200)
           .option("changeEndBatchId", 41250)
           .load(cp))

changes.groupBy("batch_id", "change_type").count().orderBy("batch_id").show(100)

If you see many update rows but few delete rows over a long range, state is accumulating and nothing is being evicted. The change feed reads changelog files, so on many runtimes it works only when changelog checkpointing is enabled for RocksDB (spark.sql.streaming.stateStore.rocksdb.changelogCheckpointing.enabled true). Check your runtime's docs.

Step 5: check state before a code change

Before you deploy a change to a stateful query:

  1. Record state-metadata for the current checkpoint.
  2. Run the new code against a copy of the checkpoint on a test cluster with trigger(availableNow=True).
  3. Read state-metadata from the copy and compare operator IDs, names and partition counts.
  4. Read a sample of statestore rows and confirm the key and value schemas are what the new code expects.

If they differ, plan the change as a new checkpoint with a backfill. Do not let it fail in production.

Caution

Never edit or delete files inside a checkpoint's state/ or offsets/ folders to "trim" state. The stream will fail or silently lose or duplicate data. To shrink state, change the query and start from a new checkpoint.

Prevent it next time

  • Alert on stateOperators[].numRowsTotal and memoryUsedBytes from StreamingQueryListener or job metrics, and look at the trend, not only the absolute value.
  • Always use a watermark with stateful operators and check the evicted row counts in query progress.
  • Keep checkpoints on a volume or external location that the on-call group can read, so the state reader is available during an incident.
  • Name your queries (.queryName(...)) so progress and state reads map clearly to jobs.