Zero Labs
Industry News / AI

Part XXI — Streaming State: Watermarks, State Stores, and the 146GB Checkpoint

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Every Structured Streaming query is a stateful program wearing a batch costume. The watermark is the only thing standing between your state store and unbounded growth — and when it is misconfigured, the checkpoint doesn’t save you. It becomes the incident.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVI | Part XVII | Part XVIII | Part XIX | Part XX| Part XXIThe 146GB Checkpoint That Ate the Fraud PipelineThe page came at 2:47 AM, and the symptom made no sense at first: fraud.dedup_orders — a Structured Streaming query whose entire job is deduplicating order events — had fallen 93 minutes behind. Not failed. Not erroring. Just… walking, while 38,000 events per second piled up behind it. The consumer lag graph looked like a ski slope.The query was simple enough to be boring. Kafka in, deduplicate on order_id, Delta Lake out. Someone, at some point, had set the watermark to 7 days — "to be safe," the commit message said, "so we never miss a late retry." The upstream payment service does retry failed webhooks for up to 20 minutes. Seven days of safety margin for a 20-minute retry SLA.Here is what seven days of watermark on a 38k-events-per-second firehose means arithmetically: every unique order_id seen in the last seven days must be kept in state, because a duplicate could theoretically still arrive. That's roughly 1.4 billion live keys. The state store — RocksDB, thankfully, or we'd have died much earlier — had swollen to 146GB across 200 partitions. Each two-minute micro-batch spent 41 seconds just writing state changelog deltas to the checkpoint directory, and that number was climbing every day.Then came the deploy. A routine config change, a routine restart. Restarting a Structured Streaming query means reloading the latest state snapshot and replaying the changelog since that snapshot — and our snapshot-plus-changelog replay took 38 minutes. When the executors finally came back, two of them OOM’d during state restoration, the query restarted again, and the lag went from 93 minutes to “we’ll tell you when it’s over.”Part VIII of this series covered the batch-vs-streaming execution contract — one SQL engine, two very different promises. This is the chapter where the streaming side of that contract sends its bill: in Structured Streaming, state is not a feature of the query. State is the query. Everything else is plumbing.So: where does streaming state actually live, what is supposed to bound it, and what does “exactly-once” really cost when the bound is wrong?The Mechanic Underneath: A Streaming Query Is a Versioned Key-Value Store With a SQL FrontendStrip away the DataFrame API and this is what’s running: for every stateful operator in your query, Spark maintains a versioned key-value store, partitioned the same way as your shuffle partitions, versioned by micro-batch ID. Each micro-batch reads the previous version, applies its updates, and writes a new version. The SQL you wrote — the aggregation, the dedup, the join — is a polite fiction over get, put, and delete on that store.Three components implement it:The StateStoreProvider. The default, HDFSBackedStateStoreProvider, keeps the working set in JVM heap and spills deltas to the checkpoint directory. The alternative, RocksDBStateStoreProvider (via spark.sql.streaming.stateStore.providerClass), keeps state in an off-heap LSM tree on local disk. Same API, radically different ceiling: heap versus disk.The watermark. Defined as max event time observed so far minus allowed lateness. It is the query’s statement about the future — “I do not expect data older than this” — and the engine uses it as a license to evict state it believes can never be needed again.The checkpoint. Offsets, state snapshots, state changelog deltas, and the commit log, all in the checkpoint directory. It is what makes restart possible and exactly-once semantics achievable.The operators that keep state: streaming aggregations, dropDuplicates, stream-stream joins, and flatMapGroupsWithState/mapGroupsWithState. If your query has none of these, congratulations — you have no state problem. Our dedup query had exactly one, and one was enough.Watermarks Don’t Filter Data; They License EvictionThis is the most misunderstood line in the Structured Streaming documentation, so let’s be blunt: a watermark does not filter your data. It authorizes the engine to forget. Data older than the watermark isn’t “processed late” — for stateful operators, it’s dropped silently (or, more precisely, the state that would have matched it is already gone).The watermark only moves forward, and it’s computed as the minimum across partitions — one straggler partition with old event times pins the watermark for the entire query. And critically: without a watermark, stateful operators never evict anything. A dropDuplicates("order_id") with no watermark is an infinite key set with extra steps. Our 7-day watermark was technically an eviction policy — it evicted keys after seven days — but on a 38k/sec firehose, "evict after seven days" is barely distinguishable from "never."The sizing rule is not complicated, which is what makes getting it wrong so embarrassing: the watermark’s allowed lateness should match the upstream lateness SLA, not your anxiety. Our upstream retried for 20 minutes. The correct watermark was 20 minutes (plus a small buffer), which would have kept roughly 46 million keys instead of 1.4 billion. The 7-day setting wasn’t safety; it was a 500x state multiplier purchased with someone else’s disk.Stream-stream joins deserve a special warning here, because they bite differently: a stream-stream join requires watermarks on both sides, and each side’s state is evicted by its own watermark. Leave one side unwatermarked and that side’s state grows forever while the other side stays trim — the asymmetry makes it look like a “mystery” growth problem when it’s really a missing three-line config.RocksDB vs In-Memory: Where the 146GB Actually LivesHad we been on the default HDFSBackedStateStoreProvider, this incident would have been an OOM at 3 AM instead of a slowdown — the entire 146GB working set would have needed JVM heap, and no executor heap is 146GB. RocksDB moved the ceiling from heap to local disk, which is why the query degraded gracefully instead of dying. Give the LSM tree its due: it bought us months.But “graceful degradation” still degrades. Here’s where the 146GB bit us, component by component:Checkpoint write amplification. Every micro-batch writes changelog deltas for every changed key to the checkpoint directory, plus periodic full snapshots. At 1.4B keys with steady churn, our 2-minute micro-batches spent 41 seconds on state I/O alone — over a third of the batch interval burned before any business logic ran.Restart replay. A restart loads the latest snapshot and replays every changelog delta since it. Thirty-eight minutes of replay before the query processed a single new event — during which lag kept accumulating.Compaction debt. RocksDB’s LSM tree needs periodic compaction, and spark.sql.streaming.stateStore.rocksdb.compactOnCommit exists because without it, read amplification during state lookups grows with every uncompacted level. We had it at the default, on executors whose local disks were already 80% full of state.The state store is not a black box you can ignore once you’ve picked RocksDB. It’s a database you’re now operating — with its own storage engine, its own compaction, and its own failure modes. The fraud query’s state directory had become the largest “database” in our infrastructure, and nobody was monitoring it as one.On restart, the arrow runs backward: the query reloads the checkpoint, replays deltas onto the state store, and only then resumes. That backward arrow is the 38 minutes.Exactly-Once Is an End-to-End Property, and the State Store Sends the BillLet’s settle what “exactly-once” actually means in Structured Streaming, because the phrase gets thrown around like a guarantee and it’s really a contract with four signatories:A replayable source (Kafka offsets can be re-read; a socket stream cannot).Deterministic transformations (your business logic, Spark’s responsibility once you behave).An idempotent sink (writing to Delta with foreachBatch + MERGE on the batch ID, so a retried batch doesn't double-write).A durable checkpoint (offsets + state + commit log, so a restart resumes from a consistent point).Spark delivers 2 and the machinery for 4. You supply 1 and 3. Miss any one and you have at-least-once with extra steps — which is exactly what most “exactly-once” pipelines quietly are.And here is the cost nobody puts in the design doc: exactly-once is purchased with write amplification and restart latency, both proportional to state size. The changelog deltas, the snapshots, the 38-minute replay — that’s the premium on the exactly-once insurance policy, and it’s denominated in state bytes. Our 7-day watermark didn’t just waste disk; it multiplied the cost of every guarantee the query made. Shrink the state and every downstream cost — checkpoint I/O, restart time, compaction debt — shrinks with it. There is no cheaper exactly-once optimization than needing less state.One more contractual fine print: the checkpoint directory is part of the query’s semantics. Change the state schema — the key columns, the aggregation, the watermark column — and you cannot resume from the old checkpoint; you need a new checkpoint location, which means reprocessing from the source’s earliest retained offset. We learned to treat checkpoint paths as immutable infrastructure, versioned alongside the query code.The Fix, and What It CostThe naive version is the one that paged us. The optimized version starts from the upstream SLA and treats the state store as the database it is:# Naive: "be safe" with a 7-day watermark on the default in-memory state store.# (events# .withWatermark("event_ts", "7 days") # 500x more state than the 20-min retry SLA needs# .dropDuplicates("order_id")) # default HDFSBackedStateStoreProvider: heap is the ceiling# Optimized: watermark sized to the upstream retry SLA, state moved off-heap.spark.conf.set( "spark.sql.streaming.stateStore.providerClass", "org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider",) # off-heap LSM: the ceiling moves from executor heap to local diskspark.conf.set( "spark.sql.streaming.stateStore.rocksdb.compactOnCommit", "true") # pay compaction incrementally instead of as read-amplification debtdeduped = ( events .withWatermark("event_ts", "20 minutes") # upstream retries for 20 min; anything later is dropped BY DESIGN, not by accident .dropDuplicates("order_id"))Two operational companions, both non-optional:State parallelism matched to key cardinality. We rebalanced to 400 state partitions so no single RocksDB instance held a disproportionate key range — Part VII’s skew playbook applies to state stores too, because a state store is just a partitioned key space.State monitoring as a first-class metric. We added a StreamingQueryListener scraping stateOperators metrics from each progress event — numRowsTotal, memoryUsedBytes — into our dashboards with an alert at 2x the post-fix baseline. The state store is now the largest database we operate; it gets database-grade observability.The quantified results, two weeks later:State size: 146GB → 11GB. 1.4B live keys → ~46M, matching the 20-minute watermark window.Processing lag: 93 minutes → 35 seconds at the same 38k events/sec input.Checkpoint write per micro-batch: 41s → 3s. State I/O stopped being the bottleneck.Restart time: 38 minutes → 5 minutes. The backward arrow got short.The Catch: A Watermark Is a Heuristic, and Heuristics Drop DataThe honest counterweight, because every number above came with a trade:Shrinking the watermark changes dedup semantics. Going from 7 days to 20 minutes means a duplicate arriving 21 minutes late is now processed as a new order. That is a business decision wearing an engineering costume — we got written sign-off from the fraud team before deploying it, and you should too.Late data dies silently. There is no dead-letter queue, no warning, no metric that says “I dropped 12,000 late events this hour” unless you build one. If late data matters to you, add a side-output or a counter on the watermark gap before you tighten anything.State schema changes need a new checkpoint. New key, new aggregation, new watermark column — the old checkpoint is unreadable to the new query plan. Version your checkpoint paths with your query code and plan the reprocessing window.RocksDB is not magic disk. It needs fast local SSDs, headroom for compaction (we keep 40% free on state volumes now), and memory budgets of its own (spark.sql.streaming.stateStore.rocksdb.*). On spinning disks or cramped volumes, it compacts forever and your "fix" becomes a new incident.Exactly-once without an idempotent sink is fiction. If your sink can’t tolerate a retried batch, no watermark tuning in the world gives you exactly-once. The guarantee is end-to-end or it isn’t.TakeawaysEvery stateful operator is a key-value store: aggregations, dedup, stream-stream joins, and flatMapGroupsWithState all persist versioned state per partition. If you can't name your query's stateful operators, you can't reason about its failure modes.No watermark, no eviction: state without a watermark grows until something breaks — usually the checkpoint, the restart, or the heap, in that order.Size the watermark to the SLA, not your anxiety: allowed lateness should mirror the upstream lateness contract. Every extra hour is a state multiplier on your highest-cardinality key space.RocksDB moves the ceiling from heap to disk: the default in-memory provider makes executor heap your state limit; RocksDB trades that for local-disk capacity and compaction ops. Pick deliberately.The checkpoint is part of the query’s contract: offsets, state snapshots, and the commit log are load-bearing. Version checkpoint paths with your code and never hand-edit them.Exactly-once is end-to-end and priced in state bytes: replayable source, deterministic logic, idempotent sink, durable checkpoint — and every byte of state multiplies the write amplification and restart cost of all four.Monitor state like production data: numRowsTotal and memoryUsedBytes per state operator, alerted at 2x baseline. The state store is a database you're operating whether you admit it or not.In streaming, state is the query. Everything else is just the plumbing that feeds it.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XXI — Streaming State: Watermarks, State Stores, and the 146GB Checkpoint was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.