cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

Structured Streaming job becomes progressively slower

angelinak
New Contributor

What could cause a Structured Streaming job to become slower after running continuously for several days?

The pipeline performs deduplication and aggregations, and the incoming data volume remains relatively consistent.

Could this be related to the growing state store?

How can we monitor state store growth and determine whether the configured watermark duration is appropriate?

3 ACCEPTED SOLUTIONS

Accepted Solutions

ThomazNeto
Databricks Partner

Hi Angelina,

Yes, with deduplication in the pipeline, a growing state store is the first thing I'd check. The usual cause is calling dropDuplicates without the watermarked event-time column in the keys. The Databricks docs say that in that case the operator doesn't evict state at all, so it grows with every new key. Over time, that slows the query down and can end in out-of-memory errors. Steady input volume doesn't help because every new key still adds to the state.

Depending on how your duplicates show up, the docs give two ways to bound it:

duplicates are exact copies (e.g. retried writes): include event time in the keys

df.withWatermark("event_time", "30 minutes").dropDuplicates(["id", "event_time"])

duplicates arrive within some delay of each other (DBR 13.3 LTS and above)

df.withWatermark("event_time", "30 minutes").dropDuplicatesWithinWatermark(["id"])

If you really need every duplicate removed and the number of keys has no upper limit, the docs suggest using the target table as the source of truth instead, with MERGE in foreachBatch or AUTO CDC in a pipeline, rather than keeping all keys in state. The aggregations need a watermark too. Without one, their state also grows without limit.

To see what's going on, look at the stateOperators section of the streaming query progress (Spark UI streaming tab, lastProgress, or a StreamingQueryListener):

  • numRowsTotal and memoryUsedBytes should level off after a while. If they keep climbing day after day, state isn't being evicted.
  • numRowsRemoved should go above zero once the watermark starts moving. If it stays at zero, the watermark isn't cleaning anything up.
  • numRowsDroppedByWatermark counts rows that arrived too late. If it keeps going up, the watermark is shorter than how late your data actually arrives.
  • customMetrics.numDroppedDuplicateRows shows how many duplicates were actually removed.

You can also read the state itself from the checkpoint with the state reader (state-metadata and statestore formats) to see which operator holds the most rows. The requirements depend on the runtime and compute access mode.

For picking the watermark, it's a trade-off between latency and how much late data you tolerate. For dedup specifically, the docs say it has to be longer than the maximum time difference between duplicate events if you want to guarantee that all duplicates within that expected delay are removed. A practical way to land on a number is to start from how late your data really arrives and adjust using numRowsDroppedByWatermark and the state size.

One last thing, on DBR 17.3 LTS and above, RocksDB is already the default state store, with changelog checkpointing on. On older runtimes it's worth turning on if your state is large.

Deduplication

Watermarks 

Monitoring streaming queries

State reader

RocksDB state store 

Thomaz A. Rossito Neto
Principal Data Architect & AI Strategy — CI&T
thomazn@ciandt.com
linkedin.com/in/thomaz-antonio-rossito-neto | Databricks Solutions Architect Champion

View solution in original post

SumeshKashyap
Honored Contributor

Hi @angelinak 

Adding to Thomaz's answer, which covers the state side well: before tuning state, confirm state is actually the culprit. Each batch's progress has a durationMs breakdown, and whichever phase grows over the days tells you where to look.

for p in query.recentProgress:

    print(p["batchId"], p["durationMs"], [s["numRowsTotal"] for s in p.get("stateOperators", [])])

How to read it:

- addBatch growing while numRowsTotal grows: it's state. Apply Thomaz's watermark fixes.

- addBatch growing while state is flat: it's the sink. The most common case is a MERGE in foreachBatch against a target that keeps getting bigger. Every batch scans more of the table unless the ON condition can prune, so cluster the target on the merge key (CLUSTER BY customer_id) or add a date predicate to the ON clause. Small files from frequent micro-batches make it worse, so enable optimized writes and auto compaction on the target.

- latestOffset / getBatch growing: it's the source. A plain file source (format("json").load(path)) re-lists an ever-growing directory each batch. Switch to Auto Loader, which tracks files incrementally, or file notification mode for very large directories.

- queryPlanning or triggerExecution growing with everything else flat: usually driver pressure, for example caching a DataFrame in foreachBatch without unpersisting it. Watch driver memory and GC in the cluster metrics.

If the job doesn't need sub-minute latency, running it as a scheduled job with trigger(availableNow=True) also sidesteps most long-running drift, since each run starts with a fresh driver.

Docs: https://docs.databricks.com/aws/en/structured-streaming/stream-monitoring 

View solution in original post

tajamulkhan
Esteemed Contributor
Hi Angelina
 
Yes, a growing state store is one of the first things I would investigate, especially when the pipeline performs stateful operations such as deduplication and aggregations.

1. Monitor state store metrics

progress = query.lastProgress

if progress:
    for state in progress["stateOperators"]:
        print({
            "total_rows": state["numRowsTotal"],
            "memory_bytes": state["memoryUsedBytes"],
            "removed_rows": state["numRowsRemoved"],
            "watermark": progress.get("eventTime", {})
        })
 

If numRowsTotal and memoryUsedBytes continuously increase while incoming data volume remains stable, it could indicate that old state is not being removed effectively.

Also, monitor micro-batch duration, state commit time and processing throughput.

2. Review watermark configuration

For example, if duplicate events normally arrive within 30 minutes but the watermark is configured for 24 hours, the pipeline may retain unnecessary state.

On supported Databricks Runtime versions, consider:

df = (
    source_df
    .withWatermark("event_time", "1 hour")
    .dropDuplicatesWithinWatermark(["event_id"])
)
 

Choose the watermark based on actual event arrival delays and business requirements. A shorter watermark reduces state retention but may cause late records to be dropped.

3. Check whether the watermark is actually advancing

Monitor eventTime.watermark and numRowsDroppedByWatermark across multiple micro-batches.

A watermark alone does not guarantee state cleanup. For aggregations, ensure the operation uses an appropriate event-time window and output mode.

4. Consider RocksDB state store

For large stateful workloads, RocksDB can reduce JVM memory pressure. Also, consider enabling changelog checkpointing on supported runtime versions to reduce checkpointing overhead.

My recommendation is to first identify which stateful operator is accumulating state, then optimize the watermark and aggregation logic before increasing compute capacity. Test any changes to stateful logic for checkpoint compatibility before deploying them.

Official references:

  • Watermark configuration

  • Streaming deduplication

  • RocksDB state store and monitoring

  • Structured Streaming checkpoints

View solution in original post

4 REPLIES 4

ThomazNeto
Databricks Partner

Hi Angelina,

Yes, with deduplication in the pipeline, a growing state store is the first thing I'd check. The usual cause is calling dropDuplicates without the watermarked event-time column in the keys. The Databricks docs say that in that case the operator doesn't evict state at all, so it grows with every new key. Over time, that slows the query down and can end in out-of-memory errors. Steady input volume doesn't help because every new key still adds to the state.

Depending on how your duplicates show up, the docs give two ways to bound it:

duplicates are exact copies (e.g. retried writes): include event time in the keys

df.withWatermark("event_time", "30 minutes").dropDuplicates(["id", "event_time"])

duplicates arrive within some delay of each other (DBR 13.3 LTS and above)

df.withWatermark("event_time", "30 minutes").dropDuplicatesWithinWatermark(["id"])

If you really need every duplicate removed and the number of keys has no upper limit, the docs suggest using the target table as the source of truth instead, with MERGE in foreachBatch or AUTO CDC in a pipeline, rather than keeping all keys in state. The aggregations need a watermark too. Without one, their state also grows without limit.

To see what's going on, look at the stateOperators section of the streaming query progress (Spark UI streaming tab, lastProgress, or a StreamingQueryListener):

  • numRowsTotal and memoryUsedBytes should level off after a while. If they keep climbing day after day, state isn't being evicted.
  • numRowsRemoved should go above zero once the watermark starts moving. If it stays at zero, the watermark isn't cleaning anything up.
  • numRowsDroppedByWatermark counts rows that arrived too late. If it keeps going up, the watermark is shorter than how late your data actually arrives.
  • customMetrics.numDroppedDuplicateRows shows how many duplicates were actually removed.

You can also read the state itself from the checkpoint with the state reader (state-metadata and statestore formats) to see which operator holds the most rows. The requirements depend on the runtime and compute access mode.

For picking the watermark, it's a trade-off between latency and how much late data you tolerate. For dedup specifically, the docs say it has to be longer than the maximum time difference between duplicate events if you want to guarantee that all duplicates within that expected delay are removed. A practical way to land on a number is to start from how late your data really arrives and adjust using numRowsDroppedByWatermark and the state size.

One last thing, on DBR 17.3 LTS and above, RocksDB is already the default state store, with changelog checkpointing on. On older runtimes it's worth turning on if your state is large.

Deduplication

Watermarks 

Monitoring streaming queries

State reader

RocksDB state store 

Thomaz A. Rossito Neto
Principal Data Architect & AI Strategy — CI&T
thomazn@ciandt.com
linkedin.com/in/thomaz-antonio-rossito-neto | Databricks Solutions Architect Champion

SumeshKashyap
Honored Contributor

Hi @angelinak 

Adding to Thomaz's answer, which covers the state side well: before tuning state, confirm state is actually the culprit. Each batch's progress has a durationMs breakdown, and whichever phase grows over the days tells you where to look.

for p in query.recentProgress:

    print(p["batchId"], p["durationMs"], [s["numRowsTotal"] for s in p.get("stateOperators", [])])

How to read it:

- addBatch growing while numRowsTotal grows: it's state. Apply Thomaz's watermark fixes.

- addBatch growing while state is flat: it's the sink. The most common case is a MERGE in foreachBatch against a target that keeps getting bigger. Every batch scans more of the table unless the ON condition can prune, so cluster the target on the merge key (CLUSTER BY customer_id) or add a date predicate to the ON clause. Small files from frequent micro-batches make it worse, so enable optimized writes and auto compaction on the target.

- latestOffset / getBatch growing: it's the source. A plain file source (format("json").load(path)) re-lists an ever-growing directory each batch. Switch to Auto Loader, which tracks files incrementally, or file notification mode for very large directories.

- queryPlanning or triggerExecution growing with everything else flat: usually driver pressure, for example caching a DataFrame in foreachBatch without unpersisting it. Watch driver memory and GC in the cluster metrics.

If the job doesn't need sub-minute latency, running it as a scheduled job with trigger(availableNow=True) also sidesteps most long-running drift, since each run starts with a fresh driver.

Docs: https://docs.databricks.com/aws/en/structured-streaming/stream-monitoring 

tajamulkhan
Esteemed Contributor
Hi Angelina
 
Yes, a growing state store is one of the first things I would investigate, especially when the pipeline performs stateful operations such as deduplication and aggregations.

1. Monitor state store metrics

progress = query.lastProgress

if progress:
    for state in progress["stateOperators"]:
        print({
            "total_rows": state["numRowsTotal"],
            "memory_bytes": state["memoryUsedBytes"],
            "removed_rows": state["numRowsRemoved"],
            "watermark": progress.get("eventTime", {})
        })
 

If numRowsTotal and memoryUsedBytes continuously increase while incoming data volume remains stable, it could indicate that old state is not being removed effectively.

Also, monitor micro-batch duration, state commit time and processing throughput.

2. Review watermark configuration

For example, if duplicate events normally arrive within 30 minutes but the watermark is configured for 24 hours, the pipeline may retain unnecessary state.

On supported Databricks Runtime versions, consider:

df = (
    source_df
    .withWatermark("event_time", "1 hour")
    .dropDuplicatesWithinWatermark(["event_id"])
)
 

Choose the watermark based on actual event arrival delays and business requirements. A shorter watermark reduces state retention but may cause late records to be dropped.

3. Check whether the watermark is actually advancing

Monitor eventTime.watermark and numRowsDroppedByWatermark across multiple micro-batches.

A watermark alone does not guarantee state cleanup. For aggregations, ensure the operation uses an appropriate event-time window and output mode.

4. Consider RocksDB state store

For large stateful workloads, RocksDB can reduce JVM memory pressure. Also, consider enabling changelog checkpointing on supported runtime versions to reduce checkpointing overhead.

My recommendation is to first identify which stateful operator is accumulating state, then optimize the watermark and aggregation logic before increasing compute capacity. Test any changes to stateful logic for checkpoint compatibility before deploying them.

Official references:

  • Watermark configuration

  • Streaming deduplication

  • RocksDB state store and monitoring

  • Structured Streaming checkpoints

balajij8
Esteemed Contributor III

The job slows down because deduplication and aggregation are stateful operations as every key you dedupe or group by gets parked in the state store and it stays there until the watermark decides it's safe to forget it. The watermark itself is the newest event time it has seen, minus the configured delay. The data volume may be steady, but if the watermark delay is much bigger than how late the data actually arrives, keys sit in state for far longer than they need to. If you are deduplicating on something near unique (UUIDs), new keys arrive faster than the watermark can clean up old ones and state keeps growing. As the state store becomes very big, every micro batch gets more expensive - more lookups, bigger SST files, more disk reads that miss cache, longer flush and compaction times and more files written to the checkpoint folder each batch. Those costs scale with state size, not input size which is why the job keeps getting slower even though the data coming in has not changed. On top of that, state store files can pile up on the checkpoint path even when the watermark is working correctly adding drag over time.

You can follow below

Use RocksDB state store if you haven't already as its good for stateful jobs that hold a lot of state and it can handle hundreds of millions of keys where the default store stalls. Next, look at the query's progress data (in query.lastProgress, the Structured Streaming UI or a listener) and watch numRowsTotal under stateOperators - in a healthy stream it flattens out - if it keeps climbing while numRowsRemoved stays low, the watermark is too loose. Then right size the watermark - measure how late your records actually arrive, check numRowsDroppedByWatermark (near zero means you have room to shrink the delay) and set the delay to the observed worst case lateness plus a small buffer. If you are unioning or joining multiple streams, note that the global watermark crawls at the pace of your slowest source by default as one lagging stream stalls eviction for everything, so fix that source or set the multiple watermark policy to max. If state still grows after all that, the problem is the keys - use dropDuplicatesWithinWatermark for pure dedup (it holds each key only for the watermark duration) or transformWithState with per-key TTLs or for aggregations add a time bucket to the group-by so old buckets drop off naturally. Lastly, clean up stale state store files at the checkpoint location and watch batch durations over the next few days to confirm they recover.