This is the lesson where everything comes together. We'll build ShopKart's real pipeline: two days of orders, a customer who moves city, duplicates, bad rows, and a revenue table at the end. Every number below came from actually running it.
📥Landing files
orders_<date>.json, customers.csv in a volume
🥉Bronze
Raw rows + _ingested_at, _source_file
- bronze.orders
🥈Silver
Clean, typed, de-duplicated, history
- silver.orders
- silver.customers
- orders_rejected
🥇Gold
Ready for dashboards
- gold.daily_city_revenue
| Layer | What's in it | Rules | Who uses it |
|---|---|---|---|
| Bronze | Raw data, append-only | Never change it; add load metadata | Data engineers (replays, debugging) |
| Silver | Clean, typed, unique rows; history | Validate, de-duplicate, MERGE | Engineers, data scientists |
| Gold | Aggregates, star schemas | Shaped for one use | Analysts, dashboards, apps |
Setup
from pyspark.sql import functions as F, Window
from delta.tables import DeltaTable
run_date = "2026-11-18" # which day's file to load (lesson 10 turns this into a job parameter)Bronze: land it raw
# BRONZE: land the raw file as-is, plus two columns that say where and when it came from.
bronze = (spark.read
.schema(orders_schema)
.json(f"/Volumes/shopkart/raw/landing/orders/orders_{run_date}.json")
.withColumn("_ingested_at", F.current_timestamp())
.withColumn("_source_file", F.col("_metadata.file_path")))
bronze.write.mode("append").saveAsTable("shopkart.bronze.orders")No cleaning at all, only two extra columns. _metadata.file_path is a hidden column Spark provides for file sources. Now, if a number looks wrong in a report, you can trace it back to the exact file. Bronze has 6 rows, including the bad ones.
Silver: clean and de-duplicate
# SILVER: clean, typed, one row per order (the latest version wins).
latest_first = Window.partitionBy("order_id").orderBy(F.desc("updated_at"))
silver_orders = (spark.table("shopkart.bronze.orders")
.filter(F.col("customer_id").isNotNull() & (F.col("quantity") > 0))
.withColumn("status", F.upper(F.trim("status")))
.withColumn("amount", F.round(F.col("quantity") * F.col("price"), 2))
.withColumn("rn", F.row_number().over(latest_first))
.filter("rn = 1")
.drop("rn", "_source_file"))
# Keep the bad rows instead of silently losing them.
rejected = (spark.table("shopkart.bronze.orders")
.filter(F.col("customer_id").isNull() | (F.col("quantity") <= 0)))
rejected.write.mode("overwrite").saveAsTable("shopkart.silver.orders_rejected")- Validate: no customer or quantity ≤ 0 → not allowed in silver.
- Standardise: trim and upper-case the status so “ delivered” and “DELIVERED” match.
- De-duplicate: keep only the newest version of each order (window +
row_number, from lesson 4). - Quarantine: bad rows go to
orders_rejectedso someone can fix the source instead of losing data silently.
# Upsert into silver: update orders we know, insert new ones. Safe to re-run.
if not spark.catalog.tableExists("shopkart.silver.orders"):
silver_orders.write.saveAsTable("shopkart.silver.orders")
else:
(DeltaTable.forName(spark, "shopkart.silver.orders").alias("t")
.merge(silver_orders.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll(condition="s.updated_at > t.updated_at")
.whenNotMatchedInsertAll()
.execute())The first run creates the table; later runs MERGE. The condition s.updated_at > t.updated_at means an older copy arriving late can never overwrite newer data. After day 1: 4 silver orders, 2 rejected.
Silver customers with history (SCD Type 2)
Customers change: Rahul moves from Mumbai to Pune. Should old reports say Mumbai or Pune? To be able to answer both, keep history. That's a Slowly Changing Dimension, Type 2.
| Type | On change | History? |
|---|---|---|
| SCD Type 0 | Never change the value | No |
| SCD Type 1 | Overwrite the old value | No |
| SCD Type 2 | Close the old row, add a new row | Yes, full history |
| SCD Type 3 | Keep a 'previous value' column | Only one step back |
# Customers dimension with history (SCD Type 2): first load.
customers_in = spark.read.option("header", True).csv("/Volumes/shopkart/raw/landing/customers/")
if not spark.catalog.tableExists("shopkart.silver.customers"):
(customers_in
.withColumn("is_current", F.lit(True))
.withColumn("valid_from", F.current_timestamp())
.withColumn("valid_to", F.lit(None).cast("timestamp"))
.write.saveAsTable("shopkart.silver.customers"))Gold: the business answer
# GOLD: business-ready answers. Revenue per day per city, delivered orders only.
current_customers = spark.table("shopkart.silver.customers").filter("is_current")
daily_city_revenue = (spark.table("shopkart.silver.orders")
.filter(F.col("status") == "DELIVERED")
.join(current_customers, "customer_id")
.groupBy(F.to_date("order_ts").alias("order_date"), "city")
.agg(F.sum("amount").alias("revenue"),
F.count("order_id").alias("orders")))
daily_city_revenue.write.mode("overwrite").saveAsTable("shopkart.gold.daily_city_revenue")
display(spark.table("shopkart.gold.daily_city_revenue"))| order_date | city | revenue | orders |
|---|---|---|---|
| 2026-11-18 | Kolkata | 3496.0 | 2 |
| 2026-11-18 | Mumbai | 598.0 | 1 |
The boss's question from lesson 1, answered. Gold is rebuilt with overwrite because it's small and fully derived from silver.
Day 2 arrives
We set run_date = "2026-11-19" and re-run bronze, silver and the silver MERGE. The new file has order O1003 (now DELIVERED), a new order O1007, and O1008 twice. Result we checked: bronze has 10 rows (it keeps everything), silver has 6 unique orders, and O1003 is DELIVERED.
Then Rahul's change arrives, and we apply SCD Type 2 with a MERGE trick:
# Next day: Rahul moved from Mumbai to Pune, and Meera is a new customer.
updates = spark.read.option("header", True).csv("/Volumes/shopkart/raw/landing/customer_updates/")
current = spark.table("shopkart.silver.customers").filter("is_current")
# Customers whose details changed need a NEW row (the old row gets closed).
changed = (updates.alias("u")
.join(current.alias("c"), "customer_id")
.filter("u.city <> c.city OR u.email <> c.email")
.select("u.*"))
staged = (changed.withColumn("merge_key", F.lit(None).cast("string")) # never matches → INSERT new version
.unionByName(updates.withColumn("merge_key", F.col("customer_id")))) # matches → close the old row
(DeltaTable.forName(spark, "shopkart.silver.customers").alias("t")
.merge(staged.alias("s"), "t.customer_id = s.merge_key AND t.is_current")
.whenMatchedUpdate(
condition="t.city <> s.city OR t.email <> s.email",
set={"is_current": "false", "valid_to": "current_timestamp()"})
.whenNotMatchedInsert(values={
"customer_id": "s.customer_id", "name": "s.name", "city": "s.city", "email": "s.email",
"is_current": "true", "valid_from": "current_timestamp()", "valid_to": "null"})
.execute())
display(spark.table("shopkart.silver.customers").orderBy("customer_id", "valid_from"))| customer_id | name | city | is_current | valid_to |
|---|---|---|---|---|
| C01 | Asha | Kolkata | true | null |
| C02 | Rahul | Mumbai | false | (closed today) |
| C02 | Rahul | Pune | true | null |
| C03 | Priya | Bengaluru | true | null |
| C04 | Imran | Delhi | true | null |
| C05 | Meera | Chennai | true | null |
How the trick works: one MERGE can't both update and insert for the same matching row. So we feed it each changed customer twice: once with merge_key = customer_id (matches the current row → close it) and once with merge_key = null (never matches → insert the new version). New customers like Meera simply don't match and are inserted.
Re-running gold after day 2 gives:
| order_date | city | revenue | orders |
|---|---|---|---|
| 2026-11-18 | Kolkata | 3496.0 | 2 |
| 2026-11-18 | Pune | 598.0 | 1 |
| 2026-11-18 | Bengaluru | 4999.0 | 1 |
| 2026-11-19 | Delhi | 1196.0 | 1 |
Star schema: how gold is often shaped
For BI tools, gold is often a star schema: one fact table of events with numbers (orders: quantity, amount) surrounded by dimension tables describing them (customers, products, dates). Facts are long and thin; dimensions are short and wide. Our silver.customers SCD2 table becomes dim_customer.
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Explain the medallion architecture.Fresher+
Q2How do you make a pipeline idempotent?1–3 yrs+
Q3How do you handle late-arriving or out-of-order data?1–3 yrs+
Q4How do you handle bad records?1–3 yrs+
Q5Implement SCD Type 2 with Delta MERGE.3+ yrs+
Q6A report shows revenue under a customer's new city for last year's orders. Why, and how do you fix it?3+ yrs+
Key takeaways
- ✓Bronze keeps the truth, silver makes it clean, gold makes it useful.
- ✓MERGE plus an updated_at condition makes silver idempotent and safe for late data.
- ✓SCD Type 2 keeps history and enables point-in-time reporting.
- ✓One problem remains: we pick files by date by hand. Next lesson, Auto Loader finds new files for us.
Frequently asked questions
What is the medallion architecture?
A way to organise lakehouse tables in three layers: bronze (raw data as it arrived), silver (cleaned, de-duplicated, typed) and gold (business-ready aggregates for reports). Each layer is built from the one before it.
Why keep a bronze layer at all?
Bronze is your safety copy. If you find a bug in your cleaning logic, you can rebuild silver and gold from bronze without asking the source system for the data again.
What is SCD Type 2?
Slowly Changing Dimension Type 2 keeps history: when a customer's city changes, the old row is closed (valid_to set, is_current = false) and a new row is added. Type 1 simply overwrites the old value and keeps no history.
Is gold always an aggregate?
Usually it's what the business consumes: aggregates like daily revenue, or star-schema fact and dimension tables for BI tools. The rule is 'ready to use', not necessarily 'summed up'.
Should every pipeline have exactly three layers?
No. It's a guideline. Some teams add a staging layer or skip gold for simple cases. The important ideas are: keep raw data, clean in one place, and serve consumers from curated tables.
🧠 Quick check: medallion architecture
1. Where does raw, unchanged data go?
2. Where do you remove duplicates and fix types?
3. Why use MERGE (not overwrite) for silver?
4. In SCD Type 2, a customer moves city. What happens?
Checking your access…