Symptom
The streaming query is running, not failing, but data is getting later every hour. Typical signs:
- The driver log repeats
Current batch is falling behind. The trigger interval is 60000 milliseconds, but spent 184000 milliseconds. - Kafka consumer lag or the source's offsets-behind metric grows steadily.
processedRowsPerSecondis consistently lower thaninputRowsPerSecond.- After a restart, the first batch runs for hours.
The query will never catch up while processing rate is below arrival rate. The job is to find which phase of the micro-batch is slow and fix that one.
Check 1: read the progress, not the UI
Pull the last few progress events from the running query:
import json
q = [s for s in spark.streams.active if s.name == "orders_stream"][0]
for p in q.recentProgress[-5:]:
print(json.dumps({
"batchId": p["batchId"],
"numInputRows": p["numInputRows"],
"inputRowsPerSecond": p.get("inputRowsPerSecond"),
"processedRowsPerSecond": p.get("processedRowsPerSecond"),
"durationMs": p["durationMs"],
"sources": [{"desc": s["description"],
"metrics": s.get("metrics")} for s in p["sources"]],
}, indent=2))
print(q.status)
In PySpark 3.x recentProgress returns dictionaries; in newer versions it returns progress objects that still support key access. In Scala, use query.recentProgress.map(_.prettyJson).
Then map the largest value in durationMs to a cause:
Largest durationMs field | What it means | Look at |
|---|---|---|
addBatch | Time running the actual Spark job (transform plus sink write) | Spark UI stages for that batch, the sink |
latestOffset / getBatch | Time asking the source what's new | File listing on large directories, Kafka broker latency |
queryPlanning | Planning the batch | Very wide schemas, huge plans, many unions |
walCommit / commitOffsets | Writing the checkpoint | Slow or throttled checkpoint storage |
triggerExecution only, others small | Overhead between phases | State store commits; see the RocksDB note below |
For Kafka sources on recent Spark versions, sources[].metrics includes avgOffsetsBehindLatest and maxOffsetsBehindLatest. Graph those; they show whether you are catching up. Databricks also shows estimatedTotalBytesBehindLatest for some sources. Metric names vary by version and platform, so check your build's output.
Tip
To keep the history after the query restarts, add a
StreamingQueryListener(available in PySpark from 3.4) that writes each progress event to a table or your metrics system.recentProgressonly holds the last few batches in memory.
Check 2: is the batch too big or too small?
Two opposite failure modes look the same from outside.
Batch too big. No rate limit, so after a pause or restart the query pulls the whole backlog into one batch. That batch spills, runs out of memory or takes hours, and nothing commits until it finishes.
Batch too small. A rate limit set long ago is now below the arrival rate. Every batch is fast but the lag still grows, because each batch takes a fixed slice.
Compare numInputRows with your rate limit. If every batch hits the limit exactly and lag grows, the limit is too low. If numInputRows is huge and addBatch is huge, set a limit.
df = (spark.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "broker1:9092,broker2:9092")
.option("subscribe", "orders")
.option("startingOffsets", "latest")
.option("maxOffsetsPerTrigger", 2_000_000) # cap per micro-batch, split across partitions
.option("minPartitions", 96) # more Spark tasks than Kafka partitions
.load())
Per source:
| Source | Rate-limit options |
|---|---|
| Kafka | maxOffsetsPerTrigger; minOffsetsPerTrigger with maxTriggerDelay (Spark 3.2+) to avoid tiny batches |
| Delta table | maxFilesPerTrigger (default 1000), maxBytesPerTrigger |
| File source | maxFilesPerTrigger |
| Auto Loader (Databricks) | cloudFiles.maxFilesPerTrigger, cloudFiles.maxBytesPerTrigger |
Size the limit from what one batch can process inside the trigger interval with headroom: if the cluster processes 50,000 rows/s and the trigger is 60 s, a limit around 2 million rows leaves room for spikes and lets the query catch up when the backlog clears.
Warning
startingOffsetsonly applies when the query starts with a new checkpoint. On an existing checkpoint, the stored offsets win. Changing it tolateston a running pipeline does nothing, and deleting the checkpoint to skip a backlog loses data and can duplicate writes in non-idempotent sinks.
Check 3: source parallelism
By default the Kafka source creates one Spark task per Kafka partition. A topic with 12 partitions read by a 200-core cluster uses 12 cores for the read and any narrow transforms after it.
Fixes, in order of preference:
- Set
minPartitionson the Kafka source so Spark splits large partitions into several offset ranges. repartition(n)after parsing if the heavy work is after the read. This adds a shuffle, so only do it if the stages after the read are the slow part.- Add Kafka partitions. This changes key ordering for producers; plan it as a separate change.
For Delta and file sources, many small files cause slow latestOffset and many tiny tasks. Compact the source table or folder and, on Databricks, use file notification mode for Auto Loader on large directories.
Check 4: the sink and foreachBatch
When addBatch dominates, open the Spark UI, find the jobs for the slow batch ID and see which stage is slow.
Common sink problems:
| Pattern | Problem | Fix |
|---|---|---|
foreachBatch writes to two or more targets | The source DataFrame is recomputed for each write | batch_df.persist() at the start, unpersist() at the end |
foreachBatch with a Delta MERGE | MERGE scans the whole target every batch | Add a partition or clustering predicate to the merge condition, keep target files compacted |
| JDBC sink | One connection per task, row-by-row inserts | Set batchsize, limit numPartitions, or land in a staging table and load in bulk |
.collect() or .toPandas() in foreachBatch | Pulls the batch to the driver | Do the work with DataFrame operations |
| Delta sink with many small files | Slow writes and slow downstream reads | Optimized writes / auto compaction where supported, or scheduled OPTIMIZE |
def write_batch(batch_df, batch_id):
batch_df.persist()
(batch_df.filter("event_type = 'order'")
.write.format("delta").mode("append").saveAsTable("silver.orders"))
(batch_df.filter("event_type = 'refund'")
.write.format("delta").mode("append").saveAsTable("silver.refunds"))
batch_df.unpersist()
(df.writeStream
.foreachBatch(write_batch)
.option("checkpointLocation", "abfss://chk@lake.dfs.core.windows.net/orders_stream")
.trigger(processingTime="60 seconds")
.queryName("orders_stream")
.start())
Check 5: stateful operators and shuffle partitions
For aggregations, dropDuplicates and stream-stream joins, the number of state partitions is fixed by spark.sql.shuffle.partitions at the time the checkpoint was created. Changing the setting later has no effect on that query.
- If the state stage has 200 tasks on a 32-core cluster, each batch runs in several waves. If it has 8 tasks on a 200-core cluster, most cores sit idle.
- To change it you need a new checkpoint, which means a planned restart with state rebuilt or a backfill. Treat it as a migration, not a tuning tweak.
- Large state stores slow down commits. Check
stateOperators[].numRowsTotalandmemoryUsedBytesin the progress output. If state keeps growing, the watermark is not working.
Trigger choice
| Trigger | When it fits |
|---|---|
processingTime="N seconds" | Continuous low-latency pipeline; N should be longer than a normal batch |
availableNow=True (Spark 3.3+) | Scheduled catch-up runs; processes the backlog in several rate-limited batches, then stops |
| Default (no trigger) | Next batch starts as soon as the last finishes; fine if the cluster is dedicated |
availableNow is a good way to clear a large backlog: run it on a bigger cluster with the same checkpoint, let it finish, then restart the normal query. Do not run two queries on the same checkpoint at the same time.
Quick map
| What you see | Likely cause | Fix |
|---|---|---|
| Every batch hits the rate limit, lag grows | Limit too low | Raise maxOffsetsPerTrigger / maxFilesPerTrigger |
| One giant batch after restart | No rate limit | Set a limit before restarting |
| Few tasks in the read stage | Kafka partitions < cores | minPartitions |
latestOffset in seconds or minutes | Directory listing | Compact files, use notification mode |
addBatch slow, sink stage dominates | foreachBatch recompute, MERGE scans | persist(), narrower merge predicate |
| Checkpoint phases slow | Storage throttling | Separate checkpoint storage, check account limits |
Prevent it next time
- Always set a rate limit on production streams, sized from measured throughput.
- Export progress events through a listener and alert on offsets-behind growing for several consecutive batches, not on a single slow batch.
- Load-test with a replayed backlog before go-live, so you know how long catch-up takes after an outage.
- Choose
spark.sql.shuffle.partitionsdeliberately before the first start of any stateful query. - Keep checkpoints on their own storage path and never share them between queries.
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