Structured Streaming internals

Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.

SwiftKart's click counter on Databricks ran well for three weeks. Then its micro-batches crept from 20 seconds to 9 minutes, and executors began dying with java.lang.OutOfMemoryError: Java heap space. Nobody had changed the code. At 22:00 on Thursday the job died for the last time. At 04:00 its checkpoint folder was deleted to "reset" it, and it came back fast. At 9:00 Tess reports six hours of clicks missing. Nora says: "Both problems live in that one folder. Open it."

You'll learn to

  • Trace one micro-batch from the offsets file to the commit file
  • Say exactly which batch a restart runs again, and why
  • Make a sink skip a batch it has already written
  • Keep state bounded, and recover from a lost checkpoint

Learn

A stream is a loop of small batches

A Structured Streaming query is a loop, run by Spark's driver (the program that plans the work, Lesson 12.1). Each turn of the loop is one micro-batch:

  1. Ask Kafka how far the topic goes now, and pick the range of offsets to read. maxOffsetsPerTrigger can cap it.
  2. Write the plan down: a small file, offsets/N, with the range and this batch's watermark. Nothing has been processed yet.
  3. Run the batch as an ordinary Spark job. Tasks load the state (the running counts of Lesson 15.4), update it and save a new version.
  4. Hand the result to the sink, with the batch number N.
  5. Write a second small file, commits/N: batch N is done.

The two small files are the whole trick. Write the plan first. Tick it off last.

One micro-batch, from offsets to commit

A Kafka topic, a checkpoint folder and a Delta sink during batch 41: the offset range is planned, offsets/41 is written, state version 42 is saved, the sink receives batch 41, and commits/41 is written last.

  1. Plan the range. Batch 40 stopped at offset 1,840,100. The topic now ends at 1,840,250. Batch 41 will read those 150 clicks.

  2. Write offsets/41. The range and the batch's watermark, 10:21, go into the checkpoint before a single click is processed. From now on, "batch 41" means exactly this range.

  3. Run the batch. Tasks load state version 41 (the counts after batch 40), add the 150 clicks, drop rows that are too late, and save version 42.

  4. Write to the sink. The windows that closed go to the Delta table, labelled as batch 41. A crash right now is the dangerous one: the output is out, and nothing says so yet.

  5. Write commits/41. The batch is ticked off, and the file carries the watermark for batch 42. Until this file exists, a restart runs batch 41 again with the same range.

Watch the middle box. Its six rows stay in place; each step turns one of them from "not written" to written.

The folder that remembers everything

Those files live in one folder, the checkpoint (checkpointLocation). It is the query's whole memory:

  • offsets/: one file per batch, the plan. Written first.
  • commits/: one file per finished batch. Written last.
  • state/: the running counts, saved as a new version after every batch.
  • metadata: the query's id, the same across restarts.

Now the rule that makes a restart exact. If the newest offsets file has no matching commits file, that batch started and never finished. Spark runs it again, with the same range, the same watermark, and the state as it was before.

The picture shows the folder after a crash in batch 41.

The checkpoint after a crash in batch 41

A folder tree of a checkpoint: the metadata file, offsets files 40 and 41, only commit 40, state files for operator 0 across 200 shuffle partitions, and a sources folder.

Compare offsets/ with commits/: 41 is planned and not ticked off, so batch 41 runs again. Under state/ there is one folder per stateful operator, then one per shuffle partition.

Run a query micro-batch by micro-batch

import ministream as ms

broker = ms.Broker()
ms.load_events(broker, 'clicks', partitions=1, path='landing/events/*.jsonl')
cp, sink = ms.Checkpoint(), ms.Sink()
query = ms.WindowedCount(broker, 'clicks', cp, sink, window_minutes=60,
                         delay_minutes=120, max_offsets_per_trigger=50)
for p in query.run():          # like trigger(availableNow=True)
    print(p['batchId'], p['numInputRows'], p['watermark'], 'state', p['numRowsTotal'],
          'dropped', p['numRowsDroppedByWatermark'], 'emitted', len(p['output']))
print(len(cp.files()), 'checkpoint files')
print('offsets/2:', cp.offsets[2])
print('commits/2:', cp.commits[2])

Each line is one micro-batch: its number, rows read, watermark, rows in state, rows dropped as too late, windows written. The limit of 50 offsets shapes the batches. Batch 4 reads no rows: it is the no-data batch that closes the windows the last watermark passed. The last two lines are the plan and the tick for batch 2.

A crash between the write and the commit

You have met this gap before, in Lesson 15.3: a job writes its output, and dies before it records that it did.

Here the gap is between step 4 and step 5. The sink has batch N. The checkpoint has offsets/N and no commits/N. On restart Spark follows its rule and runs batch N again: same offsets, same watermark, same starting state, so the same output.

That is at-least-once, done very precisely. The second attempt is an exact copy of the first. So the sink has an easy job: it only has to recognise a batch number it has already written.

A windowed count crashes after writing batch 3 to the sink but before its commit; on restart the checkpoint shows offsets for batch 3 with no commit, the batch is rerun with the same offsets, and an idempotent sink skips the second write while a plain append duplicates it.

Step to the crash: offsets/3 has no commit. Step on to the rerun, then switch the sink to a plain append and watch the 10:00 window appear twice.

A sink that knows the batch number

Whether the copy is harmless depends on the sink.

  • A Delta table (format("delta")): each commit records the query id and the batch id in the Delta log, and a batch already there is skipped. Exactly once.
  • foreachBatch(fn): Spark calls your function as fn(df, batch_id). That is at-least-once, unless you make each write idempotent: pass txnAppId (a stable name) and txnVersion=batch_id to every Delta write, MERGE on a natural key, or store the batch id in the same database transaction as the rows.
  • A Kafka topic: at-least-once only. Spark's guide says records may be duplicated, so readers dedupe on a key.

foreachBatch writing two Delta tables, exactly once

Runs on Databricks:

APP_ID = 'clicks_10m_gold_v1'      # stable for the life of this checkpoint

def write_both(df, batch_id):
    df.persist()
    (df.write.format('delta').mode('append')
       .option('txnAppId', APP_ID).option('txnVersion', batch_id)
       .saveAsTable('swiftkart.gold.clicks_10m'))
    (df.groupBy('type').agg({'count': 'sum'}).write.format('delta').mode('append')
       .option('txnAppId', APP_ID).option('txnVersion', batch_id)
       .saveAsTable('swiftkart.gold.clicks_by_type'))
    df.unpersist()

query = (counts.writeStream
    .foreachBatch(write_both)
    .outputMode('append')
    .option('checkpointLocation', '/Volumes/swiftkart/stream/checkpoints/clicks_10m_gold')
    .start())

Find txnAppId and txnVersion on both writes. If batch 57 dies after the first table, its rerun skips that table, which already holds version 57 for this app id, and writes the second.

Crash after the sink write, then restart

import ministream as ms

times = ['10:02', '10:04', '10:07', '10:11', '10:14', '10:23', '10:26', '10:31']
for idempotent in [True, False]:
    broker = ms.Broker()
    broker.create_topic('clicks', partitions=1)
    for i, t in enumerate(times):
        broker.produce('clicks', None, {'event_id': f'e{i}', 'ts': f'2025-06-01T{t}:00Z'})
    cp, sink = ms.Checkpoint(), ms.Sink(idempotent=idempotent)
    args = dict(window_minutes=10, delay_minutes=10, max_offsets_per_trigger=3)

    query = ms.WindowedCount(broker, 'clicks', cp, sink, **args)
    query.trigger()
    query.trigger()
    print(query.trigger(crash='after_sink'))              # batch 2 dies before commits/2
    print('  offsets', sorted(cp.offsets), 'commits', sorted(cp.commits))

    query = ms.WindowedCount(broker, 'clicks', cp, sink, **args)   # restart: same checkpoint
    rerun = query.trigger()
    print('  rerun of batch', rerun['batchId'], '| sink wrote it again:', rerun['sinkWrote'])
    query.run()
    print('  idempotent sink' if idempotent else '  plain append', sink.rows)

The same crash, twice. Both times the checkpoint shows offsets 0 to 2 and commits 0 to 1, and the restart reruns batch 2. With the idempotent sink the 10:00 window is there once. With a plain append it is there twice. Only the sink decides.

Remember: offsets/N first, commits/N last. A batch with a plan and no tick runs again, exactly the same, so the sink must recognise its number.

Where the running counts live

Now the first mystery. Whatever a query must remember between batches is its state: open windows, ids already seen, rows waiting for a join partner. A step that keeps state is called a stateful operator.

Spark keeps state in state stores. Before a stateful operator, rows are shuffled by key (Lesson 12.3), so the same key always reaches the same store. There is one store per shuffle partition: with the default spark.sql.shuffle.partitions of 200, a windowed count has 200 stores.

That number is frozen into the checkpoint: a key hashed into one of 200 stores would be looked for in the wrong one. Spark's guide lists it among the settings that cannot change after the first run. To change it, start a new checkpoint.

By default a store is a hash map in the executor's Java memory. Hold on to that fact.

Mystery one: ids that are never forgotten

Done right, the dedupe reads withWatermark("ts", "2 hours").dropDuplicates(["event_id", "ts"]). An id is evicted (dropped from state) once the watermark passes its event time:

  • 5,000 x 7,200 s = 36 million rows
  • at about 100 bytes a row, 3.6 GB, or 18 MB in each of 200 stores. Comfortable.

The job had dropDuplicates(["event_id"]). With no event time in the key, the watermark has nothing to compare against, and no id can ever be evicted:

  • 5,000 x 86,400 s = 432 million new rows a day

All of it sits in Java memory. Garbage collection slows every batch, and then the heap runs out. That is the job that ran fine for three weeks.

Since Spark 3.5, dropDuplicatesWithinWatermark(["event_id"]) dedupes on the id alone and still evicts by the watermark.

The same windowed count with no watermark runs in update mode; every batch rewrites the windows it changed, nothing is evicted, and the number of state rows grows with every new window.

The same disease in a windowed count. Watch the bars: one more state row for every new window, for ever.

Joins remember both sides

Joining two streams, say ad impressions with clicks, needs the same care. A click may arrive before or after its impression, so Spark keeps both sides in state and waits.

To bound that state you need two things: a watermark on both inputs, and a time-range condition, such as clickTime BETWEEN impressionTime AND impressionTime + INTERVAL 1 HOUR. A buffered impression is then evicted once the watermark passes its time plus the hour.

Outer joins need both as well. They emit an unmatched row (with nulls) only when the watermark passes that bound, so a left outer result arrives at least the bound plus the delay late.

Sizing: 3,000 impressions a second, a 1-hour bound and a 10-minute delay keep about 3,000 x 4,200 s = 12.6 million impression rows, plus the buffered clicks.

Where all this state is kept

The default store (HDFSBackedStateStoreProvider)RocksDB (RocksDBStateStoreProvider, since Spark 3.2)
A hash map on the executor's Java heapRocksDB: native memory and local disk, off the Java heap
Each version writes a .delta file of changed keys, with a snapshot now and thenUploads new SST files at each commit, or only a changelog (...rocksdb.changelogCheckpointing.enabled, false by default, Spark 3.5+)
Millions of keys bring long garbage-collection pauses, batch times that swing, then OutOfMemoryError: Java heap spaceHolds far more keys per executor; memory is unbounded unless boundedMemoryUsage is on, with maxMemoryUsageMB (500 by default) as the cap
Fine for small stateTurn on with spark.sql.streaming.stateStore.providerClass=org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider

Mystery two: the six missing hours

The job died at 22:00. At 04:00 its checkpoint was deleted and the job was started again.

A new checkpoint has no offsets/ files, so the query asks its startingOffsets option where to begin. For Kafka the default is latest: the end of the topic. Everything between 22:00 and 04:00 was skipped, silently. Kafka could not help, because Spark's Kafka source keeps its offsets only in the checkpoint and never commits them to Kafka.

The checkpoint is the query. Never share one, never copy half of one, never delete one to "reset" a job.

What should have happened at 04:00: find the last offsets you trust. If the bronze table stores Kafka's partition and offset columns (it should), the next offset for each partition is max(offset) + 1. Pass those as JSON in startingOffsets.

Six hours that no checkpoint covers

A timeline of Thursday night: clicks arrive in Kafka all night, the old checkpoint covers them up to 22:00, the new checkpoint starts at the latest offset at 04:00, and the six hours in between are read by nobody.

The axis is hours after 18:00 on Thursday: the job dies at 22:00 and is restarted at 04:00. Kafka holds every click the whole time (top lane). What is missing is a reader that knew where to start.

Restart from the offsets the bronze table already holds

Runs on Databricks:

import json
from pyspark.sql import functions as F

last = (spark.table('swiftkart.bronze.clicks')
        .groupBy('partition').agg(F.max('offset').alias('last'))
        .orderBy('partition').collect())
starting = json.dumps({'clicks': {str(r['partition']): r['last'] + 1 for r in last}})
print(starting)

clicks = (spark.readStream.format('kafka')
    .option('kafka.bootstrap.servers', 'broker:9092')
    .option('subscribe', 'clicks')
    .option('startingOffsets', starting)      # used only because the checkpoint is new
    .load())
{"clicks": {"0": 1840251, "1": 1839005, "2": 1612005}}

The printed JSON is what goes into startingOffsets: one next offset per partition. The option is read only when the checkpoint is empty; on later restarts the checkpoint wins.

Two more rules for a clean recovery. Use a new txnAppId in foreachBatch: a new checkpoint numbers batches from 0 again, and Delta would skip them as already written under the old id. And state cannot be copied over: replay from far enough back to rebuild it. If those offsets have aged out of Kafka, failOnDataLoss (true by default) stops the query with "Some data may have been lost because they are not available in Kafka any more".

Triggers: when a batch runs, and how big it is

TriggerWhen batches runStops?Use it for
none (the default)the next batch starts as soon as the previous one endsnothe lowest micro-batch latency
processingTime="1 minute"on each 1-minute boundary; at once if a batch overran; no batch without datanosteady latency in fewer, bigger batches
availableNow=True (Spark 3.3+)everything available at start, in as many batches as the rate limits allow, then a final no-data batchyesstreaming code run on a schedule
once=True (deprecated)one batch with everything availableyesnothing new: move to availableNow
continuous="1 second" (experimental)records flow continuously; a checkpoint every secondnoabout 1 ms latency, at-least-once, map-like queries only

The trigger says when the loop turns. Rate limits cap each batch: on Kafka maxOffsetsPerTrigger (no default), or minOffsetsPerTrigger with maxTriggerDelay (15 minutes); on Delta maxFilesPerTrigger (1,000) and maxBytesPerTrigger. A backlog of 90 million offsets with maxOffsetsPerTrigger=5000000 drains in 18 bounded batches instead of one enormous one.

Changing a running query is not free. The checkpoint pins the shuffle partitions, the stateful operators and their schemas. Add a dropDuplicates, change a grouping key or a join type, and the restart fails the state schema check (spark.sql.streaming.stateStore.stateSchemaCheck, true). Adding a rate limit is safe; changing the subscribed topics is not. Plan such changes as a new query with a new checkpoint, started from known offsets.

Numbers to remember

WhatValueNote
spark.sql.shuffle.partitions200one state store per partition for each stateful operator; fixed by the checkpoint
spark.sql.streaming.minBatchesToRetain100how many batches the checkpoint keeps
Inside an offsets/N filethree partsa version line; a JSON line with the batch watermark, timestamp and pinned configs; one line of offsets per source, such as {"clicks":{"0":1840250,"1":1839004}}
Default store on diska .delta file per versionplus a .snapshot now and then, under state/<operator/<partition/
A task and its storeopens version N, commits N + 1the scheduler prefers the executor that has the store loaded; elsewhere it is reloaded from the checkpoint first, which is why spark.locality.wait matters
query.lastProgressnumRowsTotal, memoryUsedBytesunder stateOperators[]; divide them for the real bytes per row
startingOffsets (Kafka)latestread only when the checkpoint is empty
failOnDataLosstruestops the query when offsets it needs are gone from Kafka
transformWithStateSpark 4.0the new operator for custom state, replacing mapGroupsWithState and flatMapGroupsWithState: typed state variables (ValueState, ListState, MapState), timers per key and a TTL; Python has a row flavour and transformWithStateInPandas
State data sourceSpark 4.0, read-only, experimentalspark.read.format("statestore").load(checkpoint) returns key, value and partitionid; format("state-metadata") lists the operators and their batch ranges
On Databricksone checkpoint per queryin a Unity Catalog volume, with RocksDB for large state; kafka-consumer-groups shows no lag for a Spark job, so watch the query's progress

What changed at SwiftKart

Mystery one: the dedupe now includes the event time, so the watermark can evict. State settles near 36 million rows, in RocksDB, off the Java heap.

That changes the state schema, so it ships as a new query: new checkpoint, new txnAppId, fresh output table. The same move solves mystery two. The new query starts from offsets looked up in the bronze table, from before the gap. The six hours are still in Kafka, which keeps 7 days, so they are replayed. Once it has caught up, the dashboard is pointed at the new table.

You add two alerts: state rows that only grow, and batches that take longer than the trigger interval.

That is streaming, end to end: a log, a promise about delivery, a clock, and a folder that remembers. Module 16 turns to a new kind of reader of your data: AI agents.

In one line

Each micro-batch writes its plan first and its commit last, so a restart reruns the unfinished batch exactly; the sink must skip a batch it has seen, and state stays bounded only if the watermark can evict it.

Interview corner

What does Structured Streaming write to the checkpoint in one micro-batch, and what happens on restart?

Before any work it writes offsets/N with the offset range, the batch watermark and pinned configs; the stateful tasks then write state version N + 1 for each operator and partition; the sink gets the batch with its id; and commits/N is written last with the next watermark. On restart, if the newest offsets file has no commit, that batch is rerun with exactly the same range, watermark and starting state, so the output is the same. The sink has to make that possible second write harmless, which Delta does by recording the query id and batch id.

How do you get exactly-once into Delta, and into a database, with foreachBatch?

Into Delta directly, the streaming sink is already idempotent per batch. Inside foreachBatch I pass a stable txnAppId and txnVersion equal to the batch id on every Delta write, so a rerun skips tables already written for that batch, and I persist the batch DataFrame so it is not computed twice. For a database I MERGE on a natural key or store the batch id in a control table in the same transaction as the rows, and skip a batch id already recorded. After a new checkpoint I change the app id, because batch ids restart at 0.

A stateful streaming job gets slower every day and then dies with OutOfMemoryError. How do you diagnose and fix it?

I look at stateOperators in the query progress: if numRowsTotal grows steadily, state is never evicted. Usually there is no watermark, or the event-time column is not part of the state key, as with dropDuplicates on the id alone, or a stream-stream join lacks a time-range condition. The fix is a watermark that can evict, such as dropDuplicatesWithinWatermark or a time bound on the join, plus RocksDB if the bounded state is still large; with the default store state lives on the JVM heap and garbage collection degrades first. The state data source can confirm which partitions hold the rows.

The checkpoint is lost. How do you restart without losing or duplicating data?

I do not restart blindly, because a new checkpoint starts from startingOffsets, latest by default, and Spark never committed offsets to Kafka. I read the highest Kafka offset per partition that reached the bronze table, start a new query with startingOffsets set to those plus one, and a new txnAppId so Delta does not skip the new batch ids. Stateful jobs need to replay far enough back to rebuild their windows. If the offsets have aged out, failOnDataLoss stops the query, and the gap has to come from another copy of the raw events.