Project 02 · Lakehouse

Data Lakehouse with Medallion Architecture

Order files from the web store, point-of-sale exports from 140 stores, nightly inventory snapshots and web events land in cloud storage all day. Auto Loader picks up each new file exactly once and writes it untouched to bronze Delta tables. A Lakeflow Declarative Pipeline (formerly Delta Live Tables) cleans, deduplicates and conforms the data into silver, where data quality expectations quarantine bad rows instead of failing the run, then builds the gold tables that sales, inventory and marketing reporting read.

  • Databricks
  • Delta Lake
  • Auto Loader
  • Lakeflow Declarative Pipelines
  • Unity Catalog
Sample data Last 30 days · Sep 7 – Oct 6, 2026 Download data (CSV)

How rows moved through the layers

Landing files → bronze → silver (or quarantine) → gold, last 30 days

Revenue by category

Daily, from gold.daily_sales

Why rows were quarantined

Silver expectations that rows failed

Auto Loader: new files per hour

Last 7 days, all four landing folders

Pipeline update time

p50 and p95 per day, 24 updates a day

Data quality expectations

From the pipeline event log, last 30 days

Tables in Unity Catalog

Freshness checked against each table's SLA

How it works

Each layer has one job: bronze keeps everything, silver makes it trustworthy, gold makes it useful.

  1. 01 · Land

    Cloud storage

    Web orders as JSON, POS exports as CSV from 140 stores, inventory snapshots as Parquet and web events, all in one landing bucket.

  2. 02 · Ingest

    Auto Loader

    cloudFiles streams every new file exactly once, infers and evolves the schema, and keeps surprises in _rescued_data.

  3. 03 · Bronze

    Delta Lake

    Rows exactly as they arrived, plus the source file and ingest time. Nothing is dropped here.

  4. 04 · Silver

    Lakeflow pipeline

    Typed, deduplicated and conformed. Expectations quarantine rows that break the rules and log every failure.

  5. 05 · Gold

    Materialized views

    Daily sales, inventory health and the web funnel, refreshed incrementally each update.

  6. 06 · Serve

    Unity Catalog + SQL warehouse

    Lineage and access control on every table; BI tools and this dashboard query gold.

  • Bronze keeps everything. Auto Loader writes each file as-is with _source_file and _ingested_at. Columns nobody expected land in _rescued_data, so a row can always be traced to its file.
  • Expectations decide, not exceptions. Unusable rows are dropped to quarantine, odd but valid rows only warn, and a missing SKU fails the update, because that means the upstream contract broke.
  • Quarantine, then replay. Failed rows are kept with the rule they broke. Once the cause is fixed, for example a new store added to silver.stores, they are replayed into silver.
  • Customers keep their history. Customer changes from the CRM feed are applied as SCD type 2 with apply_changes, so reports can use the address that was valid at order time.

Data model

Tables live in Unity Catalog under retail. The CSV download is gold.daily_sales for the 30-day window.

retail.bronze.orders_rawStreaming table · Auto Loader
order_idstring
As sent by the web store
order_tsstring
Raw timestamp text, parsed in silver
store_id / customer_idstring
Raw ids
linesarray<struct>
SKU, quantity, unit price
_rescued_datastring
Fields that did not match the schema
_source_file / _ingested_atstring / timestamp
Where and when the row arrived
retail.silver.order_linesStreaming table · expectations
order_id / line_nostring / int
Unique per line; duplicates removed
order_tstimestamp
Parsed and converted to UTC
store_idint
Must exist in silver.stores
channelstring
web or store
sku / categorystring
Joined from the product dimension
quantity / unit_price_usdint / decimal(10,2)
Quantity must be positive
retail.gold.daily_salesMaterialized view · the CSV download
datedate
Order date, store local time
categorystring
Product category
order_lines / units_soldbigint
Lines and units sold
revenue_usddecimal(14,2)
Quantity × unit price
avg_line_value_usddecimal(10,2)
Revenue per line

Key code

The pipeline itself, the bundle that deploys it, and the event-log query behind the expectations table.

The Lakeflow pipeline: Auto Loader into bronze, expectations and quarantine in silver, a materialized view in gold.

import dlt
from pyspark.sql import functions as F

LANDING = "s3://retail-landing"

RULES = {
    "known_store_id": "store_known",
    "positive_quantity": "quantity > 0",
    "valid_order_ts": "order_ts IS NOT NULL",
}
# A row goes to quarantine if any rule is false or null
QUARANTINE_IF = " OR ".join(f"NOT coalesce({rule}, false)" for rule in RULES.values())


# ---------- Bronze: every file, exactly once, as it arrived
@dlt.table(comment="Raw web orders from Auto Loader")
def orders_raw():
    return (
        spark.readStream.format("cloudFiles")
        .option("cloudFiles.format", "json")
        .option("cloudFiles.schemaEvolutionMode", "addNewColumns")
        .option("cloudFiles.inferColumnTypes", "false")
        .load(f"{LANDING}/orders/")
        .withColumn("_source_file", F.col("_metadata.file_path"))
        .withColumn("_ingested_at", F.current_timestamp())
    )


# ---------- Silver: typed and checked; bad rows are routed, not lost
# (`stores` and `products` are defined in dimensions.py)
@dlt.view
def order_lines_checked():
    stores = dlt.read("stores").select("store_id", F.lit(True).alias("store_known"))
    lines = (
        dlt.read_stream("orders_raw")
        .withColumn("line", F.explode("lines"))
        .select(
            "order_id",
            F.col("line.line_no").cast("int").alias("line_no"),
            F.to_timestamp("order_ts").alias("order_ts"),
            F.col("store_id").cast("int").alias("store_id"),
            F.col("line.sku").alias("sku"),
            F.col("line.quantity").cast("int").alias("quantity"),
            F.col("line.unit_price").cast("decimal(10,2)").alias("unit_price_usd"),
        )
    )
    return (
        lines.join(F.broadcast(stores), "store_id", "left")
        .withColumn("store_known", F.coalesce("store_known", F.lit(False)))
        .withColumn("is_quarantined", F.expr(QUARANTINE_IF))
    )


@dlt.table(comment="Clean order lines")
@dlt.expect_all_or_drop(RULES)
def order_lines():
    return (
        dlt.read_stream("order_lines_checked")
        .withWatermark("order_ts", "2 days")
        .dropDuplicatesWithinWatermark(["order_id", "line_no"])
        .drop("store_known", "is_quarantined")
    )


@dlt.table(comment="Rows that failed a silver rule, kept for replay")
def order_lines_quarantine():
    return dlt.read_stream("order_lines_checked").where("is_quarantined")


# ---------- Gold: refreshed incrementally on each update
@dlt.table(comment="Daily sales by category")
def daily_sales():
    return (
        dlt.read("order_lines")
        .join(dlt.read("products"), "sku")
        .groupBy(F.to_date("order_ts").alias("date"), "category")
        .agg(
            F.count("*").alias("order_lines"),
            F.sum("quantity").alias("units_sold"),
            F.sum(F.col("quantity") * F.col("unit_price_usd")).alias("revenue_usd"),
        )
        .withColumn("avg_line_value_usd", F.round(F.col("revenue_usd") / F.col("order_lines"), 2))
    )

Engineering notes

A schema change that broke nothing

On Sep 22 the web store added promo_code to its order JSON. Auto Loader added the column to bronze, the pipeline restarted once on its own, and silver picked the field up after a one-line change. No rows were lost.

Quarantine is down 12%

Most quarantined rows came from two stores that sent an unknown store_id after a POS upgrade. Adding them to silver.stores and replaying the quarantine table recovered about 96K rows.

The slow day

On Sep 24, update p95 reached 21 minutes while a fixed-size cluster scaled for a backfill. Moving the pipeline to serverless on Sep 26 brought p95 back to about 11 minutes.

Gold stays cheap

Gold tables are materialized views, so most hourly updates only reprocess the current day instead of recomputing 30 days of sales.

About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as gold_daily_sales.csv or read data.json.