Medallion Architecture on Databricks, End to End
Build bronze, silver and gold on Databricks with Auto Loader, MERGE and liquid clustering, plus the mistakes that break it in production.
Bronze keeps what arrived, silver keeps what is correct, gold keeps what the business asked for. Here is how to build all three on Databricks without the usual mess.
TL;DR
- Medallion is a contract about trust, not a folder structure. Each layer promises its readers something different.
- Bronze is append-only and never cleaned. That is the only reason you can replay silver after a bug.
- Silver is where the real engineering lives: types, deduplication, MERGE on a business key, constraints.
- Every gold table answers one question for one named owner. If nobody owns it, drop it.
- On current Databricks, use Unity Catalog managed tables with liquid clustering and stop hand-tuning partitions.
The problem
NorthBridge Retail, a fictional chain with 400 stores, receives order files every night. They land between 1 a.m. and 5 a.m. Some arrive twice, and a few stores resend corrected files days later.
Analysts query the same folder the files land in. On Monday the sales dashboard shows revenue 6% above the finance report, because Saturday's resent files were counted twice. Nobody can say which number is right. Nobody can rebuild last week either, because the load job overwrote the originals.
None of this is a Spark problem. It is a layout problem: raw, cleaned and reported data share one place and one set of rules. Medallion architecture fixes that by giving each stage its own tables and its own promise to the people who read it.
Key concepts
Data moves in one direction, and each hop makes a stronger promise than the one before it. The layers are schemas in one Unity Catalog catalog — northbridge.bronze, northbridge.silver, northbridge.gold — and grants follow the layers, so analysts never see bronze.
| Concept | What it means | Why it matters here |
|---|---|---|
| Auto Loader | Incremental file ingestion that remembers which files it has read | A file that lands twice under the same path is loaded once |
| Checkpoint | The stream's saved progress | Restarts continue where they stopped, no manual watermark table |
| MERGE | Upsert by key into a Delta table | Resent store files update rows instead of duplicating them |
| Liquid clustering | Data layout by chosen columns, replaces partitioning and ZORDER | Keys can change later without rewriting the table design |
| Managed table | Unity Catalog owns the files | Databricks can compact and vacuum it for you |
Step-by-step implementation
Environment for all code: Databricks Runtime 16.4 LTS, Unity Catalog enabled, PySpark and Databricks SQL. The catalog and the three schemas already exist.
Step 1 — Bronze: load exactly what arrived
Bronze has one job: capture every file once, unchanged, with enough metadata to trace a row back to its file. No casting, no filtering, no joins.
from pyspark.sql import functions as F
landing = "/Volumes/northbridge/landing/raw/orders"
chk = "/Volumes/northbridge/landing/raw/_checkpoints/bronze_orders"
(spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("cloudFiles.schemaLocation", f"{chk}/schema")
.option("cloudFiles.schemaEvolutionMode", "rescue")
.option("header", "true")
.load(landing)
.select(
"*",
F.col("_metadata.file_path").alias("_source_file"),
F.current_timestamp().alias("_ingested_at"),
)
.writeStream
.option("checkpointLocation", chk)
.trigger(availableNow=True)
.toTable("northbridge.bronze.orders"))Two choices here do most of the work. Without type inference, Auto Loader reads every CSV column as a string, so a bad value can never fail the load. And rescue mode parks unexpected columns in _rescued_data instead of stopping the stream.
availableNow processes whatever is waiting and then shuts down. You get streaming bookkeeping at batch cost.
Step 2 — Silver: make it correct
Create the table once, with the rules written into it.
CREATE TABLE IF NOT EXISTS northbridge.silver.orders (
order_id BIGINT NOT NULL,
store_id STRING,
amount DECIMAL(12,2),
order_date DATE,
updated_at TIMESTAMP
) CLUSTER BY (order_date);
ALTER TABLE northbridge.silver.orders
ADD CONSTRAINT valid_amount CHECK (amount >= 0);Then read bronze as a stream and upsert each micro-batch.
from delta.tables import DeltaTable
from pyspark.sql import Window, functions as F
def upsert_orders(batch_df, batch_id):
latest = Window.partitionBy("order_id").orderBy(F.col("updated_at").desc())
clean = (batch_df
.withColumn("order_id", F.col("order_id").cast("bigint"))
.withColumn("amount", F.col("amount").cast("decimal(12,2)"))
.withColumn("order_date", F.to_date("order_date"))
.withColumn("updated_at", F.to_timestamp("updated_at"))
.filter("order_id IS NOT NULL AND amount >= 0")
.withColumn("rn", F.row_number().over(latest))
.filter("rn = 1")
.select("order_id", "store_id", "amount", "order_date", "updated_at"))
target = DeltaTable.forName(batch_df.sparkSession, "northbridge.silver.orders")
(target.alias("t")
.merge(clean.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll(condition="s.updated_at > t.updated_at")
.whenNotMatchedInsertAll()
.execute())
(spark.readStream.table("northbridge.bronze.orders")
.writeStream
.foreachBatch(upsert_orders)
.option("checkpointLocation",
"/Volumes/northbridge/landing/raw/_checkpoints/silver_orders")
.trigger(availableNow=True)
.start())The row_number step is not optional. MERGE fails if two source rows match the same target row, and a store that sends the same order twice in one night will do exactly that.
The s.updated_at > t.updated_at condition makes the job safe to rerun. Replaying an old file never overwrites a newer row.
Step 3 — Gold: answer one question
The finance team asks for daily revenue by store. That is one gold table.
CREATE OR REPLACE TABLE northbridge.gold.daily_store_sales
CLUSTER BY (order_date) AS
SELECT
order_date,
store_id,
COUNT(*) AS order_count,
SUM(amount) AS revenue
FROM northbridge.silver.orders
GROUP BY order_date, store_id;A full rebuild is fine while the table is small. When it starts to hurt, switch to a materialized view or an incremental MERGE, and leave the consumers untouched.
From production: gotchas and lessons
The pattern is simple on a whiteboard. These are the places it bends in real projects.
- Symptom: Gold revenue jumps after a source resends a file. Cause: Silver was loaded with an append, so corrected rows became extra rows. Fix: MERGE on the business key with a newer-wins condition, and deduplicate inside the batch first.
- Symptom: The bronze job fails one morning with a schema change error, with no code change on your side.
Cause: The source added a column and the stream was left on the default evolution mode, which stops on new columns.
Fix: Pick the mode on purpose. With rescue, the load keeps running; add an alert when
_rescued_datais not null. - Symptom: A silver bug is found and there is nothing to replay from. Cause: Someone tidied bronze: filtered bad rows, removed duplicates, or deleted landing files early. Fix: Treat bronze as evidence. Write a retention period per layer and never run business logic there.
- Symptom: Sixty gold tables and three definitions of revenue. Cause: Every dashboard request got its own table, each with its own filter. Fix: Each gold table needs a named owner and a named consumer. Define shared measures once, then reuse them.
Performance and cost notes
- Layout: Databricks now recommends liquid clustering for new tables in place of partitioning and ZORDER. Cluster on the columns your readers filter by, or use
CLUSTER BY AUTOon managed tables and let the platform choose. - Maintenance: Predictive optimization runs
OPTIMIZEandVACUUMon Unity Catalog managed tables. Check that it is enabled before you schedule your own jobs. It is billed as serverless jobs compute. - Compute: A nightly feed does not need an always-on stream.
availableNowon a job cluster does the same work and stops. - Rebuilds: Bronze to silver should always be incremental. Gold can be rebuilt in full until its runtime becomes a problem.
- Small files: Hundreds of tiny store files per night are fine in the landing volume. They are a problem only if bronze is never compacted.
When not to use this
Three layers are a default, not a law. Databricks' own documentation calls the pattern a recommended practice, not a requirement.
- One small source, one consumer: Two layers are enough. A silver table that only renames columns is ceremony.
- Sub-second operational lookups: Layer hops add latency. Serve those from an operational store and feed the lakehouse from it.
- A fourth or fifth layer: Add one only when it has its own readers and its own promise. Extra layers without a contract just move the mess.
Checklist
- Bronze, silver and gold are separate schemas with separate grants
- Bronze is append-only and carries source file and ingestion time
- Every silver table has a business key, a MERGE and at least one constraint
- Every gold table has a named owner and a named consumer
- Each layer has a written retention period
- A silver table can be rebuilt from bronze, and you have tried it once
Practice
- Add a
store_regioncolumn to the landing files and confirm it lands in_rescued_data, not in a failed job. - Resend one order with a later
updated_atand a different amount. Check that silver holds one row and gold revenue moved by the difference. - Truncate silver, reset its checkpoint and rebuild it from bronze. Compare row counts before and after.
- Try: Build an SCD Type 2 with MERGE
Watch
Further reading
- What is the medallion lakehouse architecture? (Databricks docs)
- Use liquid clustering for tables (Databricks docs)
- Predictive optimization for Unity Catalog managed tables (Databricks docs)
- Designing a Medallion Framework: A Decision Guide (Azure Architecture Blog)
Next in this series: Medallion Architecture in a Fabric Lakehouse.
Keep going
Medallion Architecture in a Fabric Lakehouse
Build bronze, silver and gold in one Fabric lakehouse with schemas and materialized lake views, plus the gotchas that hit in production.
Build an SCD Type 2 with MERGE
Apply a day's customer address changes to a dimension table, closing old versions and inserting new ones, in a single MERGE.
Medallion Architecture Checklist
A printable checklist for designing and reviewing bronze, silver and gold layers — naming, quality gates, ownership and the questions to ask at each hop.
One practical note a week
Get new articles, problems and guides in your inbox.
Thanks! You're on the list. (Local demo — no email provider is wired up yet.)