Skip to content
Bronze 7 min read · RocksDB 2 practice problems ↓

Checkpoints and state stores

A stream that runs for months will be restarted: deploys, crashes, cluster upgrades. The checkpoint is what lets it continue as if nothing happened. This lesson opens the checkpoint folder, explains each part in plain words, and shows where a stream keeps what it remembers between batches.

Step 4 · Structured Streaming · Bronze · Output modes and checkpoints, lesson 2 of 2

Read first: Structured Streaming basics (skip if you know it)

In plain words first

Picture reading a long book over many evenings. Before each evening you write in a notebook "tonight: pages 120 to 150". When you finish, you tick it. Next to that, you keep notes about the characters so far. If you fall asleep half way, tomorrow you see an entry without a tick and reread exactly pages 120 to 150, with your character notes as they were before that evening.

A checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more → is that notebook. The "tonight" entries are the offsetsoffset: The position of a message inside a Kafka partition: 0, 1, 2, ... A stream stores the offsets it has read in its checkpoint. Learn more → log, the ticks are the commits log, and the character notes are the state: running counts, open windows, ids already seen.

Inside a checkpoint folder

PathHoldsWritten
metadataThe query id, which stays the same across restartsOnce, at the first start
offsets/NWhat batch N will read, plus settings that must not change later (such as the number of shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → partitionspartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more →)Before batch N runs
commits/NA tick: batch N is finishedAfter the sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → wrote batch N
sources/0For a file sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more →: the files already readWith each batch
state/<operator>/<partition>/What each stateful step remembers, per partition: N.delta files with the changes, and a full N.snapshot now and thenWith each batch, for stateful queries

On restart Spark reads the last entry in offsets. If commits has the same batch, it moves on to new data. If not, the batch was interrupted: it is run again on exactly the recorded input, with the state as it was after the previous batch.

State is split into partitions, for good

A stateful step, such as a count per user, sends each user's rows to one of a fixed number of slices, the shuffle partitions, and each slice keeps the state for its users. That number is spark.sql.shuffle.partitions when the checkpoint is created, 200 by default, and it is written into the offsets log. Changing the setting later has no effect on that query: its state is already split 200 ways. Choose the number before the first run, from the expected state size, and plan a new checkpoint if it ever has to change.

Where state lives while the query runs

Default (HDFS-backed)RocksDB
WhereA hash map in executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → memory (the JVM heap)A small database on the executor's local disk, with a memory cache
Good forSmall stateMillions of keys; avoids long garbage-collection pauses
Saved to the checkpoint asChanged keys as delta files, plus snapshotssnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more → now and thenChanged RocksDB files; with changelog checkpointing, only the changed keys
Turn on withNothing to dospark.sql.streaming.stateStore.providerClass = org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
Note: RocksDB can hold more state; it does not make state smaller. Only a watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → (or a TTL in custom state) removes old keys. Newer APIs such as transformWithState require RocksDB.

Looking inside the state

Spark 4 can read a checkpoint's state like a table: spark.read.format("statestore").load(checkpoint_path) returns each key, its value and its partition, and format("state-metadata") lists the stateful steps. Use it to answer "how big is the state, and which keys never expire?" instead of guessing from metrics.

Housekeeping

  • Spark keeps the last spark.sql.streaming.minBatchesToRetain batches of offsets, commits and state files (100 by default) and deletes older ones as it goes.
  • Put checkpoints on durable storage (S3, ADLS, GCS, HDFS), never on the local disk of a cluster that can disappear.
  • One checkpoint per query, never shared. Deleting one makes the query start over from startingOffsets.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Open a checkpoint and look at what it holds, including the state.

ExplorePySpark · What a checkpoint holds, and the state inside it
import json, os

os.makedirs("lab/chk/in", exist_ok=True)
with open("lab/chk/in/a.json", "w") as f:
    f.write("\n".join(json.dumps({"user": u}) for u in ["ana", "bo", "ana"]))

(spark.readStream.schema("user STRING").json("lab/chk/in")
    .groupBy("user").count()
    # memory sink: keeps the result in a temp table named "chk_counts"
    .writeStream.outputMode("complete").format("memory").queryName("chk_counts")
    .option("checkpointLocation", "lab/chk/_chk")
    .trigger(availableNow=True)
    .start().awaitTermination())

visible = lambda d: sorted(f for f in os.listdir(d) if not f.startswith("."))
print("top level:", visible("lab/chk/_chk"))
print("offsets:", visible("lab/chk/_chk/offsets"),
      "commits:", visible("lab/chk/_chk/commits"))
parts = [p for p in os.listdir("lab/chk/_chk/state/0") if p.isdigit()]
print("state partitions of operator 0:", len(parts))

# Spark 4: read the state store like a table
(spark.read.format("statestore").load("lab/chk/_chk")
    .selectExpr("key.user", "value.count").orderBy("user").show())

Output from a real run

top level: ['commits', 'metadata', 'offsets', 'sources', 'state']
offsets: ['0'] commits: ['0']
state partitions of operator 0: 200
+----+-----+
|user|count|
+----+-----+
| ana|    2|
|  bo|    1|
+----+-----+

What to notice:

  • Five folders: offsets (what each batch will read), commits (batches finished), sources, metadata and state.
  • One batch ran, so there is one offset and one commit, both 0.
  • The state has 200 partitions, and you can read it like a table: ana 2, bo 1. That number is fixed when the checkpoint is created; changing the setting later does not change it.

Common mistakes

  • Raising spark.sql.shuffle.partitions to speed up a running stateful query — No effect: the number is fixed in the checkpoint.
  • Switching to RocksDB to fix state that grows forever — It only stores more. Add a watermark or a TTL.
  • Copying a checkpoint to start a second query — Two queries now share one id and history. Each query needs its own checkpoint.
  • Checkpoints on a local disk that can disappear — Lost with the cluster, and with them the exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → guarantee.

Key takeaways

  • offsets is written before a batch runs and commits after it finishes: together they make a re-run exact.
  • State is split into the number of shuffle partitions chosen at the first run, for good.
  • RocksDB holds large state on disk; only watermarks and TTLs make it smaller.
  • Spark 4 reads state as a table with format("statestore").

Interview prep

THE QUESTION

"A streaming job's checkpoint folder is several terabytes. What is in it, and how do you shrink it?"

Almost certainly state: state/ holds every key of every stateful operator, versioned per batch. Check which operator and why it grows: an aggregation or dropDuplicates without a watermark keeps keys forever. Read it with the statestore data source to see the keys. Fixes: add or shorten a watermark, use dropDuplicatesWithinWatermark, set a TTL for custom state, and keep minBatchesToRetain at its default. RocksDB with changelog checkpointing makes each batch's upload smaller, but does not remove keys.

Avoid: "the checkpoint stores the output" or "just the offsets". It stores the input ranges (write-ahead), the commits, the file source log and all operator state.

Follow-ups · answer out loud, then open

Follow-up"Why can't you change spark.sql.shuffle.partitions on a running stateful query?"
State is split by key into that many partitions when the checkpoint is created, and the number is stored in the offsets log. Rows must keep going to the partition that holds their state, so Spark keeps the original number. Changing it needs a new checkpoint.
Scenario"Executors of a stateful stream keep hitting long garbage-collection pauses. What do you change?"
Move state off the JVM heap with the RocksDB state store provider, ideally with changelog checkpointing. Then check why state is so large: a missing or too-long watermark is the usual cause.
Trap"State older than minBatchesToRetain is removed from the state store."
minBatchesToRetain only controls how many old versions of the checkpoint files are kept for recovery. Which keys live in state is decided by watermarks, TTLs and your code.

Check yourself

3 questions

offsets/42 exists but commits/42 does not. What happens on restart?

Show the answer

Batch 42 is run again on the same input. An unfinished batch is re-run exactly.

You set spark.sql.shuffle.partitions to 50 and restart a stateful query that started with 200. How many state partitions does it use?

Show the answer

200. The number is stored in the checkpoint when it is created.

What does switching to the RocksDB state store solve?

Show the answer

Large state that causes memory pressure and GC pauses. It moves state off the JVM heap; it does not remove keys.

Practise this

Interview problems on streaming, graded on hidden tests

Keep going

Up next · new module: Kafka basics · 8 min read
Kafka in plain words
Topics, partitions, offsets, brokers and retention: why Kafka is a log that keeps messages, not a queue that deletes them.

Related lessons

Previous: Output modes: append, update, complete

Primary sources: Recovering from failures with checkpointing · State store · State data source