Platform Engineering · Lesson 161

Data Lakehouse Architecture: Open Tables, Medallion Layers, and Governance

A lakehouse keeps data in cheap object storage, like a data lake, and adds what a warehouse gives you: tables with schemas, ACID transactions, time travel, and fast SQL. The trick is an open table format (Apache Iceberg, Delta Lake, or Apache Hudi) that stores table metadata next to Parquet files, so many engines (Spark, Trino, Flink, Snowflake, BigQuery, Athena, Databricks) can read and write the same tables. Around it sit a catalog, medallion layers (bronze raw, silver cleaned, gold business-ready), governance, and table maintenance. This lesson follows one day of order events from landing to a dashboard, and shows two failures: small files that made every query slow, and a gold table nobody could trust because two jobs wrote it at once without a table format.

Difficulty: Advanced · Know this first: Lesson 160, Lesson 56

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes of pipeline from the last event to the dashboard being ready. It is a worked example, not a measurement. The table format and maintenance hops are where a lakehouse stops behaving like a warehouse.

Try it: files, formats, and the morning dashboard

Pick the table format for gold, how often silver is compacted, and how many writers touch gold. The readouts show files per table, query time, and whether readers can trust the result.

9,000silver files
4 sdashboard query
consistentwhat readers see

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Lakehouse work grows in four levels: reading tables, building layers, operating tables, and running a governed data platform.

Basic — Read tables and snapshots

At the basic level you can query a lakehouse table and its history.

  • Object storage, Parquet files, and the table format's metadata.
  • Snapshots and time travel; the catalog that names tables.
  • Bronze, silver, gold.

Where it breaks: reading files directly from the bucket instead of through the table.

Try it: Basic

A colleague reads gold by listing Parquet files in the bucket. What is the risk?

Now do it: Query a table's snapshots in your engine.

Intermediate — Build the layers

At the intermediate level you build bronze, silver, and gold with the right operations.

  • Append to bronze; MERGE INTO silver by key; rebuild or incrementally update gold.
  • Partitioning by how tables are queried (Iceberg hidden partitioning by day).
  • Quality checks between layers.

Try it: Intermediate

Late events arrive for yesterday. How does silver absorb them?

Now do it: Write a MERGE for one silver table.

Advanced — Operate the tables

At the advanced level tables stay fast and cheap.

  • Compaction, snapshot expiry, orphan cleanup, and manifest rewrites on schedules.
  • File size and count per table monitored; clustering or sort order for common filters.
  • Concurrent writers coordinated through the catalog; retries on commit conflicts.

Try it: Advanced

Storage for a table keeps growing though its data does not. Why?

Now do it: Check the oldest snapshot on your largest table.

Master — A governed data platform

At the master level the lakehouse is a governed platform shared by many teams and engines.

  • One catalog with fine-grained access, PII tags, masking, and audit.
  • Gold tables as data products with owners, contracts, and SLAs.
  • Lineage from bronze to dashboards and models; deletion for privacy requests across layers.

Trade-off: open formats avoid lock-in and need you (or a managed service) to run maintenance and governance that a warehouse does for you.

Try it: Master

A customer asks to be deleted. Where must the deletion happen?

Now do it: Trace one customer's data through your layers.

Go deeper

Iceberg in Spark SQL: create, merge, time travel, and maintain a table. Delta and Hudi have equivalents (OPTIMIZE, VACUUM, and so on); check your engine's documentation.

CREATE TABLE lake.silver.orders (order_id string, customer_id string, amount decimal(12,2), ts timestamp)
USING iceberg PARTITIONED BY (days(ts));

MERGE INTO lake.silver.orders t
USING (SELECT * FROM lake.bronze.order_events WHERE ingest_date = current_date()) s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

SELECT count(*) FROM lake.silver.orders TIMESTAMP AS OF '2026-11-26 00:00:00';     -- time travel

CALL lake.system.rewrite_data_files(table => 'silver.orders', options => map('target-file-size-bytes','268435456'));
CALL lake.system.expire_snapshots(table => 'silver.orders', older_than => TIMESTAMP '2026-11-20 00:00:00');
CALL lake.system.remove_orphan_files(table => 'silver.orders');

Lakehouse pieces on each cloud: storage (S3, ADLS Gen2, Cloud Storage); catalogs (Glue Data Catalog and S3 Tables, Unity Catalog or OneLake in Microsoft Fabric, BigLake metastore); engines (Athena, EMR, Redshift; Databricks, Synapse, Fabric; BigQuery, Dataproc); governance (Lake Formation, Unity Catalog or Purview, Dataplex and BigLake). Formats are increasingly readable across them, which is the point of choosing an open one.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The folder that two jobs wrote.

Timeline

  • 01:00A backfill of last month starts rewriting gold daily-revenue folders, which are plain Parquet.
  • 03:00The nightly job rewrites yesterday's folder while the backfill is also rewriting it.
  • 07:00The board pack is generated. Its query lists the folder mid-rewrite and reads files from both jobs; yesterday's revenue is counted twice.
  • Next dayFinance spots the jump. The day is rebuilt, the board pack corrected, and gold moved to Iceberg tables in the shared catalog.

What changed after

Every layer is a table with atomic commits, backfills write through the same table with commit retries, compaction and snapshot expiry run on schedules with file-count alerts, and gold tables have owners and a freshness SLA.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A virtual environment for Python packages: python3 -m venv ~/lake && . ~/lake/bin/activate. Then pip install duckdb; the steps below make Parquet files locally, with no cloud account.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Write a day of order events as many small Parquet files, the way a streaming job does.

    mkdir -p ~/labs/lake/silver && cd ~/labs/lake
    python3 -c "
    import duckdb
    for i in range(200):
        duckdb.sql(f\"COPY (SELECT {i}*50 + range AS order_id, (random()*100)::DECIMAL(10,2) AS amount FROM range(50)) TO 'silver/part-{i:04d}.parquet'\")
    "
    ls silver | wc -l; du -sh silver

    Options: Each COPY writes one Parquet file of 50 rows, like one micro-batch.

    Expect: 200 files of a few kilobytes each.

    Clean up: rm -rf ~/labs/lake.

  2. Query them, then compact them into one file and query again.

    python3 -c "import duckdb,time; t=time.time(); print(duckdb.sql(\"SELECT count(*), sum(amount) FROM 'silver/*.parquet'\").fetchone(), round(time.time()-t,3), 's')"
    python3 -c "import duckdb; duckdb.sql(\"COPY (SELECT * FROM 'silver/*.parquet') TO 'compacted.parquet'\")"
    python3 -c "import duckdb,time; t=time.time(); print(duckdb.sql(\"SELECT count(*), sum(amount) FROM 'compacted.parquet'\").fetchone(), round(time.time()-t,3), 's')"

    Expect: The same count and sum both times; the compacted file is read faster because there is one file to open instead of 200. On object storage the gap is far larger, because each file is a request.

  3. Look inside a Parquet file: the schema and row-group statistics that let engines skip files.

    python3 -c "import duckdb; print(duckdb.sql(\"SELECT path_in_schema, stats_min, stats_max FROM parquet_metadata('compacted.parquet')\"))"

    Expect: Minimum and maximum per column and row group: what a query engine reads to decide whether to open the data at all.

2. Python: snapshots.py

This program contrasts a gold table kept as a plain folder of files with one kept by a table format. Two writers (the nightly job and a backfill) rewrite the same day at the same time while a reader lists the data: the folder gives the reader a mix of both, the table format's atomic snapshots give it one consistent version and make the second writer retry. Then it estimates the cost of small files. Save it as snapshots.py, then run it.

# snapshots.py
class Folder:
    """Plain Parquet folder: writers replace files one by one; readers list whatever is there."""
    def __init__(self):
        self.files = {"part-0": ("v1", 500), "part-1": ("v1", 500)}
    def write_file(self, name, version, revenue):
        self.files[name] = (version, revenue)
    def read(self):
        return sum(r for _, r in self.files.values()), sorted({v for v, _ in self.files.values()})

class Table:
    """Table format: a commit swaps the whole file list at once, if nobody committed in between."""
    def __init__(self):
        self.snapshots = [{"part-0": ("v1", 500), "part-1": ("v1", 500)}]
    def commit(self, base, files):
        if base != len(self.snapshots) - 1:
            return False                                  # someone committed first: retry from the new snapshot
        self.snapshots.append(files)
        return True
    def read(self):
        current = self.snapshots[-1]
        return sum(r for _, r in current.values()), sorted({v for v, _ in current.values()})

folder = Folder()
folder.write_file("part-0", "nightly", 520)              # the nightly job has written one of its two files
folder.write_file("part-2", "backfill", 510)             # the backfill writes its own file for the same day
print("folder, read mid-write:   revenue", *folder.read())

table = Table()
base = len(table.snapshots) - 1
print("table, read mid-write:    revenue", *table.read())
ok_nightly = table.commit(base, {"part-a": ("nightly", 520), "part-b": ("nightly", 490)})
ok_backfill = table.commit(base, {"part-c": ("backfill", 1010)})
print(f"commits: nightly {'ok' if ok_nightly else 'conflict'}, backfill {'ok' if ok_backfill else 'conflict, retries on the new snapshot'}")
print("table, after the commits: revenue", *table.read())
print()

REQUEST_MS, MB_PER_S = 12, 400                           # per-file open on object storage, scan speed
for files, size_mb in ((2_400_000, 0.04), (375, 256)):            # the same 96 GB of data
    total_mb = files * size_mb
    seconds = files * REQUEST_MS / 1000 / 64 + total_mb / MB_PER_S / 64     # 64 readers in parallel
    print(f"{files:>9,} files of {size_mb:>6} MB: about {seconds / 60:5.1f} minutes to scan")

Run it, and you should see this output:

$ python3 snapshots.py
folder, read mid-write:   revenue 1530 ['backfill', 'nightly', 'v1']
table, read mid-write:    revenue 1000 ['v1']
commits: nightly ok, backfill conflict, retries on the new snapshot
table, after the commits: revenue 1010 ['nightly']

2,400,000 files of   0.04 MB: about   7.6 minutes to scan
      375 files of    256 MB: about   0.1 minutes to scan

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/data-lakehouse-architecture && cd ~/labs/data-lakehouse-architecture) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Data Lakehouse Architecture: Open Tables, Medallion Layers, and Governance", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Write a day of order events as many small Parquet files, the way a streaming job does.'
  'Query them, then compact them into one file and query again.'
  'Look inside a Parquet file: the schema and row-group statistics that let engines skip files.'
)

step_1() {
mkdir -p ~/labs/lake/silver && cd ~/labs/lake
python3 -c "
import duckdb
for i in range(200):
    duckdb.sql(f\"COPY (SELECT {i}*50 + range AS order_id, (random()*100)::DECIMAL(10,2) AS amount FROM range(50)) TO 'silver/part-{i:04d}.parquet'\")
"
ls silver | wc -l; du -sh silver
}

step_2() {
python3 -c "import duckdb,time; t=time.time(); print(duckdb.sql(\"SELECT count(*), sum(amount) FROM 'silver/*.parquet'\").fetchone(), round(time.time()-t,3), 's')"
python3 -c "import duckdb; duckdb.sql(\"COPY (SELECT * FROM 'silver/*.parquet') TO 'compacted.parquet'\")"
python3 -c "import duckdb,time; t=time.time(); print(duckdb.sql(\"SELECT count(*), sum(amount) FROM 'compacted.parquet'\").fetchone(), round(time.time()-t,3), 's')"
}

step_3() {
python3 -c "import duckdb; print(duckdb.sql(\"SELECT path_in_schema, stats_min, stats_max FROM parquet_metadata('compacted.parquet')\"))"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

A retailer has a data lake of Parquet folders and a separate warehouse, with numbers that disagree. Design the lakehouse that replaces both.

Clarifying questions to ask

Which table format and catalog? How are bronze, silver, and gold built and owned? Which engines read what? How are tables maintained? How is access governed, and how are deletions handled? How do you migrate without breaking dashboards?

Rough sizing

Say 400 TB, 2 billion events a day, 300 gold tables, 50 dashboards, 12 data teams, and privacy deletions within 30 days.

Shape of the answer

Iceberg tables on object storage with a REST catalog (or the cloud's managed catalog) shared by Spark, Flink, Trino, and the BI warehouse; streaming into bronze, hourly MERGE into silver with quality checks, gold as owned data products with SLAs; hourly compaction for streaming tables, nightly expiry and orphan cleanup, file-count alerts; table, column, and row grants with PII masking and audit; deletion jobs across layers followed by snapshot expiry; migration table by table with both systems compared until numbers match.

Trade-offs to name

Open formats avoid lock-in and need maintenance and governance that a warehouse bundles; many engines on one catalog is flexible and needs careful permission design; short snapshot retention saves storage and limits time travel and audit.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
No compactionHop 9: MaintenanceBreaksNothing compacts silver. After months of minute-by-minute appends it holds 2.4 million files averaging 40 KB.
Plain Parquet, two writersHop 2: Table formatBreaksGold is a folder of plain Parquet. A backfill of last month and the nightly job both rewrite the daily revenue folder at the same time.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Object storage → Table format → Catalog → Bronze → Silver → Gold → Query engines → Governance → Maintenance. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

Architecture review checklist

Review the design in this lesson, or your own, against these ten areas. Tick an area when you can answer its question with evidence: a number, a test, a document, or an owner. Your ticks stay in this browser.

  1. Business outcomeWhich result for users or the business does this design serve, and which number shows it is working?
  2. SecurityWho and what can reach each part, how is identity proven, and how is data protected in transit and at rest?
  3. ReliabilityWhat is the target (SLO), which single failures does the design survive, and how was that tested?
  4. PerformanceWhat latency and throughput are required at peak, and where is the first bottleneck?
  5. OperationsHow is it deployed, observed, and changed safely, and who is paged when it breaks?
  6. CostWhat does it cost per month and per unit of work (request, tenant, model call), and what grows the bill?
  7. SustainabilityWhich resources sit idle, which region and hardware does it run on, and what can scale to zero?
  8. GovernanceWhich policies, guardrails, and compliance rules apply, and how are they enforced in code?
  9. OwnershipWhich team owns each component, its budget, and its on-call, and where is that written down?
  10. Failure and recovery planWhat is the RTO and RPO, what is the runbook for a region or dependency loss, and when was it last rehearsed?

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 162
AI/ML Platform Architecture: From Data to Models and LLMs in Production

An AI/ML platform is the shared ground that lets many teams build, ship, and run models without each rebuilding the same plumbing: data from the lakehouse, a feature store, managed training on shared GPUs, experiment tracking and…

Go to Lesson 162 →

Or browse the full course from the Lessons index.