Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

Raw, Clean, Modeled: Designing the Layers

Build bronze, silver and gold layers for two order sources in DuckDB, with a quarantine for bad rows, a registry of owners and retention rules, a governance check, and a rebuild after a bug that shows why retention and replay must be planned together.

Contentsand lesson path

What you will learn

  • Organize data into raw, cleaned and modeled layers (for example bronze, silver and gold) with naming, ownership and retention rules.

01. The problem

A shop sells through its own website and through a marketplace. Each source sends orders in its own shape: the website as JSON files, the marketplace as CSV with different column names and prices in pence. Finance wants daily revenue in euros. You could write one big query from the raw files to the report, but then every fix means changing that query, nobody can see where a number went wrong, and the next team that needs orders starts again from the raw files.

The common answer is to organise the data in three layers, often called the medallion layers. Bronze holds raw data exactly as received. Silver holds cleaned, typed and deduplicated data, still one row per source record. Gold holds business-ready tables, such as marts for one team. In this worked example you build all three with DuckDB, then add the rules that make layers work in practice: names, owners and retention. You need Python and pip install "duckdb==1.5.6".

02. Step 1: Land the files and load bronze

Create these three files. The landing folders carry the ingest date in their names, like the partitions an extractor writes. Notice the problems a real source brings: the website sends order S-1002 twice because it was refunded later, S-1003 has the amount n/a, and one file is from July.

JSON · landing/shop/ingest_date=2026-07-20/orders.json
[
  {"order_id": "S-0901", "email": "[email protected]",
   "ts": "2026-07-20T08:00:00Z", "amount": "12.00",
   "currency": "EUR", "status": "PAID"}
]
JSON · landing/shop/ingest_date=2026-11-01/orders.json
[
  {"order_id": "S-1001", "email": "[email protected]",
   "ts": "2026-11-01T09:12:00Z", "amount": "40.00",
   "currency": "EUR", "status": "PAID"},
  {"order_id": "S-1002", "email": "[email protected]",
   "ts": "2026-11-01T09:30:00Z", "amount": "25.50",
   "currency": "EUR", "status": "PAID"},
  {"order_id": "S-1002", "email": "[email protected]",
   "ts": "2026-11-01T11:05:00Z", "amount": "25.50",
   "currency": "EUR", "status": "REFUNDED"},
  {"order_id": "S-1003", "email": "[email protected]",
   "ts": "2026-11-01T12:00:00Z", "amount": "n/a",
   "currency": "EUR", "status": "PAID"}
]
CSV · landing/marketplace/ingest_date=2026-11-01/sales.csv
sale_ref,buyer_email,sold_at,price,state
M-77,[email protected],2026-11-01 10:00:00+00,1550,complete
M-78,[email protected],2026-11-01 14:20:00+00,899,complete

Bronze reads every field as text, so a bad value can never stop the load, and adds where and when each row came from. Each source gets its own schema, named bronze_<source>. The small runner runsql.py executes a SQL file against lake.duckdb and prints the result of its last statement.

Python · runsql.py
"""Run a SQL file against lake.duckdb and print the result of its last statement."""
import sys

import duckdb

con = duckdb.connect("lake.duckdb")
*setup, last = [s for s in open(sys.argv[1]).read().split(";") if s.strip()]
for statement in setup:
    con.execute(statement)
print(con.sql(last))
SQL · bronze.sql
-- Bronze: every record as received, all text, plus where and when it came from.
CREATE SCHEMA IF NOT EXISTS bronze_shop;
CREATE SCHEMA IF NOT EXISTS bronze_marketplace;
CREATE OR REPLACE TABLE bronze_shop.orders AS
SELECT * EXCLUDE (filename), filename AS _source_file,
       TIMESTAMPTZ '2026-11-01 13:00:00+00' AS _loaded_at
FROM read_json('landing/shop/*/orders.json', format = 'array',
               columns = {order_id: 'VARCHAR', email: 'VARCHAR', ts: 'VARCHAR',
                          amount: 'VARCHAR', currency: 'VARCHAR', status: 'VARCHAR'},
               hive_partitioning = true, filename = true);
CREATE OR REPLACE TABLE bronze_marketplace.sales AS
SELECT * EXCLUDE (filename), filename AS _source_file,
       TIMESTAMPTZ '2026-11-01 15:00:00+00' AS _loaded_at
FROM read_csv('landing/marketplace/*/sales.csv', all_varchar = true,
              hive_partitioning = true, filename = true);
SELECT 'bronze_shop.orders' AS table_name, count(*) AS row_count FROM bronze_shop.orders
UNION ALL SELECT 'bronze_marketplace.sales', count(*) FROM bronze_marketplace.sales;
Terminal
python runsql.py bronze.sql
Expected output
┌──────────────────────────┬───────────┐
│        table_name        │ row_count │
│         varchar          │   int64   │
├──────────────────────────┼───────────┤
│ bronze_shop.orders       │         5 │
│ bronze_marketplace.sales │         2 │
└──────────────────────────┴───────────┘

03. Step 2: Clean and conform into silver

Silver is where technical cleaning happens, once, for everyone. The view orders_typed maps both sources onto one set of standard column names, converts types with TRY_CAST (NULL instead of an error), standardises status values, and replaces the email address with a hash, so personal data stops at bronze. The table orders then keeps only rows with a valid timestamp and amount, and the newest version of each order. Silver stays at the source grain: one row per order, not yet summed into anything.

SQL · silver.sql
-- Silver: typed, standard names, one row per order, still at the source grain.
CREATE SCHEMA IF NOT EXISTS silver_sales;
CREATE OR REPLACE VIEW silver_sales.orders_typed AS
SELECT order_id, 'shop' AS source_system, sha256(lower(email)) AS customer_key,
       TRY_CAST(ts AS TIMESTAMPTZ) AS ordered_at,
       TRY_CAST(amount AS DECIMAL(10, 2)) AS amount, currency,
       lower(status) AS status, _source_file
FROM bronze_shop.orders
UNION ALL
SELECT sale_ref, 'marketplace', sha256(lower(buyer_email)),
       TRY_CAST(sold_at AS TIMESTAMPTZ),
       TRY_CAST(price AS DECIMAL(10, 2)), 'GBP',
       CASE state WHEN 'complete' THEN 'paid' ELSE state END, _source_file
FROM bronze_marketplace.sales;
CREATE OR REPLACE TABLE silver_sales.orders AS
SELECT * EXCLUDE (_source_file) FROM silver_sales.orders_typed
WHERE ordered_at IS NOT NULL AND amount IS NOT NULL
QUALIFY row_number() OVER (PARTITION BY source_system, order_id
                           ORDER BY ordered_at DESC) = 1;
CREATE OR REPLACE TABLE silver_sales.orders_rejected AS
SELECT order_id, source_system, _source_file,
       CASE WHEN ordered_at IS NULL THEN 'bad timestamp' ELSE 'bad amount' END AS reason
FROM silver_sales.orders_typed
WHERE ordered_at IS NULL OR amount IS NULL;
SELECT order_id, source_system, ordered_at::DATE AS day, amount, currency, status
FROM silver_sales.orders ORDER BY source_system, order_id;
Terminal
python runsql.py silver.sql
Expected output
┌──────────┬───────────────┬────────────┬───────────────┬──────────┬──────────┐
│ order_id │ source_system │    day     │    amount     │ currency │  status  │
│ varchar  │    varchar    │    date    │ decimal(10,2) │ varchar  │ varchar  │
├──────────┼───────────────┼────────────┼───────────────┼──────────┼──────────┤
│ M-77     │ marketplace   │ 2026-11-01 │       1550.00 │ GBP      │ paid     │
│ M-78     │ marketplace   │ 2026-11-01 │        899.00 │ GBP      │ paid     │
│ S-0901   │ shop          │ 2026-07-20 │         12.00 │ EUR      │ paid     │
│ S-1001   │ shop          │ 2026-11-01 │         40.00 │ EUR      │ paid     │
│ S-1002   │ shop          │ 2026-11-01 │         25.50 │ EUR      │ refunded │
└──────────┴───────────────┴────────────┴───────────────┴──────────┴──────────┘

S-1002 appears once, as refunded. S-1003 is missing, but not lost: rows that fail the checks go to silver_sales.orders_rejected, a quarantine table, with a reason, so someone can fix the source and nothing disappears silently. Query it with a one-line file, rejected.sql, containing SELECT order_id, source_system, reason FROM silver_sales.orders_rejected;.

Expected output (python runsql.py rejected.sql)
┌──────────┬───────────────┬────────────┐
│ order_id │ source_system │   reason   │
│ varchar  │    varchar    │  varchar   │
├──────────┼───────────────┼────────────┤
│ S-1003   │ shop          │ bad amount │
└──────────┴───────────────┴────────────┘

04. Step 3: Model the business question in gold

Gold applies business rules: revenue counts paid orders only, converted to euros. The schema name gold_finance says both the layer and the domain that uses it. The conversion uses a fixed example rate; a real mart would join a rates table.

SQL · gold.sql
-- Gold: a business-ready mart. Revenue counts paid orders only, in euros.
CREATE SCHEMA IF NOT EXISTS gold_finance;
CREATE OR REPLACE TABLE gold_finance.daily_revenue AS
SELECT ordered_at::DATE AS order_date, source_system, count(*) AS paid_orders,
       sum(amount * CASE currency WHEN 'GBP' THEN 1.15 ELSE 1.00 END)::DECIMAL(12, 2)
         AS revenue_eur                       -- fixed example rate for GBP
FROM silver_sales.orders
WHERE status = 'paid'
GROUP BY ALL;
SELECT * FROM gold_finance.daily_revenue ORDER BY ALL;
Terminal
python runsql.py gold.sql
Expected output
┌────────────┬───────────────┬─────────────┬───────────────┐
│ order_date │ source_system │ paid_orders │  revenue_eur  │
│    date    │    varchar    │    int64    │ decimal(12,2) │
├────────────┼───────────────┼─────────────┼───────────────┤
│ 2026-07-20 │ shop          │           1 │         12.00 │
│ 2026-11-01 │ marketplace   │           2 │       2816.35 │
│ 2026-11-01 │ shop          │           1 │         40.00 │
└────────────┴───────────────┴─────────────┴───────────────┘

Marketplace revenue of €2,816.35 for two orders should look wrong to you. Keep it for now; step 6 fixes it.

05. Step 4: Names, owners and a governance check

Layers only stay clear if three rules are written down and checked. Naming: every schema is <layer>_<source or domain>, so a table name tells you how far it can be trusted. Ownership: every table has one owning team that answers questions about it and approves changes. Retention: every table has a stated life, set by cost and by law; raw data with personal details is usually kept for the shortest time. The script below records those rules in a registry table, adds a comment to the gold table that catalog tools can display, and runs a check that lists any layer table without a registry entry.

SQL · registry.sql
-- Who owns each table, how long it is kept, and whether it holds personal data.
CREATE SCHEMA IF NOT EXISTS ops;
CREATE OR REPLACE TABLE ops.table_registry (
  table_name     VARCHAR PRIMARY KEY,
  layer          VARCHAR NOT NULL CHECK (layer IN ('bronze', 'silver', 'gold')),
  owner          VARCHAR NOT NULL,
  retention_days INTEGER,               -- NULL means keep until the owner decides
  personal_data  BOOLEAN NOT NULL
);
INSERT INTO ops.table_registry VALUES
  ('bronze_shop.orders',         'bronze', 'team-ingestion',  90, true),
  ('bronze_marketplace.sales',   'bronze', 'team-ingestion',  90, true),
  ('silver_sales.orders',        'silver', 'team-sales-data', 1095, false),
  ('gold_finance.daily_revenue', 'gold',   'team-finance-bi', NULL, false);
COMMENT ON TABLE gold_finance.daily_revenue IS
  'Paid orders per day and source, in EUR. Owner: team-finance-bi.';
-- Governance check: every table in a layer schema must be registered.
SELECT t.schema_name || '.' || t.table_name AS unregistered_table
FROM duckdb_tables() t
LEFT JOIN ops.table_registry r ON r.table_name = t.schema_name || '.' || t.table_name
WHERE t.schema_name SIMILAR TO '(bronze|silver|gold)_.*' AND r.table_name IS NULL;
Terminal
python runsql.py registry.sql
Expected output
┌──────────────────────────────┐
│      unregistered_table      │
│           varchar            │
├──────────────────────────────┤
│ silver_sales.orders_rejected │
└──────────────────────────────┘

The check caught the quarantine table: it was created in step 2 and nobody registered it. Register it with a short retention, then run the check again; in a real platform this check runs in CI and fails the build.

SQL · register_rejected.sql
INSERT INTO ops.table_registry VALUES
  ('silver_sales.orders_rejected', 'silver', 'team-sales-data', 30, false);
SELECT count(*) AS unregistered_tables
FROM duckdb_tables() t
LEFT JOIN ops.table_registry r ON r.table_name = t.schema_name || '.' || t.table_name
WHERE t.schema_name SIMILAR TO '(bronze|silver|gold)_.*' AND r.table_name IS NULL;
Expected output (python runsql.py register_rejected.sql)
┌─────────────────────┐
│ unregistered_tables │
│        int64        │
├─────────────────────┤
│                   0 │
└─────────────────────┘

06. Step 5: Apply retention

Bronze holds raw email addresses, so its retention is 90 days. Apply the rule for the run date, then remove the expired landing folder as well; on object storage, a lifecycle rule usually deletes old files automatically.

SQL · retention.sql
-- Apply bronze retention for the run date 2026-11-01: drop data past its limit.
DELETE FROM bronze_shop.orders
WHERE ingest_date < DATE '2026-11-01' - (SELECT retention_days FROM ops.table_registry
                                         WHERE table_name = 'bronze_shop.orders');
SELECT ingest_date, count(*) AS rows_left
FROM bronze_shop.orders GROUP BY ALL ORDER BY 1;
Terminal
python runsql.py retention.sql
rm -r "landing/shop/ingest_date=2026-07-20"
ls landing/shop
Expected output
┌─────────────┬───────────┐
│ ingest_date │ rows_left │
│    date     │   int64   │
├─────────────┼───────────┤
│ 2026-11-01  │         4 │
└─────────────┴───────────┘

ingest_date=2026-11-01

07. Step 6: Fix a bug and rebuild from bronze

The marketplace documentation says prices are in pence. Because bronze kept the original text, the fix is one line in silver.sql, and silver and gold are rebuilt without asking the marketplace for anything. Change the marketplace price line to the one below, then rebuild.

SQL · silver.sql, line 12 after the fix
       (TRY_CAST(price AS DECIMAL(12, 2)) / 100)::DECIMAL(10, 2), 'GBP',
Terminal
python runsql.py silver.sql > /dev/null
python runsql.py gold.sql
Expected output
┌────────────┬───────────────┬─────────────┬───────────────┐
│ order_date │ source_system │ paid_orders │  revenue_eur  │
│    date    │    varchar    │    int64    │ decimal(12,2) │
├────────────┼───────────────┼─────────────┼───────────────┤
│ 2026-11-01 │ marketplace   │           2 │         28.16 │
│ 2026-11-01 │ shop          │           1 │         40.00 │
└────────────┴───────────────┴─────────────┴───────────────┘

Marketplace revenue is now €28.16: (15.50 + 8.99) × 1.15. But look again: the July row has gone from gold. Silver keeps orders for three years, yet this full rebuild read bronze, which now keeps only 90 days, so the July order was dropped. A full rebuild from bronze can only restore what bronze still holds. Either rebuild only the affected dates (merging them into silver, as in Incremental Loads with Watermarks and Lookbacks), or keep bronze, or an archive of it, for as long as you may need to replay. Decide this when you set the retention rules, not after a bug.

08. Check your understanding

Practice check · 3 questions

Layers in practice

Each question changes one detail of the worked example. Pick the best answer.

Q1. Marketing now wants revenue per customer per month. Which table should the new gold mart be built from?
Q2. You must be able to rebuild two years of silver after any bug, and bronze contains raw email addresses, which the privacy policy allows for only 90 days. What design meets both rules?
Q3. Next week the governance check lists `gold_finance.tmp_check`, created by an analyst for a one-off test. What is the right response?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the skill practice, give your fact table the same three layers. Write the naming rule, register every table with an owner, a retention period and a personal-data flag, and add the governance check to your test suite. Then introduce a bug in one silver rule, fix it, and rebuild, and write down which retention setting made the rebuild complete or incomplete.

10. Review prompt

Without looking back, explain what belongs in bronze, silver and gold and why cleaning happens in silver; how the quarantine table protects you; what the naming, ownership and retention rules are for; and why the rebuild in step 6 lost the July order.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check