Incremental file ingestion
Files keep landing in a folder: exports, logs, partner drops. The job is to load each file exactly once, keep up as volume grows, and survive schema changes. That is incremental ingestion.
Step 4 · Structured Streaming · Silver · Streams into the lakehouse, lesson 2 of 2
On this page
Read first: Structured Streaming basics · Data lake storage: formats and layout (skip if you know them)
In plain words first
A mailroom receives letters all day. A careless clerk opens "everything that came after lunch", and gets it wrong whenever a letter is stamped late or a delivery is slow. A careful clerk keeps a logbook: every letter is written down when it is opened, so none is opened twice and none is missed, whatever the clock says. Incremental ingestion is the careful clerk, and the 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 the logbook.
The problem
The naive job lists the landing folder, compares with what it loaded last time (by file name or modification time), and loads the difference. It works on day one. Then the folder holds millions of files and listing takes longer than loading; a file is written slowly and picked up half-written; a job fails between loading and recording; two runs overlap. Each failure means duplicated or missing data.
The file source as a stream
Structured Streaming treats a folder as a stream of files. The checkpoint writes down which files each micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → read, so each file is loaded once, even across restarts. Run it all the time, or let a scheduler start it with an availableNow triggertrigger: The setting that decides when the next micro-batch starts: straight away, on a fixed interval, or once over everything waiting. Learn more →, which loads everything new and stops:
order_schema = "order_id STRING, customer STRING, amount DOUBLE, order_ts TIMESTAMP" (spark.readStream .format("json") .schema(order_schema) # streams need a schema up front .option("maxFilesPerTrigger", 1000) # bound each micro-batch .load("s3://landing/orders/") .writeStream .format("delta") .option("checkpointLocation", "s3://chk/orders_bronze/") # Spark 3.3+: process what is new, then stop .trigger(availableNow=True) .toTable("bronze.orders"))
- Exactly once comes from the checkpoint plus a transactional sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → such as Delta or Iceberg.
- availableNow gives batch scheduling with streaming bookkeeping: no "what did I load last time" table to maintain. It also respects
maxFilesPerTrigger, splitting a large backlog into several batches. - cleanSource (
archiveordelete) moves or deletes processed files, which keeps the landing folder small. - The catch: the sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → still lists the directory every batch. With millions of files that listing becomes the bottleneck.
Auto Loader and COPY INTO
On Databricks, two tools address the gaps. They are proprietary features of that platform, but the ideas show up in interviews generally.
Auto Loader (cloudFiles) | COPY INTO | |
|---|---|---|
| Interface | A streaming source: spark.readStream.format("cloudFiles") | A SQL command run as a batch |
| Discovering files | Directory listing, or file notification mode using cloud events and a queue, which avoids listing entirely | Lists the source path each run |
| Tracking | Checkpoint with a scalable key-value store of processed files | Table metadata records loaded files; reruns skip them |
| Schema | Infers and stores the schema, evolves it when new columns appear, and puts unexpected values in _rescued_data | Explicit or inferred per run |
| Fits | Continuous or frequent ingestion, millions of files | Simple, occasional loads of thousands of files |
Schema drift and bad records
New columns
Type changes and junk
Raw first
Backfills and late files
A stream only processes files it has not seen. To reprocess history (a parsing bug, a new column), start a new checkpoint into a new or truncated target, or run a separate batch backfill over a date range and keep the stream for new data. Never delete the checkpoint of a running pipeline casually: it will reload everything into the same target and duplicate it.
ingest_date=2025-03-01/) even if the data has its own event dates. Late-arriving files then simply land in today's folder, and backfills can target specific ingestion dates.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 Delta Lake, with spark already created: each builds its own data.
Goal: Load each new file exactly once on a schedule, recording which file every row came from.
import os from pyspark.sql import functions as F os.makedirs("lab/ingest/landing", exist_ok=True) def partner_drop(name, lines): with open(f"lab/ingest/landing/{name}.csv", "w") as f: f.write("order_id,amount\n" + "\n".join(lines)) def scheduled_run(): (spark.readStream .schema("order_id INT, amount DOUBLE") .option("header", "true") .csv("lab/ingest/landing") .withColumn("source_file", F.col("_metadata.file_name")) .withColumn("loaded_at", F.current_timestamp()) .writeStream.format("delta") .option("checkpointLocation", "lab/ingest/_checkpoint") .trigger(availableNow=True) # process what is new, then stop .start("lab/ingest/bronze") .awaitTermination()) partner_drop("drop_001", ["1,10.0", "2,20.0"]) scheduled_run() partner_drop("drop_002", ["3,30.0"]) scheduled_run() scheduled_run() # nothing new: loads nothing bronze = spark.read.format("delta").load("lab/ingest/bronze") bronze.groupBy("source_file").count().orderBy("source_file").show()
Output from a real run
+------------+-----+ | source_file|count| +------------+-----+ |drop_001.csv| 2| |drop_002.csv| 1| +------------+-----+
What to notice:
- Three runs, two files, three rows: each file was loaded once, and the third run found nothing new.
source_fileshows where every row came from.- There is no "what did I load last time" table to maintain: the checkpoint keeps track.
Common mistakes
- Tracking loaded files by modification time — Clock skewskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more →, slow writers and copied files break it. Use a source that records processed files.
- Picking up files while they are still being written — Writers should write to a temporary name or folder and rename or move when done.
- Deleting the checkpoint to "fix" a stream — Everything is reprocessed into the same target: duplicates.
- Inferring the schema on every batch run — The schema changes with whatever files happen to arrive.
Key takeaways
- A streaming file source with a checkpoint loads each file exactly once.
- trigger(availableNow=True) gives scheduled batch runs with streaming bookkeeping.
- Auto Loader adds notification-based discovery and schema evolution; COPY INTO is an idempotent batch load (both Databricks).
- Land raw first, keep bad records visible, and backfill with a new checkpoint.
Interview prep
THE QUESTION
"Partners drop CSV files into S3 all day. Design an ingestion that loads each file exactly once into a Delta table."
Avoid: "store the last run time and load files modified after it". Clock skew, slow writers and copied files make it skip or double-load files.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between trigger(once=True) and trigger(availableNow=True)?"
maxFilesPerTrigger, which can be huge after a backlog. availableNow (Spark 3.3+) splits the backlog into several bounded batches, and replaces once, which is deprecated.Scenario"A parsing bug corrupted the last two weeks in bronze. How do you reload those files?"
Trap"The file source detects when an existing file is overwritten and reloads it."
Check yourself
3 questionsWhat makes the file source process each file only once across restarts?
Show the answer
The checkpoint log of processed files, plus a transactional sink. The checkpoint records processed files per batch; the sink commits atomically.
What does trigger(availableNow=True) do?
Show the answer
Processes all new data, possibly in several batches, then stops. It turns a stream into an incremental batch job.
Why can a plain file stream slow down as a landing folder grows?
Show the answer
Each batch lists the directory, and listing millions of files is slow. Listing cost grows with the folder; archive processed files or use notifications.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Kafka in depth · 7 min readKafka producers: acks, retries and batching
How the key picks a partition, what acks and the idempotent producer protect against, batching and compression, and writing to Kafka from Spark.
Related lessons
Structured Streaming basicsStructured Streaming · 7 min read
Streaming into Delta tablesData lake & lakehouse · 6 min read
The medallion architecture
Previous: Streaming into Delta tables
Primary sources: Structured Streaming: file source · Databricks Auto Loader