Layers and materialisations
Part of the free LogicWiz Data Engineering course, Module 8: Transformation as code: dbt. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:15 on Wednesday. Tess has two dashboards open, and they show two different revenue numbers for the same day. Each one takes 40 seconds to load. Nothing failed overnight. The dbt project has grown to 30 models in one folder, and three of them clean the raw orders, each a little differently.
You'll learn to
- Sort models into sources, staging, intermediate and marts
- Choose how a model is stored: view, table or ephemeral
- Predict what a view and a table show after new data lands
- Work out which choice scans fewer gigabytes a day
Learn
Three cleaners, three truths
Start with the two numbers that disagree.
Both dashboards count the same orders. But each reads a different model that cleans the raw orders table, and the three cleaning models do not agree on the details. Fix a bug in one and the other two still have it.
Nora asks one question: "How many models are allowed to read the raw orders table?" Today the answer is three. It should be one.
Look at the picture. Follow the arrows back from each dashboard to the raw table.
Three cleaners, two answers
One raw orders table feeds three separate cleaning models; dashboard A reads the first and dashboard B reads the third, so the two dashboards can show different revenue.
Read it left to right. The two dashboards reach the same raw table through different cleaning models, so nothing forces their numbers to match.
Give every step one home
The fix is to sort the models into layers. A layer is a group of models with one job, and each job is done in exactly one place.
Think of a restaurant kitchen. Deliveries come in at the back door. Everything is washed and chopped once, at the prep station. The cooks combine the prepped food, and only finished plates go out to the tables. No cook walks to the back door for an unwashed carrot.
dbt projects use four layers. Each has a name and a prefix, so anyone can open the project and tell what a model is for from its name alone. Data flows one way through them.
The layers of a dbt project
| Layer | Prefix | What goes there | At SwiftKart |
|---|---|---|---|
| Sources | (YAML) | Raw tables as the loader left them. Declared, never changed | shop.orders, shop.payments |
| Staging | stg | One model per source table: rename, cast, fix units. No joins | stgorders, stgpayments |
| Intermediate | int | Joins and logic that several marts reuse | intordertotals |
| Marts | fct, dim | What people and dashboards query: facts and dimensions | fctdailyrevenue, dimcustomers |
Marts read intermediate or staging models, never a raw source. This is the bronze, silver and gold idea from Module 5, named the dbt way.
SwiftKart, in four layers
Two raw tables feed two staging models, which join into one intermediate model, which feeds the mart fct_daily_revenue. Every arrow goes one layer forward.
Read it left to right: every arrow goes one layer forward, and only the staging models touch a raw table.
Staging: clean each raw table once
The prep station is the staging layer: one model per raw table, and it is the only model allowed to read that table.
A staging model does light work. It renames columns to your standard (paid_ts becomes paid_at), casts types, converts units and lower-cases codes. It does not join or aggregate.
The payoff comes the day the source changes. When the shop renames a column, you fix one staging model. Every model after it keeps working, because it only ever saw your clean names.
Joins and sums that several marts need go one layer on, into an intermediate model. Run the project below: three layers, four models.
Three layers at SwiftKart
import minidbt
models = {
# staging: one model per source table
'stg_orders': """
select order_id, customer_id, cast(order_ts as date) as order_date, status
from {{ source('shop', 'orders') }}
""",
'stg_order_items': """
select order_id, product_id, qty, unit_price, qty * unit_price as line_amount
from {{ source('shop', 'order_items') }}
""",
# intermediate: logic that several marts reuse
'int_order_totals': """
select o.order_id, o.customer_id, o.order_date, o.status, sum(i.line_amount) as order_total
from {{ ref('stg_orders') }} as o
join {{ ref('stg_order_items') }} as i on i.order_id = o.order_id
group by o.order_id, o.customer_id, o.order_date, o.status
""",
# mart: what the dashboard reads
'fct_daily_revenue': """
{{ config(materialized='table') }}
select order_date, count(*) as orders, round(sum(order_total), 2) as revenue
from {{ ref('int_order_totals') }}
where status in ('placed', 'shipped', 'delivered')
group by order_date
""",
}
project = minidbt.Project(models=models)
project.build()
project.lineage()
Only the two staging models call source(). A second mart, say revenue per customer, would read int_order_totals too, so the order total is worked out once.
Remember: each raw table is read by exactly one staging model. Everything else reads through ref().
Why the dashboard takes 40 seconds
One number is fixed. The 40 seconds are still there.
When dbt builds a model, it can save one of two things. It can save the query alone, so the work is done again each time someone reads it. That is a view. Or it can run the query once and save the rows. That is a table. How a model is stored is called its materialisation, and a view is the default.
In kitchen terms, a view is a dish cooked from scratch for every order. A table is cooked once in the morning and served from the fridge.
So far every SwiftKart model is a view. The dashboard reads a view on a view on a view, and each read re-runs the whole chain over the raw data.
How a model is stored: its materialisation
| view (the default) | table |
|---|---|
| Stores only the query | Stores the result rows |
| Always fresh: reads its inputs every time it is queried | A copy as of the last build: new source rows appear after the next build |
| Free to build, can be slow to query | Costs time and storage to build, fast to query |
| Good for staging and light models | Good for marts that dashboards read all day |
A view and a table after the source changes
import duckdb
import minidbt
project = minidbt.Project(models={
'stg_orders': "select order_id, status from {{ source('shop', 'orders') }}",
'fct_order_count': "{{ config(materialized='table') }} select count(*) as n from {{ ref('stg_orders') }}",
}, quiet=True)
def counts(when):
view = duckdb.sql("select count(*) from stg_orders").fetchone()[0]
table = duckdb.sql("select n from fct_order_count").fetchone()[0]
print(f"{when:<22} view: {view} table: {table}")
project.build()
counts("after the build")
duckdb.sql("insert into shop.orders values (1081, 4, '2025-06-15 09:00:00', 'placed', 'USD', '2025-06-15 09:00:00')")
counts("a new order lands")
project.build()
counts("after the next build")
quiet=True hides the build log. The insert into shop.orders stands in for the loader writing a new order between two dbt builds.
A new order lands
A raw table, a view over it and a table built from the view. After the build all show 80; when a new order lands the view shows 81 and the table still 80; after the next build both show 81.
After the build. The raw table has 80 orders. The view shows 80, and the table stored the number 80.
A new order lands. The loader writes order 1081. The view reads the raw table each time it is queried, so it shows 81 at once. The table still holds the 80 it stored.
After the next build. dbt runs the table's query again and stores 81. The two agree until the next order arrives.
Watch the right-hand box: a table is only as fresh as its last build. That is why a scheduler runs dbt after every load (Module 9).
Remember: a view is a saved query: always fresh, and every read pays. A table is a copy: fast to read, and only as fresh as its last build.
Defaults per folder, and declared sources
Runs with dbt:
# models/staging/sources.yml
version: 2
sources:
- name: shop
schema: raw_shop
loaded_at_field: _loaded_at
freshness:
warn_after: {count: 12, period: hour}
error_after: {count: 24, period: hour}
tables:
- name: orders
- name: order_items
- name: payments
# dbt_project.yml (part of it)
models:
swiftkart:
staging:
+materialized: view
marts:
+materialized: table
The bottom lines are how real projects choose: one default per folder, so most models need no config() line. The top file declares the raw tables once and adds a freshness check: the loader stamps _loaded_at on every row it writes, and dbt source freshness warns when the newest stamp is more than 12 hours old.
A rebuild nobody sees
So the marts become tables. That raises a worry. fct_daily_revenue takes minutes to rebuild each night. What does a dashboard see if it reads halfway through?
It sees yesterday's table, complete.
On Postgres, dbt never empties the live table. It builds the new rows under a temporary name. When they are ready, it swaps the names inside one transaction. Until the commit, readers get the old table. After it, they get the new one. Never a half-built mix.
Step through it.
A table rebuild on Postgres, while a dashboard reads
A sequence between dbt, Postgres and a dashboard: dbt builds the new table under a temporary name inside a transaction, the dashboard keeps reading the old table, dbt renames the tables and commits, and the next read sees the new rows.
Build under another name. dbt opens a transaction and creates
fct_daily_revenue__dbt_tmpfrom the model's SELECT. The live table is untouched.A dashboard reads meanwhile. It asks for
fct_daily_revenueand gets yesterday's rows: the old table, whole.Swap the names, then commit. dbt renames the live table to a backup name, renames the new one into place, and commits. The swap is atomic: all of it happens, or none of it.
The next read. The dashboard now gets today's rows, and dbt drops the backup. Had the build failed, the old table would still be in place.
Read it top to bottom. The renames take a short exclusive lock, so a query that arrives during them waits a moment instead of failing.
A model that is never stored
There is a third choice, for small helpers. An ephemeral model is not built at all. dbt pastes its SQL into every model that reads it, like a note copied into each recipe that needs it.
Nothing appears in the warehouse. That has three costs:
- Nobody can select from it on its own, so a dashboard cannot read it.
- It cannot have a contract (Lesson 8.3).
- Three models that read it compute it three times.
Run the card. Look at which models ls() lists, and at the compiled SQL of the model that reads the helper.
Ephemeral: pasted in, never built
import minidbt
project = minidbt.Project(models={
'int_paid_orders': """
{{ config(materialized='ephemeral') }}
select order_id from {{ source('shop', 'payments') }} where status = 'captured'
""",
'fct_paid_count': "select count(distinct order_id) as paid from {{ ref('int_paid_orders') }}",
})
print(project.ls())
print(project.compile('fct_paid_count'))
ls() lists only fct_paid_count: the helper is not on the build list. Its SELECT sits inside the compiled SQL instead. Real dbt pastes it in as a CTE named __dbt__cte__int_paid_orders; minidbt pastes a subquery.
View or table: do the sums
Which marts deserve to be tables? Count the gigabytes.
fct_customer_revenue joins four models. The join scans 40 GB and produces a 200 MB result. The dashboard reads it 500 times a day.
As a view, every read runs the join:
- 500 reads × 40 GB = 20,000 GB a day
As a table, one nightly build runs the join, and each read scans the small result:
- build: 40 GB
- reads: 500 × 0.2 GB = 100 GB
- total: 140 GB a day
The table wins as soon as the model is read more than about once a day. A view still wins for models read rarely, for data that changes faster than you rebuild, and for staging models that only feed tables.
GB scanned a day for one mart
Two bars: 20,000 GB a day when the mart is a view read 500 times, against 140 GB a day when it is a table built once and read 500 times.
Each bar is one day of scanning for the same mart. BigQuery's on-demand pricing bills bytes scanned, and Snowflake bills warehouse seconds that grow with them, so the bars are the bill too.
Two opposite mistakes. Views on views on views make every dashboard query re-run the whole chain over raw data: that is the 40-second dashboard. Making every model a table copies the same data many times and makes each build slower and costlier. The usual default: staging as views, marts as tables, and very large facts as incremental models (Lesson 8.4).
Numbers to remember
| Name | What to remember |
|---|---|
| Default materialisation | a view |
| Per-folder default | +materialized: view or table in dbtproject.yml; override a single model with config() only when there is a reason |
| Declaring a source | gives one place to change its schema, a start for the lineage graph, and a freshness check |
| Source freshness in the example | warnafter 12 hours, errorafter 24 hours, read from loadedatfield; checked by dbt source freshness |
| A table on Postgres | built as <namedbttmp, the live table renamed to <namedbtbackup, swapped in one transaction, backup dropped |
| A table on Snowflake | transient by default: no Fail-safe and at most 1 day of Time Travel, cheaper for tables you can always rebuild |
| A table on Databricks | a Delta table |
| Ephemeral | pasted into each reader as a CTE named dbtcte<model; cannot be queried, cannot have a contract |
| materializedview | the warehouse keeps the result fresh itself; on Snowflake dbt builds a dynamic table instead |
| Break-even in the example | reads × (40 − 0.2) = 40, so about one read a day |
| What you pay for | a view costs nothing to build and every query pays for the work; a table costs storage and build time once |
What changed at SwiftKart
The three cleaning models are gone. One stg_orders reads the raw orders, and every other model reads it through ref(). Tess's two dashboards now trace back to the same cleaned table, so they show the same revenue.
The staging models stayed views. The marts became tables, rebuilt after each load, so a dashboard reads stored rows and no longer re-runs the whole chain.
But nobody has checked what is in those tables. Soon finance's "new customers in June" number counts one person three times. Lesson 8.3 adds tests, so a wrong number stops the build before Tess sees it.
In one line
Clean each raw table once in staging, reuse joins in intermediate models and serve marts; a view is always fresh but recomputes on every read, a table is fast but only as fresh as its last build.
Interview corner
How do you structure a dbt project?
Sources are declared in YAML. Staging models are 1:1 with source tables and only rename, cast and standardise. Intermediate models hold joins and logic reused by several marts. Marts are the facts and dimensions people query. Data flows one way, so each source is cleaned once and a source change is absorbed in one staging model.
View, table, incremental or ephemeral: how do you choose?
A view is cheap to build and always fresh, but recomputes on every query: good for staging and light models. A table is fast to query but only as fresh as its last build: good for marts. Incremental tables process only new or changed rows: for large facts. Ephemeral models are inlined as CTEs: small helpers that nobody queries.
A table model takes 10 minutes to rebuild. What do readers see meanwhile on Postgres and on Snowflake, and what happens if the build fails halfway?
On Postgres dbt builds the new table as model__dbt_tmp inside a transaction, renames the live table to a backup and the new one into place, commits, then drops the backup, so readers see the old rows until the commit and a failed build leaves the old table as it was. On Snowflake dbt uses create or replace, which Snowflake runs atomically, and by default the table is transient, so there is no Fail-safe copy to pay for. Either way a reader never sees a half-built table, and the cost of a rebuild is the full scan every time.
Why declare sources instead of selecting from raw tables?
A declared source gives one place to set the raw schema and table names, so moving the raw data is a one-line change. It starts the lineage graph, so you can see every model a raw table feeds. And it enables freshness checks that warn when the loader is late.