The medallion architecture
Most lakehouses organise data in three layers: bronze for raw data, silver for cleaned data, gold for business-ready tables. This lesson shows what belongs in each layer, walks one pipeline through all three, and points out where the pattern goes wrong.
Step 3 · Data lake & lakehouse · Bronze · Table formats, lesson 3 of 3
On this page
Show code in
Every code block on the page follows this.
Read first: Lake, warehouse, lakehouse (skip if you know it)
In plain words first
Think of a kitchen: groceries arrive and go straight into the pantry as they are (bronze). The cook washes, chops and portions them (silver). The finished dish goes to the table (gold). If a dish tastes wrong, you can go back to the pantry and start again, because the raw ingredients were kept.
The three layers
| Layer | Holds | Typical operations | Consumers |
|---|---|---|---|
| Bronze | Raw data, as close to the source as possible, plus ingestion metadata | Append-only loads, minimal parsing, add load timestamp and source file | Data engineers, reprocessing |
| Silver | Validated, deduplicated, typed and joined data at the entity level | Type casting, deduplication, MERGE of CDC, conforming keys, quality checks | Engineers, analysts, data scientists |
| Gold | Business-ready tables: facts and dimensions, aggregates, features | Aggregations, business logic, star schemas | BI dashboards, reports, ML, applications |
Walk through one pipeline
Bronze · land raw
bronze.orders_raw exactly as received, plus an _ingested_at column (when this pipeline read the record) and a _source column (the Kafka topic). Malformed records are kept, not dropped: bronze is your replayable history.The command
raw = (spark.readStream.format("kafka") .option("kafka.bootstrap.servers", "broker:9092") .option("subscribe", "orders").load()) (raw.selectExpr("CAST(value AS STRING) AS json", "current_timestamp() AS _ingested_at", "topic AS _source") .writeStream.option("checkpointLocation", "s3://chk/orders_raw/") .toTable("bronze.orders_raw"))
Silver · clean and merge
order_id keeping the latest event (the latest_order_events view below), and MERGE into silver.orders so it holds one current row per order.The command
spark.sql(""" MERGE INTO silver.orders t USING latest_order_events s ON t.order_id = s.order_id WHEN MATCHED AND s.event_ts > t.event_ts THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT * """)
MERGE INTO silver.orders t USING latest_order_events s ON t.order_id = s.order_id WHEN MATCHED AND s.event_ts > t.event_ts THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *
Gold · serve
gold.daily_revenue by date and region, and gold.fct_orders joined to customer and product dimensions. These are the tables dashboards query.The command
spark.sql(""" CREATE OR REPLACE TABLE gold.daily_revenue AS SELECT order_date, region, SUM(amount) AS revenue, COUNT(*) AS orders FROM silver.orders JOIN silver.customers USING (customer_id) GROUP BY order_date, region """)
CREATE OR REPLACE TABLE gold.daily_revenue AS SELECT order_date, region, SUM(amount) AS revenue, COUNT(*) AS orders FROM silver.orders JOIN silver.customers USING (customer_id) GROUP BY order_date, region
Why layers help
- Reprocessing: when silver logic has a bug, rebuild silver from bronze instead of re-extracting from source systems.
- Clear contracts: consumers know gold is curated and stable; bronze carries no guarantees.
- Separation of concerns: ingestion, cleaning and business logic change at different speeds and are owned by different people.
- Debugging: you can compare each layer to find where a number went wrong.
Where it goes wrong
- Layers as a rule, not a tool — Not every dataset needs three copies. A clean source table can go straight to silver.
- Business logic in bronze — Transforming on ingestion destroys the raw record you need for replays.
- Gold tables that copy silver — Gold should add value: aggregation, modelling, business rules.
- No retention on bronze — Raw data grows forever; set retention, but keep enough history to rebuild silver.
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: Build a bronze, silver and gold pipeline that gives the same result however many times it runs.
import json, os from pyspark.sql import Window, functions as F os.makedirs("lab/medallion/landing", exist_ok=True) landed = [ {"id": 1, "city": "Pune", "amount": "120.5", "ts": "2025-03-01 09:00:00"}, # later change {"id": 1, "city": "Pune", "amount": "130.0", "ts": "2025-03-01 10:00:00"}, # bad amount {"id": 2, "city": "Delhi", "amount": "n/a", "ts": "2025-03-01 09:30:00"}, {"id": 3, "city": "Pune", "amount": "75", "ts": "2025-03-01 11:00:00"}, ] with open("lab/medallion/landing/2025-03-01.json", "w") as f: f.write("\n".join(json.dumps(r) for r in landed)) def bronze(): """Raw records as they arrived, with where and when they came from.""" (spark.read.json("lab/medallion/landing") .withColumn("_source", F.col("_metadata.file_name")) .withColumn("_loaded_at", F.current_timestamp()) .write.format("delta").mode("overwrite").save("lab/medallion/bronze")) def silver(): """Typed, validated, one row per order: the latest change.""" latest = Window.partitionBy("id").orderBy(F.col("ts").desc()) (spark.read.format("delta").load("lab/medallion/bronze") .withColumn("amount", F.expr("try_cast(amount AS DOUBLE)")) .where(F.col("amount").isNotNull()) .withColumn("rn", F.row_number().over(latest)).where("rn = 1") .drop("rn", "_source", "_loaded_at") .write.format("delta").mode("overwrite").save("lab/medallion/silver")) def gold(): """What the business reads.""" (spark.read.format("delta").load("lab/medallion/silver") .groupBy("city") .agg(F.round(F.sum("amount"), 2).alias("revenue"), F.count("*").alias("orders")) .write.format("delta").mode("overwrite").save("lab/medallion/gold")) for run in range(2): # running the pipeline twice changes nothing bronze(); silver(); gold() spark.read.format("delta").load("lab/medallion/gold").orderBy("city").show()
Output from a real run
+----+-------+------+ |city|revenue|orders| +----+-------+------+ |Pune| 205.0| 2| +----+-------+------+
What to notice:
- Gold shows only Pune: 130.0 (order 1's latest change) + 75.0 = 205.0, from 2 orders.
- Order 2 (Delhi) was dropped in silver because its amount
n/ais not a number, but it is still in bronze, so it can be fixed and reprocessed. - The pipeline ran twice and the result did not double: each step overwrites its output.
Common mistakes
- Dropping malformed records at ingestion — Keep them in bronze or a quarantine table; you may need them.
- Letting dashboards read silver directly — Consumers then depend on technical tables that change.
- Ignoring idempotency — Each layer should be safely re-runnable: MERGE or overwrite by partition, not blind appends.
Key takeaways
- Bronze keeps raw data, silver cleans and conforms it, gold serves the business.
- Bronze is the replayable history; do not transform it destructively.
- Silver is where deduplication and MERGE of changes happen.
- Use layers where they add value, and make each step idempotent.
Interview prep
THE QUESTION
"Explain the medallion architecture and how you would design a CDC pipeline with it."
Avoid: describing bronze, silver and gold as "raw, clean, aggregated" with nothing about keys, deduplication, idempotency or reprocessing.
Follow-ups · answer out loud, then open
Follow-up"Why keep bronze if silver has the clean data?"
Scenario"A bug in the silver transformation corrupted three weeks of data. How do you recover?"
Trap"Every table needs all three layers."
Check yourself
3 questionsWhere should malformed source records go?
Show the answer
Kept in bronze or a quarantine table. Bronze preserves raw data so problems can be investigated and replayed.
Which layer typically holds deduplicated entity tables updated by MERGE?
Show the answer
Silver. Silver is the cleaned, conformed, entity-level layer.
Main benefit of keeping bronze?
Show the answer
Rebuilding downstream tables without re-extracting from sources. Raw history lets you rerun silver and gold logic after fixes.
Practise this
Problems that use this, graded on hidden tests
- Late Data in the Raw ZoneData Lake Medium
- Rebuild a Table from Its Transaction LogLakehouse Medium
- Reconcile Two Sources (Full Outer Join)Joins AdvancedHard
Keep going
Up next · new module: Delta day to day · 8 min readThe Delta transaction log
Commit files, checkpoints and optimistic concurrency: how the _delta_log turns files into a table.
Related lessons
MERGE INTO and upsertsData lake & lakehouse · 5 min read
Change Data FeedData lake & lakehouse · 6 min read
Schema enforcement and evolution
Previous: ACID on object storage
Primary sources: Delta Lake: best practices