Layers
Part of the free LogicWiz Data Engineering course, Module 5: Data modelling. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 8:40 on Monday. Tess's dashboard says 28 orders came in from 1 to 3 June. Dana's app shows far fewer. The warehouse has tables called orders, orders_clean, orders_final, orders_final_v2 and orders_new_DO_NOT_USE. The dashboard reads one of them, and nobody remembers which.
You'll learn to
- Say what belongs in bronze, silver and gold
- Build the three layers in SQL and watch the rows change
- Explain why medallion is not a star schema
- Explain Data Vault hubs, links and satellites, and their hash keys
Learn
The dashboard was reading raw files
You trace the dashboard. It counts the rows of a table that holds every landing file exactly as it arrived. An order lands once as placed and again when it ships. The 3 June file was even delivered twice. So 28 rows are not 28 orders.
Nobody lied on purpose. The table carried no label saying "raw: do not report from this".
Nora's fix is not one query. It is a rule for the whole warehouse: every table gets a job and a place, so a stranger can tell what a table is from its name alone. Those places are called layers.
Three jobs, one direction
Three steps in a row: keep the raw data as it arrived, clean it once, then apply business rules once, with data flowing one way only.
Read it left to right. Each box is one kind of work, and data never flows back to the left.
Three jobs, three layers
A pipeline does three different kinds of work. Mixing them is how a warehouse ends up with orders_final_v2.
- Keep the raw data exactly as it arrived. When a bug is found next month, you can rebuild everything from it.
- Clean it once: fix types, rename columns, drop duplicates. Every later step starts from the same tidy version.
- Apply business logic once: what counts as revenue, what an active customer is. Then publish tables shaped for people and dashboards.
Think of a restaurant kitchen. The delivery bay holds boxes as they came, the prep counter washes and cuts once, and the pass holds finished plates.
Give each job its own layer and "where should this code go?" always has an answer.
Two sets of names for the same three jobs
| Job | dbt names | Medallion | SwiftKart example |
|---|---|---|---|
| Raw, as it arrived | sources | bronze | bronze.ordersraw: every landing row, text columns, plus the file it came from |
| Cleaned, one row per thing | stg staging, int intermediate | silver | silver.orders: typed, deduplicated, latest version of each order |
| Business-ready | fct and dim marts | gold | gold.dailyrevenue, dimcustomer, fctorderline |
Bronze, silver and gold together are called the medallion layout. In dbt, staging is thin: one model per source table that renames, casts and lightly cleans. Joins and business rules live in intermediate models and marts.
Eight raw rows, layer by layer
Bronze, silver and gold for a handful of SwiftKart order rows: raw text with a duplicate and some bad values in bronze, typed and cleaned to one row per order in silver with bad rows set aside, and revenue per country per day in gold.
Press Next layer twice. In silver the duplicate is dropped and two bad rows are set aside with a reason. In gold only revenue per country per day is left.
Bronze, silver and gold at SwiftKart
Now build it for the first three daily order drops, with one Postgres schema per layer.
- Bronze stores every row of every landing file, untouched, with the file it came from. The 3 June retry is in there too: bronze does not judge.
- Silver casts the text to real types and keeps the latest version of each order. Grain: one row per order.
- Gold answers a business question: revenue per day, one row per day.
First follow one order, 1008, all the way through.
Order 1008 through the layers
Order 1008 lands in bronze three times, as placed, as shipped and as shipped again in a retried file; silver keeps one typed row with the latest status; gold counts it once in the revenue of 2 June.
2 June: the order lands. Order 1008 arrives in the 2 June file as
placed. Bronze stores the row as text, with the name of the file it came from.3 June: it lands again. The order shipped, so the 3 June file carries it again with the new status. Bronze updates nothing. It adds a second row.
The same file arrives twice. The 3 June file is delivered again as a retry. Bronze keeps that too. One order, three rows: bronze does not judge.
Silver cleans once. Silver casts the text to real types and keeps the latest version of each order. Three rows become one: order 1008, shipped.
Gold answers the question. Gold adds the order's lines to the revenue of 2 June, the day it was ordered. Three raw rows, counted once.
Read each step from the first box to the last: bronze, then silver, then gold. A dashed box is a layer that has not been built yet.
Bronze to silver to gold
-- silver: typed, one row per order, the latest version of each
CREATE TABLE silver.orders AS
SELECT order_id, customer_id, order_ts, status, updated_at
FROM (
SELECT
order_id::INT AS order_id,
customer_id::INT AS customer_id,
order_ts::TIMESTAMP AS order_ts,
status,
updated_at::TIMESTAMP AS updated_at,
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC, _file DESC) AS rn
FROM bronze.orders_raw
) latest
WHERE rn = 1;
-- gold: one row per order date, business rule applied once
CREATE TABLE gold.daily_revenue AS
SELECT s.order_ts::DATE AS order_date,
COUNT(DISTINCT s.order_id) AS orders,
SUM(i.qty * i.unit_price) AS revenue
FROM silver.orders s
JOIN public.order_items i ON i.order_id = s.order_id
WHERE s.status <> 'cancelled'
GROUP BY s.order_ts::DATE;
SELECT 'bronze.orders_raw' AS table_name, COUNT(*) AS row_count FROM bronze.orders_raw
UNION ALL
SELECT 'silver.orders', COUNT(*) FROM silver.orders
UNION ALL
SELECT 'gold.daily_revenue', COUNT(*) FROM gold.daily_revenue;
The setup loaded the 1 to 3 June drops into bronze.orders_raw: 28 rows. Silver keeps 17, one per order. Gold keeps 3, one per day. Change the last query to SELECT * FROM gold.daily_revenue to see the numbers.
The same three days, layer by layer
Bars compare the row counts for 1 to 3 June: 28 rows in bronze, 17 in silver and 3 in gold.
Tess's 28 is the top bar: rows, not orders. If silver's rule turns out wrong, rebuild silver and gold from bronze. Nothing is lost.
Remember: bronze keeps the full story, silver keeps the truth as of now, gold keeps the answer.
Each layer is written its own way
The three layers are not only read differently. They are also written differently, and the way a layer is written decides what it costs.
Bronze only ever appends. Silver finds each order by its key and replaces the old version. Gold is rebuilt when it is small, and updated one date at a time when it is big.
How each layer is written, and what it costs
Three steps from bronze to silver to gold: bronze is append-only, silver is merged on the key, gold is rebuilt or aggregated incrementally, each with its write cost.
Read it left to right. Appends are cheap, merges cost the files they touch (Lesson 5.4), and overwrites cost their full size on every run. That makes three copies of the data, but bronze is usually the only big one.
Medallion is not a star schema
People mix these two up, so be precise.
Medallion says how refined data is: the stages it passes through. A star schema (Lesson 5.3) says what shape the tables have for analysis: facts and dimensions.
They answer different questions, so they fit together. The gold layer is very often a star schema (fct_order_line, dim_customer) plus a few wide tables. Silver is usually still shaped like the source: one cleaned table per source table.
"We use medallion instead of a star schema" is a red flag. "Our gold layer is a star schema" is a good sentence.
Medallion and star schema
| Medallion (bronze, silver, gold) | Star schema |
|---|---|
| About the stages of processing | About the shape of analytic tables |
| Raw, then clean, then business-ready | Facts in the middle, dimensions around |
| Tells you where a table sits in the pipeline | Tells you what a table measures or describes |
| Popularised by Databricks for lakehouses | Popularised by Ralph Kimball for warehouses |
| Gold can hold a star schema | A star usually lives in gold, or in dbt marts |
Two layering mistakes cause most of the pain. Reading the wrong layer: a dashboard pointed at bronze counts the 3 June retry twice. That was Tess's 28. Logic in the wrong layer: a business rule written in staging gets copied into every model that uses it, and the copies drift apart. Rule of thumb: bronze never changes data, silver never decides business meaning, gold never reads bronze.
A layer rule, checked by code
# Each model and the models it reads from (its parents)
models = {
"stg_orders": ["bronze_orders_raw"],
"stg_order_items": ["bronze_order_items_raw"],
"int_order_totals": ["stg_orders", "stg_order_items"],
"fct_daily_revenue": ["int_order_totals"],
"fct_refunds": ["bronze_payments_raw"], # a shortcut someone took
"stg_customers": ["dim_customer"], # reading backwards
}
LAYER = {"bronze": 0, "stg": 1, "int": 2, "fct": 3, "dim": 3}
def layer(name):
return LAYER[name.split("_")[0]]
for model, parents in sorted(models.items()):
for parent in parents:
if layer(parent) == 0 and not model.startswith("stg_"):
print(f"{model} reads bronze directly: {parent}")
if layer(parent) > layer(model):
print(f"{model} reads a later layer: {parent}")
Two rules: only staging reads bronze, and data never flows backwards. The script finds one model that took a shortcut and one that reads backwards. Real teams run checks like this in CI (Module 10).
Many sources: hubs, links, satellites
One more design lives in the middle layer at some companies. Banks, insurers and retailers that buy other retailers must combine many source systems and prove where every value came from. They often model that layer as a Data Vault, with three kinds of table:
- A hub holds one row per business key:
hub_customer(customer_hk, customer_id, load_ts, record_source). - A link holds one row per relationship between keys:
link_customer_order(link_hk, customer_hk, order_hk, load_ts, record_source). - A satellite holds the describing columns, with history:
sat_customer(customer_hk, load_ts, hashdiff, email, city, country). It gets a new row only when something changed.
Everything is insert-only. No load ever updates a row, so every load is an append and the full history can be audited.
A Data Vault load: everything from staging at once
A graph in three columns: two staging tables feed two hubs, a link and two satellites in parallel, and the vault tables feed a customer dimension and an order fact in the business layer.
Read it left to right. The price of a vault is joins: "each customer as they are today" needs a hub, a satellite and a latest-row filter. So teams publish a star or views on top (green) for people to query.
Hash keys let every table load at once
Look at the middle column. All five vault tables read staging directly, and none reads another. How can a link load before its hubs?
Data Vault 2.0 keys every table by a hash of the business key: customer_hk = md5(upper(trim(customer_id))). A link's key is the hash of both business keys together. A hash is computed from the staging row itself, so no loader waits for another to hand out a key.
Change detection uses the same trick. The hashdiff is one hash of a satellite's describing columns. Compare that one value with the latest satellite row, and insert only when it differs.
Clean the text before you hash it (trim, one letter case, a fixed separator, NULLs replaced), or ' [email protected]' and '[email protected]' become two customers.
A hub and a satellite with a hashdiff
CREATE TABLE hub_customer (
customer_hk TEXT PRIMARY KEY,
customer_id INT NOT NULL,
load_ts TIMESTAMP NOT NULL,
record_source TEXT NOT NULL
);
CREATE TABLE sat_customer (
customer_hk TEXT NOT NULL,
load_ts TIMESTAMP NOT NULL,
hashdiff TEXT NOT NULL,
email TEXT,
city TEXT,
country TEXT,
PRIMARY KEY (customer_hk, load_ts)
);
-- load 1, 12 June: hub and satellite read the same staging rows, each on its own
INSERT INTO hub_customer
SELECT md5(customer_id::text), customer_id, TIMESTAMP '2025-06-12 02:00', 'shop.customers'
FROM customers;
INSERT INTO sat_customer
SELECT md5(customer_id::text), TIMESTAMP '2025-06-12 02:00',
md5(concat_ws('|', COALESCE(lower(trim(email)), ''), city, country)),
email, city, country
FROM customers;
-- 13 June: Ken moves to Osaka in the shop's database
UPDATE customers SET city = 'Osaka' WHERE customer_id = 4;
-- load 2: a satellite row only where the hashdiff differs from the latest one
WITH stg AS (
SELECT md5(customer_id::text) AS customer_hk,
md5(concat_ws('|', COALESCE(lower(trim(email)), ''), city, country)) AS hashdiff,
email, city, country
FROM customers
),
latest AS (
SELECT DISTINCT ON (customer_hk) customer_hk, hashdiff
FROM sat_customer
ORDER BY customer_hk, load_ts DESC
)
INSERT INTO sat_customer
SELECT s.customer_hk, TIMESTAMP '2025-06-13 02:00', s.hashdiff, s.email, s.city, s.country
FROM stg s
LEFT JOIN latest l ON l.customer_hk = s.customer_hk
WHERE l.hashdiff IS DISTINCT FROM s.hashdiff;
SELECT (SELECT COUNT(*) FROM hub_customer) AS hub_rows,
(SELECT COUNT(*) FROM sat_customer) AS sat_rows,
(SELECT COUNT(*) FROM sat_customer WHERE load_ts = TIMESTAMP '2025-06-13 02:00') AS changed;
Load 2 compared one hash per customer with the latest satellite row and inserted only Ken's new version: 30 hub rows, 31 satellite rows. Nothing was updated. The LEFT JOIN also catches customers seen for the first time.
Numbers to remember
| Thing | Value | What it means |
|---|---|---|
| dbt folders | models/staging, models/intermediate, models/marts | the same three jobs, in dbt's names (Module 8) |
| Databricks | medallion is the default layout | Auto Loader writes bronze Delta tables; notebooks or Lakeflow Declarative Pipelines (formerly Delta Live Tables) build silver and gold (Module 13) |
| Both at once | common | dbt models running on a lakehouse whose schemas are called bronze, silver and gold |
| Bronze | usually the only big copy | so it gets compression and a retention policy |
| Vault keys before 2.0 | sequence keys | they forced hubs to load first and links after |
| Layer checks in dbt | dbtprojectevaluator | a package that checks rules like the two above |
None of these change the idea: three jobs, three layers, one direction.
What changed at SwiftKart
The five mystery tables are gone. SwiftKart now has bronze.orders_raw, silver.orders and gold.daily_revenue, and each name says what the table is. Tess's dashboard reads gold, where every order counts once. Her 28 was rows in bronze. Behind them were 17 orders.
A small script in CI checks the two rules on every change: only staging reads bronze, and nothing reads backwards.
That closes Module 5. You can say what one row means, tell a fact from a dimension, draw the star, keep history and put every table in a layer. Module 6 builds the pipeline that fills those layers every night. It starts with Lesson 6.1, Anatomy of a pipeline.
In one line
Bronze keeps raw data unchanged, silver cleans it once, gold applies business rules once; medallion is about stages, a star schema is about shape, and gold often holds a star.
Interview corner
What are the bronze, silver and gold layers?
Bronze is raw data exactly as it arrived, kept so everything can be rebuilt. Silver is cleaned and conformed: typed, deduplicated, one row per entity, usually still shaped like the source. Gold is business-ready: facts, dimensions and aggregates that dashboards and models read, with business rules applied once.
Is medallion an alternative to a star schema?
No. Medallion describes how refined data is as it moves through a pipeline; a star schema describes how analytic tables are shaped. They work together: the gold layer is very often a star schema plus some wide tables built from it.
What is Data Vault and when would you use it?
A modelling approach for the integration layer with hubs (business keys), links (relationships) and satellites (attributes with history). It is insert-only and auditable, and it handles many sources loading in parallel. Teams usually still publish star schemas on top, because querying a vault directly takes many joins.
Why does Data Vault 2.0 use hash keys instead of sequences, and what does that cost?
A hash key is computed from the normalised business key, so hubs, links and satellites can all load from staging at the same time, and reloads or a second source produce the same keys. Sequences need a lookup, so links must wait for hubs. The cost is width (16 bytes binary or 32 characters of text against an 8-byte integer, hardly compressible), the need to normalise inputs identically everywhere, and a tiny collision risk that MD5 keeps around 10⁻²¹ at a billion keys. The hashdiff applies the same idea to change detection.