Sub topic 5
Ingesting files into bronze with Auto Loader
This chapter shows how to load raw files from cloud storage into a bronze Delta table with Auto Loader. It assumes you know basic PySpark DataFrames, can read a Structured Streaming readStream/writeStream pair, and understand what the bronze layer is for (raw, append-only, replayable data). You also need a Databricks workspace with Unity Catalog and a volume you can write to.
What Auto Loader does
Auto Loader is a Databricks source for Structured Streaming. You use it by calling spark.readStream.format("cloudFiles"). It watches a directory in cloud storage or a Unity Catalog volume, finds files it has not seen before, and delivers them as a streaming DataFrame.
A plain batch spark.read.json(path) re-reads every file on each run, so you would have to track which files you already loaded. Auto Loader tracks that for you. It records each discovered file in the checkpoint, so a file is processed once even if the job restarts or runs on a schedule.
Auto Loader also handles three other jobs that matter for bronze:
- File discovery at scale, from a few files per day to millions.
- Schema inference, with a stored schema that can evolve as the source changes.
- Rescued data, which keeps values that do not match the schema instead of dropping them.
A bronze ingestion step
The following code reads JSON order files and appends them to main.bronze.orders. The first statement creates the target schema if it does not exist.
from pyspark.sql import functions as F
spark.sql("CREATE SCHEMA IF NOT EXISTS main.bronze")
raw = (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/sales/checkpoints/orders_schema")
.load("/Volumes/main/sales/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp())
.withColumn("_source_file", F.col("_metadata.file_path"))
)
query = (
raw.writeStream
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_bronze")
.trigger(availableNow=True)
.toTable("main.bronze.orders")
)
query.awaitTermination()Each part of this code has a job:
cloudFiles.formattells Auto Loader the file format of the source files. JSON, CSV, Parquet, Avro, ORC, text, and binary files are supported.cloudFiles.schemaLocationis where Auto Loader stores the schema it infers. It samples your files on the first run and writes the result there. Later runs reuse it._metadata.file_pathis a hidden column that Spark exposes for file-based sources. It gives the full path of the file each row came from. It does not appear inSELECT *on the source, so you must reference it by name._ingested_atrecords when the row was loaded. Together with_source_file, it lets you trace any bronze row back to its origin. This is what makes bronze replayable and debuggable.checkpointLocationstores the stream's progress. Auto Loader keeps its list of processed files here.trigger(availableNow=True)processes everything that is available now, in as many micro-batches as needed, and then stops. You get incremental behavior with batch-style cost, and a job can run it on a schedule.awaitTermination()blocks until the run finishes. Without it, a job task may report success before the data is written.
Use .trigger(processingTime="1 minute") or leave the trigger unset if you want a continuously running stream that picks up files as they arrive.
Keep the schema location and the checkpoint separate
The schema location and the checkpoint are two different paths, and they hold different state. In the example they live side by side under /Volumes/main/sales/checkpoints/. Give each stream its own pair. Two streams that share a checkpoint corrupt each other's progress.
Decide ahead of time what happens if you delete either one:
| What you delete | Effect |
|---|---|
| Checkpoint | Auto Loader forgets which files it processed. With `includeExistingFiles` at its default of true, it re-reads every file and appends duplicates to bronze. |
| Schema location | Auto Loader infers the schema again from a sample. Columns may change type or order compared with the table. |
| Target table only | The checkpoint still says the files were processed, so the new table stays empty. Delete the checkpoint too if you want a full reload. |
Schema inference and evolution
For JSON and CSV, Auto Loader infers every column as a string by default. This is deliberate. Bronze should accept what the source sent, and strings never fail on a bad value like "N/A" in a number field. Typing belongs to the silver layer, where the casts in your SQL or PySpark code set the final types.
If you prefer typed columns in bronze, set cloudFiles.inferColumnTypes to true, or pin selected columns with hints:
raw = (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/sales/checkpoints/orders_schema")
.option("cloudFiles.schemaHints", "order_id BIGINT, amount DECIMAL(12,2)")
.load("/Volumes/main/sales/landing/orders/")
)Source systems change. Suppose a new field coupon_code starts appearing in the files. The behavior depends on cloudFiles.schemaEvolutionMode:
| Mode | Behavior when a new column appears |
|---|---|
| `addNewColumns` (default when no schema is given) | The stream stops with an error, records the new schema, and includes the column after you restart it. |
| `rescue` | The schema stays fixed. New fields go into the `_rescued_data` column as JSON text. |
| `failOnNewColumns` | The stream fails and stays failed until you update the schema or the data. |
| `none` | The schema is not evolved. New fields are ignored unless a rescued data column is set. |
The first mode surprises many people. The stream does not silently adapt. It fails once on purpose, then succeeds on the next start. A Databricks job with retries enabled recovers on its own. Without retries, the first run after a source change will fail.
The rescued data column
When Auto Loader infers a schema, it adds a _rescued_data column. It holds any value that did not fit the schema: a field not in the schema, a value that cannot be cast to the declared type, or a column whose name differs only in letter case. The column stores the value along with the source file path.
Check this column regularly. A bronze table with a steadily growing _rescued_data means the source has changed and silver may be missing fields.
SELECT _source_file, _rescued_data
FROM main.bronze.orders
WHERE _rescued_data IS NOT NULL
LIMIT 20How Auto Loader finds new files
Auto Loader has two discovery modes.
- Directory listing is the default. Each run lists the input path and compares the result against the checkpoint. It needs no extra cloud setup and works well for moderate file counts. It uses incremental listing on lexically ordered paths where it can, so it does not re-list everything.
- File notification or file events uses cloud event services, such as queues fed by storage events, to learn about new files without listing. It scales better for very large directories but needs permissions and setup in your cloud account. For Unity Catalog external locations, Databricks can manage file events for you.
Start with directory listing. Switch only when listing time becomes a measurable share of your run time.
Two options affect which files get picked up:
cloudFiles.includeExistingFilesdefaults totrue. On the first run, files already in the directory are processed. Set it tofalseto ingest only files that arrive after the stream first starts. This setting is read only at the first start, so changing it later has no effect.pathGlobFilterlimits the source to matching file names, for example*.json. This is useful when a directory also holds.tmpor_SUCCESSfiles.
Common errors
- The job succeeds and the table is empty. Check whether a checkpoint from an earlier run already marks the files as processed. Also check that the path has a trailing slash and the right case, and that your principal has
READ VOLUMEon the volume. - The stream fails after a source change. This is
addNewColumnsdoing its job. Restart it, or set up job retries. - Every column is a string in bronze. This is the default for JSON and CSV. Cast in silver, or set hints.
- Duplicate rows after a rerun. A reset checkpoint, or the same file landed under a new name. Bronze keeps both. Silver removes them.
_metadatais not found. Select it explicitly withF.col("_metadata.file_path"). It is not part ofSELECT *.- Old files are re-ingested. The checkpoint is new or was moved. Keep checkpoints in a stable location that you do not clean up.
Exercise
A teammate deletes the checkpoint folder for the orders bronze stream to "fix" a failed run, then reruns the job. The landing directory holds 500 files that were already loaded. What happens to the bronze table, and which later step protects downstream tables?
Show answer
With no checkpoint, Auto Loader has no record of the processed files. Because includeExistingFiles defaults to true, it re-reads all 500 files and appends their rows again, so bronze now holds duplicates. The silver MERGE step, which keeps one row per order_id and upserts, removes the effect of those duplicates in the cleaned tables. A better fix is to leave the checkpoint alone and correct the cause of the failure, such as a schema change handled by restarting the stream.
Exercise
You need all columns in bronze to keep exactly the values the source sent, but you also want amount typed as DECIMAL(12,2) from the start. Which Auto Loader option lets you pin that one column without typing the rest, and where would you keep a value that does not parse as a decimal?
Show answer
Use cloudFiles.schemaHints, for example "amount DECIMAL(12,2)", so only that column is typed and the others stay as inferred strings. A value that cannot be parsed as a decimal is not dropped. Auto Loader places it in the rescueddata column so you can find it later.