Sub topic 15
Operating Auto Loader in production
This chapter assumes you can already build an Auto Loader stream with the cloudFiles source and know what a checkpoint, a schema location, and a trigger do. It covers how to watch a running ingestion stream, how to restart it safely, and which changes are safe to make afterward.
What can go wrong in production
An ingestion stream usually runs unattended for months, and the failures it hits tend to come from a small set of causes:
- The schema changed and the stream stopped.
- Files arrive faster than the stream reads them, so a backlog grows.
- Someone deleted or reused a checkpoint.
- A discovery mode no longer sees every file.
- Cloud resources created for file notification outlive the stream that needed them.
Each of these can be spotted early if you know where to look.
Keep state separate and stable
Auto Loader keeps two kinds of state, and both must survive between runs.
| State | Option or location | Holds | If you lose it |
|---|---|---|---|
| Checkpoint | `checkpointLocation` on the write | Which files were discovered and committed, plus offsets | The stream treats every file as new and reprocesses it |
| Schema location | `cloudFiles.schemaLocation` on the read | Inferred schema and its evolution history | The next run re-infers the schema from a sample of files |
Follow these rules:
- Give every stream its own checkpoint and its own schema location. Two streams that share a checkpoint corrupt each other.
- Store both paths outside the landing folder, for example under
/Volumes/main/raw/_checkpoints/ordersand/Volumes/main/raw/_schemas/orders. - Tie the checkpoint to the target table. If you point the same checkpoint at a different table, rows already ingested are skipped and the new table stays incomplete.
- Never delete a checkpoint to "fix" a failure. With an append-only target, the stream will ingest every existing file again and create duplicates.
Monitor the backlog
A healthy stream keeps up with arrivals. The most useful signal is how much work is waiting, and the stream reports it in each progress update.
The source section of a progress report includes backlog metrics, such as numFilesOutstanding and numBytesOutstanding. These count files and bytes that Auto Loader has discovered but not yet processed. If these numbers rise from one run to the next, ingestion is falling behind. In the Spark UI and in the streaming query dashboard, the same figures appear next to input rate and batch duration.
The following script runs an availableNow job and prints the backlog metrics afterward:
query = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/orders")
.load("/Volumes/main/raw/landing/orders")
.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/orders")
.trigger(availableNow=True)
.toTable("main.bronze.orders"))
query.awaitTermination()
progress = query.lastProgress
if progress:
for source in progress["sources"]:
print(source["description"])
print(source.get("metrics", {}))
print("rows written:", progress["numInputRows"])Here lastProgress can be empty when a run finds nothing to do, so the script checks it before reading. For a job you schedule, send these numbers to a log table or your monitoring tool. Alert on three conditions: outstanding files grow across runs, the run duration climbs steadily, or a run reads zero rows when files should have arrived.
Inspect file discovery with cloud_files_state
Auto Loader records every file it discovers in the checkpoint. The cloud_files_state function exposes that record as a table, so you can answer questions such as "was this file ever seen?" without guessing.
SELECT path, size, discovery_time, commit_time
FROM cloud_files_state('/Volumes/main/raw/_checkpoints/orders')
WHERE commit_time IS NULL
ORDER BY discovery_time;A row with a discovery_time but no commit_time is a file that was found and not yet written. A few of these during a run are normal. Many old ones point to a stuck or failing stream. If a file is missing from the output entirely, discovery never saw it, and you should check the discovery mode (next sections) instead of the transformation code.
Handle failures and restarts
Auto Loader is built to be restarted. Because the checkpoint records progress, a restart resumes from the last committed batch. The practical question is whether the failure is transient or needs a change.
The schema case deserves attention. With cloudFiles.schemaEvolutionMode set to addNewColumns, which is the default when no schema is given, the stream stops when it sees a new column. Before stopping, it saves the widened schema in the schema location. The next start uses that schema and succeeds. This means the failure is expected, and the fix is a restart.
To make this automatic, run the stream as a job with retries enabled. A scheduled availableNow job fails, retries once, and finishes. Without retries, someone has to rerun it by hand.
What you can change on an existing stream
Some changes are safe against an existing checkpoint, and others require a new one.
| Change | Safe with the same checkpoint? |
|---|---|
| `maxFilesPerTrigger` or `maxBytesPerTrigger` | Yes, they only change batch size |
| Cluster size or job schedule | Yes |
| Switching between `availableNow` and a continuous trigger | Yes |
| Adding schema hints for a new column | Usually yes, but test on a copy |
| Changing the source path | No, the checkpoint tracks files from the old path |
| Changing `cloudFiles.format` | No, the recorded state no longer matches |
| Pointing the checkpoint at a different target table | No |
When a change falls in the "No" rows, create a new checkpoint and decide deliberately how to handle files that already exist. You can set cloudFiles.includeExistingFiles to false so the new stream only picks up files that arrive after it starts. Be sure the old stream has already ingested everything before it stops.
Keep file discovery reliable
In directory listing mode, Auto Loader finds files by listing the input path, using the checkpoint to skip files it has seen. It uses incremental listing where it can, so cost grows with new files and not with total files. Listing is simple and needs no extra cloud setup, but a very large folder with high arrival rates can make each listing slow.
File notification mode gets file events from cloud queues. It scales better but adds components that can fail on their own: permissions, queues, and event subscriptions. Events can also be dropped or delayed, so a file can be missed even though the stream itself is healthy.
For this reason, set cloudFiles.backfillInterval when you use notifications:
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("header", "true")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/events")
.option("cloudFiles.useNotifications", "true")
.option("cloudFiles.backfillInterval", "1 day")
.option("cloudFiles.maxFilesPerTrigger", "500")
.load("s3://my-bucket/landing/events"))The backfill interval makes Auto Loader do an occasional listing on top of the events. Any file the notifications missed is picked up by that listing, and the checkpoint prevents duplicates. This gives you the speed of notifications with a safety net.
Notification mode creates cloud resources. If you delete a stream permanently, remove those resources too, or they keep accruing cost and events. Use the resource cleanup tools provided with Auto Loader for your cloud, and confirm the exact steps in the Databricks documentation for your cloud provider.
Control cost and keep state small
- Batch size. Set
maxFilesPerTriggerormaxBytesPerTriggerso one batch fits comfortably in cluster memory. An unbounded first run over millions of files can cause out-of-memory errors and long failures that lose the whole batch. - Cluster use. An
availableNowjob on a job cluster starts, drains the backlog, and shuts down. This is usually cheaper than a continuous stream when data arrives in bursts and freshness of minutes is acceptable. - State growth. The checkpoint records every file ever discovered. For very long-lived streams,
cloudFiles.maxFileAgecan expire old tracking entries. Use it carefully: a file older than the limit that reappears may be ingested again. Pick a value much longer than any plausible late arrival. - Landing folder hygiene. Moving or deleting processed files does not affect correctness, since the checkpoint tracks them, but it shortens listings. If you do this, archive with a lifecycle rule and not by hand, and never rewrite a file in place. A file replaced at the same path is not guaranteed to be picked up as a new file.
A short production checklist
- One checkpoint and one schema location per stream, stored outside the landing folder.
- Job retries enabled, so schema evolution restarts happen automatically.
- Backlog metrics logged and alerted on.
- Batch size capped explicitly.
backfillIntervalset if you use file notification.- A written procedure for full reloads that does not start with deleting the checkpoint.
source_filecaptured from_metadata.file_path, so any bad row can be traced to its file.
Exercise
A scheduled availableNow job fails with an unknown-field error after a new column appears in the source JSON. The retry also fails with the same error because the Delta write rejects the new column. Which component needs attention, and should you delete the checkpoint?
Show answer
The target write needs attention, not the checkpoint. Auto Loader already saved the widened schema in the schema location, so the read side works after a restart. The Delta write must accept the new column, for example by enabling schema merging or adding the column to the table. Deleting the checkpoint would reprocess every file and create duplicates in an append-only table.
Exercise
You run Auto Loader in file notification mode and a downstream report is missing three files that exist in the landing folder. The stream shows no errors. What is the most likely cause, and which option reduces the risk?
Show answer
The cloud event notifications for those files were dropped or delayed, so Auto Loader never learned about them. Setting cloudFiles.backfillInterval makes Auto Loader run a periodic listing that finds missed files, and cloudfilesstate can confirm whether the files were ever discovered.