Sub topic 1
Why incremental ingestion needs more than listing a directory
Files arrive in cloud storage all day, and you want each one loaded into a Delta table exactly once. The obvious approach is to list the folder, find what is new, and load it. This chapter shows why that approach breaks down as the folder grows, and what a better design has to provide. The rest of the tutorial covers how Auto Loader provides it.
Prerequisites
This chapter assumes you already have the following:
- Basic Python or SQL.
- Familiarity with Spark DataFrames.
- A basic idea of Spark Structured Streaming (
readStreamandwriteStream). - Familiarity with Delta tables and cloud object storage paths such as Unity Catalog volumes or
s3://URLs.
You don't need to know Auto Loader yet.
What incremental ingestion means
Incremental ingestion means each run processes only the data that arrived since the last run. The alternative is a full reload, where every run reads everything again. A full reload is simple, but its cost grows with the total history instead of the new data. After a year of daily files, you pay a year of reads to pick up one day.
For file sources, "what is new" is the hard part. A file source has no sequence numbers or offsets like a message queue does. It only has object names and modification times. Any incremental design must answer one question reliably: which files have I already processed?
The naive approach: list and compare
The usual first attempt keeps a ledger table of processed file paths. Each run lists the landing folder, subtracts the ledger, reads the remainder, and then records the new paths.
landing = "/Volumes/main/raw/landing/orders"
ledger = "main.ops.processed_files"
spark.sql(f"CREATE TABLE IF NOT EXISTS {ledger} (path STRING)")
seen = {row.path for row in spark.table(ledger).collect()}
new_paths = [f.path for f in dbutils.fs.ls(landing) if f.path not in seen]
if new_paths:
(spark.read.format("json").load(new_paths)
.write.mode("append").saveAsTable("main.bronze.orders"))
(spark.createDataFrame([(p,) for p in new_paths], "path STRING")
.write.mode("append").saveAsTable(ledger))This works on a small folder, and for a prototype it is fine. It has four problems that show up as volume grows.
Problem 1: listing cost grows with history
Every run lists every file, including the millions you processed long ago. Object stores return a limited number of entries per request. Amazon S3, for example, returns at most 1,000 keys per list call. A folder with 10 million files needs about 10,000 sequential requests before you can even start comparing. Run that hourly and most of your job time goes to listing.
Listing also scales with the whole folder, not with the new files. A run that finds 20 new files costs the same as one that finds 20,000.
Problem 2: the ledger grows too
The seen set above is collected to the driver. Ten million paths of around 100 bytes each take about a gigabyte of driver memory. You could replace the collect() with an anti-join, which moves the work onto the cluster. Even then, every run compares the full listing against the full ledger.
Problem 3: the two writes are not atomic
The data write and the ledger write are separate commits. If the job fails between them, the data is in main.bronze.orders but the ledger doesn't know. The next run loads the same files again and you get duplicates. If you reverse the order, a failure loses those files instead, because the ledger says they are done when they are not.
You can reduce this with MERGE or idempotent keys, but you are then building a transaction protocol by hand.
Problem 4: files change and arrive in awkward ways
Real landing folders produce cases the simple loop ignores:
- Producers write nested folders such as
year=2026/month=12/day=04/.dbutils.fs.lsis not recursive, so you need to write a traversal. - A file may still be uploading when you list it. Most object stores make an object visible only when the upload completes, but mounted file systems and some tools expose partial files.
- A producer may overwrite an existing path. A path-only ledger treats the new content as already processed.
- A producer may add a column or change a type. A plain
read.format("json")infers the schema from the files in that run and produces different tables from run to run.
Alternatives people try, and where they stop
| Approach | What it fixes | What remains |
|---|---|---|
| Filter listing by modification time | Avoids a ledger | Files that arrive late with an older timestamp are skipped. Clock skew between writers breaks it. The listing still scans everything. |
| Partition folders by date and read only today's | Cuts listing size | Late files and reprocessing need special cases. Depends on producers following the layout. |
| Move processed files to an archive folder | Keeps the landing folder small | You need write and delete permissions on the source. A failure after loading but before moving causes duplicates. Other consumers lose access to the files. |
| Event-driven pipeline (queue message per file) | No listing needed | You must build and operate the queue, subscriptions, retries, and a way to catch missed events. |
Each of these solves part of the problem and moves the rest into code you must maintain.
What a good design must provide
Reading the failures above, a file ingestion system needs these properties:
- Cost proportional to new data. A run should not pay to rediscover old files.
- Durable progress tracking. The record of which files were processed must survive restarts and live in storage, not in memory.
- Atomic progress and output. Recording that a file is done and writing its rows must succeed or fail together, or at least be safely repeatable.
- Schema handling. New columns and bad values should not crash the job or silently vanish.
- Scalable discovery. Finding files must work for millions of files, using either efficient listing or storage event notifications.
- Controlled batch size. A backlog of a million files should not be read as one giant batch.
The sections that follow map these to Auto Loader features.
| Requirement | Where this tutorial covers it |
|---|---|
| Cost proportional to new data, scalable discovery | File discovery modes, file notification mode |
| Durable progress tracking, atomic progress and output | Checkpoints |
| Schema handling | Schema inference, `_rescued_data`, schema evolution |
| Controlled batch size | Rate limiting |
Auto Loader at a glance
Auto Loader is a Databricks streaming source named cloudFiles. You use it with the same readStream and writeStream calls as any Structured Streaming job. It tracks discovered files in the stream's checkpoint, so the state lives in cloud storage next to the job. Here is a minimal version of the ingestion you just wrote by hand:
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 ledger table, the set subtraction, and the two-step write are gone. The checkpoint replaces the ledger, and Structured Streaming's commit protocol coordinates it with the output. You will study each option in later chapters. For now, notice only that nothing in this code names which files are new.
The diagram below contrasts the two designs.
Common mistakes when reasoning about this problem
- Treating a modification-time filter as a safe cursor. A file written at 10:00 can become visible at 10:05. A run at 10:03 that advanced its cursor to 10:03 will never see it.
- Assuming object stores list in a useful order. S3 lists keys in lexicographic order, not by arrival time. Names such as
part-0001do not tell you which file is newest. - Optimizing the loop instead of the design. Caching the listing or parallelizing
lsreduces constant factors. The cost still grows with history. - Skipping the failure case. A pipeline that works for ten successful runs may duplicate data on the first failed one. Always ask what state exists if the job stops between any two steps.
Summary of the working model
Incremental file ingestion is a bookkeeping problem more than a reading problem. Reading a JSON file is easy. The difficulty is knowing, at scale and across failures, which files have been read. A hand-built list-and-compare loop pays for the full history on each run and splits its state across two commits. A good design keeps the bookkeeping in durable storage, ties it to the output commit, and avoids re-discovering old files. The next chapter introduces the cloudFiles source that does this.
Exercise
Your hourly job lists a landing folder with 8 million files, compares the listing with a ledger table, loads the new files, and then appends their paths to the ledger. Name two separate problems with this design and one thing that goes wrong if the job crashes between the load and the ledger update.
Show answer
First, listing cost grows with the whole folder, not with the new files. At 1,000 keys per request, 8 million files need about 8,000 list calls every hour, even if only a few files arrived. Second, the ledger grows without bound, and comparing it against the full listing gets slower over time (collecting it to the driver also risks running out of memory). If the job crashes after the load but before the ledger update, the data is already in the Delta table while the ledger doesn't list those files. The next run loads them again and creates duplicate rows.
Exercise
A teammate proposes fixing the problem by remembering the newest modification time seen and listing only files modified after it. Describe a case where this loses data.
Show answer
A file that becomes visible after the cursor has moved past its modification time is skipped permanently. For example, a producer finishes writing a file with a timestamp of 10:00, but it appears in the listing at 10:05. If a run at 10:03 advanced the cursor to 10:03, the file is older than the cursor and is never picked up. Clock skew between writers causes the same loss.