Sub topic 3
How checkpoints give you each file exactly once
This chapter assumes you know Spark Structured Streaming basics (readStream, writeStream), have written a Delta table, and can read cloud storage paths. It builds on the cloudFiles source from the previous chapter. It explains what a checkpoint stores, why that gives you each file once, and which mistakes break the guarantee.
What a checkpoint is
A checkpoint is a directory where a streaming query records its progress. Spark writes to it as the query runs. When the query restarts, Spark reads it to learn what was already done.
For Auto Loader, the checkpoint answers two questions:
- Which files has this stream already ingested?
- Which micro-batch was running when the last run stopped?
Without that record, a restarted stream would have to list the whole landing folder and guess what is new. That is the file-listing problem from the first chapter. The checkpoint lets Auto Loader skip the guessing.
You set the checkpoint on the write side:
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))The checkpoint belongs to the query, not to the table or the folder. One stream, one checkpoint.
What Auto Loader stores
Auto Loader keeps its file state in a RocksDB key-value store inside the checkpoint directory. RocksDB is an embedded database. Each key is a file identified by its path and its modification time. Auto Loader adds a key when it discovers a file and marks it as processed after the batch commits.
This design has a useful consequence. Checking whether a file is new is a key lookup. It does not depend on how many files sit in the folder. Cost grows with the number of new files, not with the total number of files.
The checkpoint holds more than the file list. Spark's own streaming metadata is also there:
| Item | Purpose |
|---|---|
| `offsets` | Records what each micro-batch plans to read, written before the batch starts |
| `commits` | Records that a micro-batch finished, written after the sink accepts the data |
| `sources` | Source-specific state, which for Auto Loader includes the RocksDB file store |
| `metadata` | The unique ID of the query |
Do not edit these files by hand. Treat the directory as owned by Spark.
How exactly-once works
The guarantee comes from two cooperating parts: a replayable source and an idempotent sink.
- Before a batch runs, Spark writes the batch's plan to
offsets. For Auto Loader, the plan names the files in the batch. - Spark reads those files and writes the rows to the Delta table.
- When the Delta write succeeds, Spark writes the batch to
commits. - Auto Loader records the files as processed.
Now consider a crash. The outcome depends on where it happens.
- Crash before step 1 completes: nothing was planned. On restart, discovery runs again and the files are still new.
- Crash between steps 1 and 3: the plan exists but there is no commit. On restart, Spark re-runs the same batch with the same files. Delta's transaction log accepts a given streaming batch only once, so a half-finished attempt does not leave duplicate rows.
- Crash after step 3: the batch is committed. Restart moves on to the next batch.
The result is called exactly-once processing. The words need care. Spark may attempt a batch more than once, but the effect on the table happens once.
What exactly-once covers and what it does not
The guarantee holds per file, per checkpoint, into a Delta sink. These limits matter in practice.
- Same path, same modification time. Auto Loader tracks files by path. If a file is overwritten in place, it is ignored by default, because the path is already recorded. Set
cloudFiles.allowOverwritestotrueonly if you want overwritten files to be reprocessed, and accept that this can produce duplicate rows for the same logical data. - Duplicate content under different names. If a producer delivers the same data twice as
a.jsonandb.json, Auto Loader reads both. The checkpoint knows files, not content. Deduplicate downstream on a business key. - Non-Delta sinks. The guarantee depends on the sink handling replays. A
foreachBatchfunction that writes to an external system must be idempotent itself, for example by using aMERGEon a key. - Multiple streams. Two queries reading the same folder with different checkpoints each ingest every file. That is correct behavior, not a bug.
Checkpoints are tied to the query definition
Some changes to a query are safe with an existing checkpoint, and some are not. Spark compares the new query against the stored state.
Generally safe:
- Changing the target table's downstream logic that does not affect state, such as adding a column with
withColumn. - Changing trigger settings.
- Changing rate limits like
cloudFiles.maxFilesPerTrigger.
Generally unsafe:
- Pointing the same checkpoint at a different source path. The stored file list refers to the old location.
- Changing the file format in a way that breaks stored schema information.
- Reusing one checkpoint for two different queries.
When you need a clean start, use a new checkpoint path and decide on purpose how to handle existing files. For example, you can start a new stream into a new table. The chapter on existing files and backfill covers the options.
Checkpoint and schema location are different
Beginners often mix up the two directories.
| Setting | Stores | Lost if deleted |
|---|---|---|
| `checkpointLocation` | Progress and the list of ingested files | Files are re-ingested |
| `cloudFiles.schemaLocation` | The inferred schema and its history of changes | Schema is re-inferred from sample files |
Keep them in separate directories, as in the example above (_checkpoints/orders and _schemas/orders). Both should be on durable storage that survives cluster termination. Do not put them on local disk of a cluster.
Restarting and recovering
The normal restart is simple: run the same code with the same checkpoint path. Nothing else is needed.
A job that uses availableNow shows this clearly. Each run does the following:
- Opens the checkpoint.
- Discovers files that are not in the stored state.
- Processes them in one or more batches.
- Commits and stops.
If a run fails halfway, rerun it. Completed batches stay committed and the failed batch is replayed.
You can look at what a stream has recorded with cloud_files_state, a table-valued function that reads the file state from a checkpoint:
SELECT path, size, discovery_time, commit_time
FROM cloud_files_state('/Volumes/main/raw/_checkpoints/orders')
ORDER BY discovery_time DESC
LIMIT 20;A row with a commit_time of NULL was discovered but not yet committed. Use this query to answer the question "did file X get ingested?" without scanning the Delta table.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Whole folder re-ingested after a deploy | Checkpoint path changed or was deleted | Pin the path in configuration and keep it stable across releases |
| Duplicate rows with identical content | Producer wrote the same data to two files | Deduplicate on a business key downstream |
| New version of a file is never picked up | Overwrite on an existing path | Write new files with new names, or set `cloudFiles.allowOverwrites` and handle duplicates |
| Error about a concurrent or incompatible checkpoint | Two queries share one checkpoint | Give each query its own checkpoint directory |
| Stream cannot restart after a code change | Change is incompatible with stored state | Use a new checkpoint and plan the backfill |
Practical rules
- Give every stream its own checkpoint directory, named after the target table.
- Store checkpoints in the same governed storage area as the data, such as a Unity Catalog volume.
- Put the checkpoint path in configuration, not scattered through notebooks.
- Never delete a checkpoint without a plan for the data already in the table.
- Prefer new file names over overwriting files in the landing folder.
Exercise
A stream with checkpoint /chk/orders has run for a month. A teammate deletes /chk/orders to "clean up", then reruns the job with the same code. What happens to the table main.bronze.orders, and what is the safest way to start fresh on purpose?
Show answer
Auto Loader has no record of ingested files, so it treats every file in the landing folder as new and appends them all again. The table then holds duplicate rows. To start fresh on purpose, either truncate or recreate the target table together with a new checkpoint path, or keep the table and use a new checkpoint while restricting what is read, for example by moving old files out of the landing folder. Decide this before deleting anything.
Exercise
Why can a micro-batch run twice after a crash without producing duplicate rows in a Delta table?
Show answer
The batch's plan is written to offsets before it runs, so a restart replays the same batch with the same files. The Delta sink records which streaming batch it has already committed and rejects a repeat, so only one write takes effect. The batch may be attempted twice, but its effect on the table happens once.