Home / Databricks on Azure

Databricks on AzureCheat sheetAdvanced

Structured Streaming query progress cheat sheet for Azure Databricks - durationMs, backlog, state and RocksDB metrics

Read StreamingQueryProgress field by field. Includes capture code, SQL for phase timing, backlog, watermark lag and state, and the traps that make healthy streams look broken.

Deepak Bhardwaj7 min read

Applies toAzure Databricks, Databricks Runtime 13.3 LTS and later; some metrics need newer runtimes

A stream is slow and the Spark UI shows only jobs. StreamingQueryProgress tells you which phase is slow, how far behind each source is and whether state is the cause. This sheet maps the fields to decisions and gives SQL to trend them.

Capture progress

Quick look from the notebook that owns the query:

import json
p = query.lastProgress
d = json.loads(p.json) if hasattr(p, "json") else p
print(json.dumps(d, indent=2))

For history, use a listener. Keep callbacks light, because slow listener code can delay queries. This one writes one JSON line to stdout for log shipping:

from pyspark.sql.streaming import StreamingQueryListener

class ProgressLog(StreamingQueryListener):
    def onQueryStarted(self, event):
        print(f"STREAM_STARTED id={event.id} run={event.runId} name={event.name}")

    def onQueryProgress(self, event):
        print("STREAM_PROGRESS " + event.progress.json)

    def onQueryIdle(self, event):
        print(f"STREAM_IDLE id={event.id} run={event.runId}")

    def onQueryTerminated(self, event):
        print(f"STREAM_ENDED id={event.id} error={event.exception}")

spark.streams.addListener(ProgressLog())

onQueryIdle needs a runtime that supports it. Where output appears depends on access mode. On Unity Catalog compute, listeners need DBR 15.1+ (dedicated), or 16.1+ for Scala on standard.

To keep history in Delta for incident analysis, poll recentProgress from the driver:

def save_progress(q, table="prod.ops.stream_progress"):
    rows = []
    for p in q.recentProgress:
        raw = p.json if hasattr(p, "json") else json.dumps(p)
        d = json.loads(raw)
        rows.append((d["id"], d["runId"], d.get("name"), int(d["batchId"]),
                     d["timestamp"], raw))
    if rows:
        (spark.createDataFrame(
            rows, "id string, run_id string, name string, batch_id bigint, ts string, raw string")
         .write.mode("append").saveAsTable(table))

recentProgress is a bounded buffer, so poll before it wraps. Overlapping polls create duplicates, which this view removes:

CREATE OR REPLACE VIEW prod.ops.v_stream_progress AS
SELECT *
FROM prod.ops.stream_progress
QUALIFY row_number() OVER (
  PARTITION BY run_id, batch_id, ts ORDER BY ts) = 1;

Warning

Progress JSON contains source paths, topic names and any observe values. Restrict the table as you would job logs, and don't put customer data in observed metrics.

Identity fields

Field Meaning Use
id Persists across restarts Trend one stream over months
runId New on each start Count restarts
batchId Batch number; can repeat on a retry Don't use as a unique key alone
name queryName, null if unset Always set it

A changed id after a deployment means a new or different checkpoint. Check that before investigating duplicates or a reload.

durationMs: where the time goes

Key Phase If it dominates
latestOffset Find the newest source offset Slow listing, broker or metadata calls
getBatch Prepare the batch from offsets Large offset range or source metadata
queryPlanning Plan the batch Wide schemas, many files, large foreachBatch plans
walCommit Write planned offsets Checkpoint storage latency
addBatch Execute and write Transform, shuffle, state or sink
commitBatch Sink commit, where supported Sink metadata
commitOffsets Write the commit log Checkpoint storage latency
triggerExecution Whole trigger Compare with the trigger interval
SELECT name, date_trunc('HOUR', to_timestamp(ts)) AS hr,
       percentile(raw:durationMs.triggerExecution::BIGINT, 0.95) AS p95_total_ms,
       percentile(raw:durationMs.addBatch::BIGINT, 0.95)         AS p95_add_ms,
       percentile(raw:durationMs.latestOffset::BIGINT, 0.95)     AS p95_offset_ms,
       percentile(raw:durationMs.queryPlanning::BIGINT, 0.95)    AS p95_plan_ms,
       percentile(raw:durationMs.walCommit::BIGINT, 0.95)        AS p95_wal_ms
FROM prod.ops.v_stream_progress
GROUP BY ALL
ORDER BY name, hr;

Some keys are missing for some sources and runtimes. Treat nulls as "not reported", not zero.

Rates and backlog

inputRowsPerSecond above processedRowsPerSecond over many batches means the stream is falling behind. A single batch proves nothing. Prefer source backlog:

Source Metric Note
Delta numBytesOutstanding, numFilesOutstanding Backlog at that batch
Auto Loader numBytesOutstanding, numFilesOutstanding Discovered but unprocessed files
Auto Loader notifications approximateQueueSize Only with cloudFiles.useNotifications
Kafka / Event Hubs endpoint maxOffsetsBehindLatest, avgOffsetsBehindLatest High max with low average: skewed partitions
Kafka / Event Hubs endpoint estimatedTotalBytesBehindLatest Estimate of bytes behind
SELECT name, batch_id, ts,
       s.description,
       s.numInputRows,
       s.metrics['maxOffsetsBehindLatest'] AS max_behind,
       s.metrics['avgOffsetsBehindLatest'] AS avg_behind,
       s.metrics['numBytesOutstanding']    AS bytes_outstanding
FROM prod.ops.v_stream_progress
LATERAL VIEW explode(from_json(raw:sources,
  'array<struct<description:string,numInputRows:bigint,metrics:map<string,string>>>')) x AS s
ORDER BY ts DESC
LIMIT 200;

Tip

Kafka backlog reads differently by runtime. From DBR 17.1, latest offsets are fetched after each batch, so a busy topic shows small non-zero values. On 17.0 and below they are fetched at the start and can read 0. Re-baseline alerts after an upgrade.

Event time and watermark

SELECT name, batch_id, ts,
       raw:eventTime.max::TIMESTAMP       AS max_event,
       raw:eventTime.watermark::TIMESTAMP AS watermark,
       timestampdiff(MINUTE, raw:eventTime.watermark::TIMESTAMP,
                     raw:eventTime.max::TIMESTAMP) AS lag_min
FROM prod.ops.v_stream_progress
WHERE raw:eventTime.watermark IS NOT NULL
ORDER BY ts DESC;
Pattern Meaning
Lag near the configured delay Normal
Watermark flat, input arriving Slow input in a union or join, or late data only
max far in the future Bad device clock; the watermark jumps and drops good data
numRowsDroppedByWatermark rising Late rows discarded; approximate and only for aggregations

State operators

Field Read it as
numRowsTotal Keys or rows in state. Steady growth means no eviction
numRowsUpdated, numRowsRemoved Churn. Removed at zero for hours needs explaining
memoryUsedBytes State store memory
commitTimeMs Time to commit state, usually the first sign of trouble
numShufflePartitions Fixed by the checkpoint
numStateStoreInstances Stream-stream joins use four per partition
customMetrics.numDroppedDuplicateRows Duplicates removed by dedupe

allUpdatesTimeMs and allRemovalsTimeMs aren't reliable, so don't alert on them.

SELECT name, batch_id, ts, o.operatorName, o.numRowsTotal,
       o.numRowsRemoved, o.commitTimeMs,
       round(o.memoryUsedBytes / 1e9, 2) AS state_gb
FROM prod.ops.v_stream_progress
LATERAL VIEW explode(from_json(raw:stateOperators,
  'array<struct<operatorName:string,numRowsTotal:bigint,numRowsRemoved:bigint,commitTimeMs:bigint,memoryUsedBytes:bigint>>')) x AS o
ORDER BY ts DESC
LIMIT 200;

RocksDB metrics

Names vary by version; check your build's output in customMetrics.

Metric High value points to
rocksdbCommitFlushLatency Flushing memtables; consider changelog checkpointing
rocksdbCommitCompactLatency Compaction during commit
rocksdbCommitFileSyncLatencyMs Upload to checkpoint storage
rocksdbWriterStallLatencyMs Writers waiting on compaction or flush
rocksdbReadBlockCacheMissCount vs hits State no longer fits in cache
rocksdbFilesCopied vs rocksdbFilesReused Large rewrites each commit
rocksdbSstFileSize Total on-disk state

Changelog checkpointing is on by default from DBR 17.3 LTS. On older runtimes, set it before starting the query:

spark.conf.set(
  "spark.sql.streaming.stateStore.rocksdb.changelogCheckpointing.enabled", "true")

Queries that use it must stay on DBR 13.3 LTS or later.

Caution

Don't delete checkpoint state to bring these numbers down. You lose aggregates and deduplication history, and may reprocess the source.

Traps that cause false alarms

  • Delta sink numOutputRows is always -1. Use DESCRIBE HISTORY for rows written.
  • No progress doesn't mean no health. Progress is emitted at the end of a batch. A long batch can be silent with the query still running.
  • Idle isn't stalled. With no data, batchId doesn't advance and onQueryIdle fires instead.
  • Multi-batch availableNow runs process backlog quickly, so rates are not comparable with continuous triggers.
  • Delta reservoirId is the table ID from DESCRIBE DETAIL, not the Unity Catalog table ID. A change means the source table was replaced.

Prevent it next time

  • Set queryName on every query and register the listener in shared startup code.
  • Alert on three things: backlog trend, p95 triggerExecution against the interval, and time since the last progress or idle event.
  • Keep 30 days of progress so you can compare with the batch before a deployment.
  • Re-baseline after each runtime upgrade.