Bronze, silver, gold
Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.
Monday, 11:00. One question is on the table: how many orders did SwiftKart take in the first week of June? Tess counted the landing files and says 68. The product team removed duplicates their own way and says 41. The dashboard says 40. All three started from the same eight files. Nora looks at you: "Which one is right, and why are there three?"
You'll learn to
- Say what belongs in bronze, silver and gold, and who reads each
- Build the three layers for SwiftKart orders
- Explain how Auto Loader loads each file exactly once
- Choose what happens when a new column arrives
Learn
Three teams, three numbers
All three are honest counts. Tess counted every row in the landing files. The product team dropped duplicates by a rule of their own. The dashboard used a third rule. Three teams cleaned the same raw files three ways.
The fix is to clean once, in tables everyone shares, in three steps. Think of a restaurant kitchen. Deliveries are stored exactly as they arrive. A prep station washes and cuts. The pass sends out finished plates.
- Bronze: the data exactly as it arrived, plus where and when it came from.
- Silver: cleaned. One row per real thing, such as one row per order with its latest status.
- Gold: shaped for one use: a dashboard, a report, a model's features.
This layout is called a medallion pipeline.
One order through the layers
Bronze, silver and gold layers side by side, with sample order rows changing at each step: raw duplicates in bronze, one clean row per order in silver, daily totals in gold.
Step through it and follow one order: several raw rows in bronze, one clean row in silver, a daily total in gold.
The three layers at SwiftKart
| Layer | What it holds | Rules | SwiftKart orders |
|---|---|---|---|
| Bronze | Every landing row as it arrived, plus sourcefile | Append only; never clean, never delete | 68 rows from 8 files, retry file included |
| Silver | One row per order, latest version, right types | Deduplicate, fix types, check keys | 40 rows |
| Gold | Answers for one audience | Aggregates, business names | Orders per day |
Read the last column: 68 was a count of bronze, and 40 is the number of real orders.
Bronze: keep everything, fix nothing
Bronze has one rule: append only. Never clean, never delete. Every landing row goes in as it arrived, the retry file's duplicates included.
That sounds wasteful until silver has a bug. If bronze had already thrown rows away, the only fix would be asking the source to send months of data again. With bronze untouched, you fix the silver code and rebuild.
Bronze adds one thing of its own: where each row came from. In the next card that is the _source_file column.
Bronze: land everything, add where it came from
import duckdb
import minidelta
bronze = minidelta.DeltaTable('lake/bronze/orders')
bronze.write("""
SELECT * EXCLUDE (filename), filename AS _source_file
FROM read_csv_auto('landing/orders/*.csv', filename = true)
""")
bronze.register('bronze_orders')
print('bronze rows:', bronze.count())
print(duckdb.sql("""
SELECT _source_file, COUNT(*) AS rows
FROM bronze_orders
GROUP BY 1
ORDER BY 1
""").fetchall()[:3])
There is Tess's 68. filename = true adds the path of the file each row came from. Keeping it in bronze is what lets you answer "where did this bad row come from?" a month later.
One row per order, then one answer
Silver answers "what is true now?". It keeps one row per order: the latest. For each order_id, sort the bronze rows by updated_at, newest first, and keep the first one. That is the dedup from Module 2. The retry file's copies tie on updated_at, so the file name breaks the tie.
Gold answers one audience's question. Here: how many orders were placed each day? It reads silver, never bronze, so every order is counted once.
Everyone who reads silver or gold now gets the same number.
Silver and gold
import duckdb
import minidelta
bronze = minidelta.DeltaTable('lake/bronze/orders')
bronze.write("""
SELECT * EXCLUDE (filename), filename AS _source_file
FROM read_csv_auto('landing/orders/*.csv', filename = true)
""")
bronze.register('bronze_orders')
silver = minidelta.DeltaTable('lake/silver/orders')
silver.write("""
SELECT order_id, customer_id, order_ts, status, updated_at
FROM bronze_orders
QUALIFY ROW_NUMBER() OVER (
PARTITION BY order_id ORDER BY updated_at DESC, _source_file DESC) = 1
""")
silver.register('silver_orders')
gold = minidelta.DeltaTable('lake/gold/orders_by_day')
gold.write("""
SELECT strftime(order_ts, '%Y-%m-%d') AS order_date, COUNT(*) AS orders
FROM silver_orders
GROUP BY 1
""")
print('bronze', bronze.count(), '| silver', silver.count(), '| gold', gold.count())
print(gold.read().order('order_date').fetchall())
QUALIFY filters on a window function, here "keep the latest row per order": the Module 2 dedup in one clause. Gold counts each order once, on the day it was placed.
Order 1002 through the layers
| Layer | Rows for order 1002 | Why |
|---|---|---|
| Bronze | placed from 2025-06-01.csv, shipped from 2025-06-02.csv | Each drop that mentions it adds a row |
| Silver | One row: shipped | The latest updatedat wins |
| Gold | Counted once in 2025-06-01 | Counted on the day it was placed |
Remember: bronze keeps everything, silver keeps one true row, gold answers one question.
The loader that must never load twice
One thing in the bronze code would not survive real life: it reads the whole landing folder on every run. Real folders grow forever. Bronze must load only the files it has not seen, and never the same file twice, even when the job crashes half-way.
On Databricks that loader is Auto Loader. It works in small rounds called micro-batches. In each one it:
- finds candidate files in the folder;
- checks each path against its list of files already seen, and keeps the new ones;
- writes them to the bronze table in one commit, stamped with the batch number;
- notes the batch as done.
The list and the notes live in a folder called the stream's checkpoint. (Same word, different thing: this is not the checkpoint inside _delta_log from Lesson 13.2.)
One Auto Loader micro-batch
A flow from the landing folder, through discovery by directory listing or a file events queue, to a RocksDB store of seen paths in the checkpoint, then a Delta commit to the bronze table, which is then recorded in the checkpoint offsets and commits.
Follow the arrows from the landing folder to the bronze table: find, check, write, mark done. The stamp in step 3 is a txn action in the Delta commit, holding the id of the stream and the batch number.
List the folder, or listen for events
Look at the two boxes in the Discovery column. They are two ways to do step 1.
Directory listing is the default. It needs only read access, but it lists the folder for every batch, and that cost grows with everything that ever landed. S3 returns at most 1,000 keys per LIST request, so:
- a folder of 2,000,000 files
- needs 2,000,000 / 1,000 = 2,000 requests for one full listing.
File notification mode has the storage announce each new file on a queue. A batch then reads a short list of new paths, however big the folder is. Databricks recommends it for most workloads.
Neither mode promises the order in which files are processed. Never rely on file order for correctness.
A crash between the write and the note
A micro-batch finds two new files and writes them to the bronze table in one commit stamped with batch 2; the job crashes before the checkpoint notes the batch; on restart the batch is replayed, the table finds its stamp and skips the write, and the checkpoint catches up.
Batch 2 starts. Six files went in with batches 0 and 1. Auto Loader finds two paths that are not in its seen list and offers them to batch 2.
Write. One Delta commit adds the rows of both files to bronze. The same commit carries a
txnaction: this stream, batch 2.Crash. The job dies before it can note batch 2 as done. The table has the rows. The checkpoint does not know that.
Restart. Auto Loader replays batch 2 with the same two files. The table finds
txnbatch 2 already there and skips the write. Then the checkpoint catches up. Every file is in bronze exactly once.
Watch the Checkpoint box and the bronze.orders box fall out of step and back in. Loading each file exactly once takes both: the seen list offers a file to one batch only, and the txn stamp makes a replayed batch harmless.
The Auto Loader idea, by hand
import glob
import json
import os
import minidelta
def ingest(pattern, table, checkpoint, max_files):
"""One availableNow run: load unseen files, at most max_files per micro-batch."""
state = json.load(open(checkpoint)) if os.path.exists(checkpoint) else {'seen': [], 'batch': 0}
new = sorted(p for p in glob.glob(pattern) if p not in set(state['seen']))
for start in range(0, len(new), max_files):
batch = new[start:start + max_files]
files = ', '.join(f"'{p}'" for p in batch)
table.write(f"""SELECT * EXCLUDE (filename), filename AS _source_file
FROM read_csv_auto([{files}], filename = true)""",
txn=('bronze-orders', state['batch'])) # at most once per batch id
print('batch', state['batch'], 'loaded', len(batch), 'files')
state['seen'] += batch
state['batch'] += 1
with open(checkpoint, 'w') as f: # then mark the batch done
json.dump(state, f)
return len(new)
bronze = minidelta.DeltaTable('lake/bronze/orders')
print('run 1:', ingest('landing/orders/*.csv', bronze, 'checkpoint.json', max_files=3), 'new files')
print('run 2:', ingest('landing/orders/*.csv', bronze, 'checkpoint.json', max_files=3), 'new files')
print('bronze rows:', bronze.count(), '| last batch in the table:', bronze.txn_version('bronze-orders'))
Eight files in batches of three: 3, 3 and 2. The second run finds nothing new. Had the run died after a write but before saving the checkpoint, the retry would replay that batch id, and txn would make the write a no-op. A real stream's id lives in its checkpoint, so deleting the checkpoint gives a new id and loads every file again.
Remember: the checkpoint knows which files were seen. The txn stamp in the table makes a replay harmless. Never delete a checkpoint, and never share one between two streams.
Auto Loader into bronze on Databricks
Runs on Databricks:
(spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("cloudFiles.schemaLocation", "/Volumes/workspace/default/checkpoints/orders_schema")
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.option("cloudFiles.maxFilesPerTrigger", 1000)
.option("header", "true")
.load("/Volumes/workspace/default/landing/orders/")
.selectExpr("*", "_metadata.file_path AS _source_file")
.writeStream
.option("checkpointLocation", "/Volumes/workspace/default/checkpoints/orders")
.trigger(availableNow=True)
.toTable("workspace.bronze.orders"))
Find the two folders: schemaLocation and checkpointLocation. Run it twice and the second run loads nothing. Drop a new CSV into the folder, run again, and only that file is loaded. availableNow processes everything new in batches of maxFilesPerTrigger, then stops: a batch job with streaming's bookkeeping.
A new column arrives at 06:02
One more surprise is waiting in the landing folder. Next month the supplier adds a coupon_code column, and at 06:02 the bronze job stops with UnknownFieldException.
Auto Loader stores the columns it expects in its schema location. The setting cloudFiles.schemaEvolutionMode decides what happens when a file brings a column that is not there:
addNewColumns(the default): add the column to the stored schema, then stop.rescue: never change the schema. Unknown columns go into a column called_rescued_data.failOnNewColumns: stop until someone updates the schema.none: ignore new columns.
The default stops the stream on purpose. Why would a loader do that?
The stop is the mechanism
Five steps: a file brings a new column, Auto Loader adds it to the stored schema, the stream stops with UnknownFieldException, the job retries, and the stream restarts with the new schema.
Read it top to bottom. With retries on the job, the red step heals itself. Without retries, bronze stays stopped until someone restarts it.
The whole pipeline, declared
Runs on Databricks:
CREATE OR REFRESH STREAMING TABLE bronze_orders AS
SELECT *, _metadata.file_path AS _source_file
FROM STREAM read_files('/Volumes/workspace/default/landing/orders/', format => 'csv');
CREATE OR REFRESH MATERIALIZED VIEW silver_orders (
CONSTRAINT valid_id EXPECT (order_id IS NOT NULL) ON VIOLATION DROP ROW
) AS
SELECT * FROM bronze_orders
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) = 1;
CREATE OR REFRESH MATERIALIZED VIEW gold_orders_by_day AS
SELECT DATE(order_ts) AS order_date, COUNT(*) AS orders
FROM silver_orders
GROUP BY ALL;
The same three layers, with no loop and no checkpoint code. This is a Lakeflow Declarative Pipeline, the feature formerly called Delta Live Tables. You declare each table as a query; Databricks works out the order, manages the Auto Loader checkpoints, and records how many rows each expectation dropped.
The trap: cleaning in bronze, or letting people read it. If bronze drops or fixes rows, you can never replay the raw data after you find a bug in silver. And a dashboard reading bronze counts the retry file twice. Bronze is for the pipeline. People read gold, and sometimes silver.
Numbers to remember
| Thing | Value | What it means |
|---|---|---|
| cloudFiles.maxFilesPerTrigger | 1,000 | The most new files one micro-batch takes |
| The seen list | A RocksDB key-value store | It lives in the stream's checkpoint, with every path already discovered |
| The txn action | Stream id and batch number | Written in the same commit as the data. If the job dies before the batch is noted, the replay finds it and is skipped |
| S3 LIST | 1,000 keys per request | What a directory listing pays, for every batch |
| File names that sort by time | Date-prefixed | Auto Loader detects the lexical order and makes far fewer LIST calls |
| File events on a Unity Catalog external location | Runtime 14.3 LTS and above | Databricks manages the notification queue for you |
| Schema inference | The first 50 GB or 1,000 files, whichever comes first | The result is stored under schemas in cloudFiles.schemaLocation |
| CSV and JSON columns | Inferred as strings | Unless you set cloudFiles.inferColumnTypes or give cloudFiles.schemaHints |
| rescueddata | A JSON string | Values that did not fit (unknown columns, type or case mismatches), with the source file path |
Medallion is a convention, not a standard. Some teams say raw, staged and curated; dbt projects say staging and marts. What matters is the contract per layer, often visible in the names: prod.bronze.orders, prod.silver.orders, prod.gold.daily_revenue. And gold is often a star schema (Module 5): medallion says how clean the data is, not how it is modelled.
What changed at SwiftKart
By the afternoon all three teams read one table, gold.orders_by_day, built from silver's 40 orders. Tess's 68 turned out to be a count of bronze rows. The answer to Nora's question is 40, and nobody recounts the landing files.
Bronze is now fed by a loader that takes each file once, survives a crash, and copes with a new column.
One weak spot is left: you. Somebody still has to press Run every morning, in the right order. Lesson 13.6 hands that to a scheduled job, with retries and an alert when it fails.
In one line
Bronze keeps raw data as it arrived, silver one clean row per thing, gold a shape for one use; Auto Loader feeds bronze each new file exactly once, with a list of seen files in its checkpoint and a txn stamp on every batch it commits.
Interview corner
What is the medallion architecture, and why keep bronze if silver is the clean copy?
Bronze holds raw data as it arrived, append only, with ingestion metadata such as the source file; silver is typed, deduplicated and conformed, one row per entity; gold is shaped for a use, often aggregates or star schemas. Bronze exists because silver logic will have bugs: with raw data kept unchanged you fix the code and rebuild silver without asking the source to resend months of data, and you can answer audit questions about what arrived when.
How does Auto Loader load each file exactly once?
Each micro-batch discovers candidate files, checks them against a RocksDB key-value store of seen paths in the stream checkpoint, and takes up to cloudFiles.maxFilesPerTrigger (1,000 by default) new ones. The Delta sink commits the batch with a txn action holding the stream id and batch id, and only then is the batch marked done in the checkpoint. If the job dies in between, the replay finds that batch id in the table and skips the write. Deleting the checkpoint gives the stream a new id, so every file is loaded again.
Directory listing or file notification mode?
Listing needs only read access but lists the whole input path every batch, so it degrades as the folder grows: at 1,000 keys per S3 LIST request, 2 million files cost 2,000 requests per listing. Lexically ordered, date-prefixed names soften that. File notification reads new paths from a cloud queue, so cost follows new files; with file events on a Unity Catalog external location Databricks manages the queue and recommends it for most workloads. Either way, file order is not guaranteed.
A new column appears in the landing files. What does Auto Loader do?
With the default addNewColumns mode it adds the column to the schema stored under _schemas and stops the stream with UnknownFieldException; the restart, usually a job retry, continues with the new column. rescue keeps the schema fixed and puts unknown fields in _rescued_data, failOnNewColumns stops until a human updates the schema, and none ignores them. I choose per source: rescue for noisy feeds, add for trusted ones, and alert either way, because a rename looks like a new column.