How dbt works inside

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 4:40 on Thursday. You changed two files, and CI has been running dbt build for 70 minutes. The project has grown to 400 models, and every pull request builds all of them, with a warehouse bill to match. Nora reads the log and says: "More threads will not fix this. Look at what dbt reads, what it compares and what SQL it really sends."

You'll learn to

  • Trace dbt build from parse to run results
  • Build only what a pull request changed, with state:modified+ and --defer
  • Read the SQL each incremental strategy sends
  • Work out run time from threads and the critical path

Learn

Seventy minutes for two changed files

Why does a two-file change build 400 models? Because nobody told dbt what changed. To tell it, you need to know what happens between typing dbt build and the first query.

dbt works like a builder with a blueprint. First it reads every file and draws the whole plan. Only then does it pick which parts to build, write their SQL and send it to the warehouse.

There are six stages. Step through them in the next picture. The first two never touch the warehouse, and everything that follows rests on that.

One dbt build, stage by stage

Six stages running down the page, lit one at a time: parse the files, write the manifest, select nodes, compile Jinja into SQL, execute on a pool of threads, and write the run results.

  1. Parse. dbt reads every .sql and .yml file and records the ref(), source() and config() calls it finds. No SQL runs, and execute is false. Partial parsing re-reads only the files that changed since last time.

  2. Manifest. dbt calls each model, test or source a node, and writes one graph of all of them to target/manifest.json. The command dbt parse stops here. Nothing has reached the warehouse yet.

  3. Select. --select, --exclude and state: pick which nodes this run will build. Until today, CI picked all 400.

  4. Compile. dbt renders the Jinja of the chosen nodes into SQL, this time with execute true. Each ref() becomes a real table name. The SQL lands in target/compiled/, and dbt compile stops here.

  5. Execute. A pool of threads workers runs each node as soon as its parents are done, through its materialisation. The statements that ran are kept in target/run/.

  6. Artifacts. dbt writes run_results.json: the status and the seconds of every node. Files such as this one and the manifest are called artifacts.

Read it top to bottom, one stage per step. The label on each arrow is what one stage hands to the next.

The manifest: your project as one file

Open target/manifest.json and you find the whole project as data: every model, test, seed, snapshot and source.

Each node has a name tag called its unique_id, such as model.swiftkart.stg_orders. For every node the file records four things you will use today:

  • its config;
  • the table or view it builds;
  • the nodes it depends_on;
  • a checksum of its file: a short fingerprint that changes when the file changes.

Two more lists, parent_map and child_map, store the arrows of the DAG in both directions.

A test is a node too, with its model as parent. That is how dbt build knows to run it before the model's children.

Part of SwiftKart's manifest, as a graph

Sources on the left feed two staging models; a unique test hangs off stg_orders; two marts depend on the staging models, each node named by its unique_id.

Follow the arrows from the sources to the marts. Each arrow is one entry in parent_map and one in child_map. The docs site, state: selection, --defer and orchestrators such as Astronomer Cosmos and Dagster all read these same edges.

Read a manifest

import json
import minidbt

models = {
    'stg_orders': "select order_id, customer_id, cast(order_ts as date) as order_date, status from {{ source('shop', 'orders') }}",
    'stg_customers': "select customer_id, country from {{ source('shop', 'customers') }}",
    'fct_daily_orders': "{{ config(materialized='table') }}\nselect order_date, count(*) as orders from {{ ref('stg_orders') }} group by 1",
    'fct_orders_by_country': "{{ config(materialized='table') }}\nselect c.country, count(*) as orders\nfrom {{ ref('stg_orders') }} as o join {{ ref('stg_customers') }} as c using (customer_id)\ngroup by 1",
}
project = minidbt.Project(models=models, schema='analytics')
manifest = project.manifest('target/manifest.json')   # like dbt parse: nothing runs

node = manifest['nodes']['model.swiftkart.fct_orders_by_country']
print(json.dumps({k: node[k] for k in ['resource_type', 'relation_name', 'config', 'depends_on']}, indent=2))
print('checksum:', node['checksum']['checksum'][:16], '...')
print('children of stg_orders:', manifest['child_map']['model.swiftkart.stg_orders'])

This is what dbt parse does: nothing runs in the warehouse. Find the four things from the list above in the output. minidbt writes a cut-down manifest with the same field names; a real one has these keys among many more.

What changed since production?

Now the fix for CI. Production also wrote a manifest on its last run. Keep that file, and CI can compare: the manifest it parsed a minute ago against production's.

dbt build --select state:modified --state prod-artifacts/ does that. A node counts as modified if it is new, or if its SQL, its configs, its database, schema or alias, a macro it uses, or its contract changed. No Git is involved: it is one manifest against another.

There is a catch. state:modified selects only the changed nodes, and a change to stg_orders can break every model below it. Add a + and dbt also selects everything downstream: state:modified+.

state:modified without the + tests nothing downstream. A pull request that renames a column in stg_orders passes CI, because only stg_orders was built. Production then breaks on every mart that reads the old name. Use a fresh production manifest too: with last week's, changes that already shipped look modified.

Borrow production for the rest

Building only the changed models leaves a hole: in the CI schema the unchanged parents do not exist.

--defer fills the hole. When dbt compiles a ref() to a node that is not selected and does not exist in your schema, it uses the table recorded in production's manifest instead. Think of borrowing a neighbour's ladder instead of building one. If your schema has its own copy, that copy wins, unless you add --favor-state.

The two flags together are called Slim CI: one changed mart means one table built in dbt_ci_pr_42, reading production's staging models.

The cost is mixing environments: a relationships test can end up comparing a CI table with a production table.

Slim CI for one pull request

A sequence between the pull request, the CI runner, the stored production artifacts and the warehouse: CI downloads the production manifest, selects only the changed model, builds it in a pull-request schema while reading unchanged parents from production, runs its tests and reports back.

Read it top to bottom. The divider is the moment --defer acts: the parent is not selected and not in the CI schema, so the next line reads it from analytics. One table is built instead of 400 models.

Remember: Slim CI is two flags. state:modified+ picks what changed and everything below it. --defer reads everything else from production.

state:modified+ and --defer in minidbt

import minidbt

models = {
    'stg_orders': "select order_id, customer_id, cast(order_ts as date) as order_date, status from {{ source('shop', 'orders') }}",
    'stg_customers': "select customer_id, country from {{ source('shop', 'customers') }}",
    'fct_daily_orders': "{{ config(materialized='table') }}\nselect order_date, count(*) as orders from {{ ref('stg_orders') }} group by 1",
    'fct_orders_by_country': "{{ config(materialized='table') }}\nselect c.country, count(*) as orders\nfrom {{ ref('stg_orders') }} as o join {{ ref('stg_customers') }} as c using (customer_id)\ngroup by 1",
}

# 1. production builds and keeps its manifest
prod = minidbt.Project(models=models, schema='analytics', quiet=True)
prod.build()
prod.manifest('prod-artifacts/manifest.json')

# 2. a pull request changes one mart
pr = dict(models)
pr['fct_daily_orders'] = pr['fct_daily_orders'].replace('count(*) as orders', 'count(*) as orders, count(distinct customer_id) as customers')

# 3. CI builds what changed and reads everything else from production
ci = minidbt.Project(models=pr, schema='dbt_ci_pr_42', state='prod-artifacts/manifest.json', defer=True)
print(ci.ls('state:modified+'))
print(ci.compile('fct_daily_orders'))
ci.build(select='state:modified+')

Look at the compiled SQL: it reads analytics.stg_orders. The parent was not selected and does not exist in dbt_ci_pr_42, so --defer used production's table from the manifest. Change stg_orders instead and both marts are selected.

Each strategy is one statement

CI is quick now. The other half of the bill is what each run sends to the warehouse.

Every incremental run first puts the model's SELECT, filter included, into a temporary table named <model>__dbt_tmp. Then the strategy decides which statement moves the batch into the table:

  • append: insert the batch. No key, no checks.
  • delete+insert: delete the table rows whose unique_key is in the batch, then insert the batch.
  • merge: one MERGE that updates matching keys and inserts the rest. Without a unique_key it acts like append.
  • insert_overwrite: replace whole partitions, such as whole days.

merge: what dbt sends to Snowflake or Databricks

Runs with dbt:

-- unique_key='order_id'; the batch is already in fct_orders__dbt_tmp
merge into analytics.fct_orders as DBT_INTERNAL_DEST
using analytics.fct_orders__dbt_tmp as DBT_INTERNAL_SOURCE
on (DBT_INTERNAL_SOURCE.order_id = DBT_INTERNAL_DEST.order_id)
when matched then update set
    order_id = DBT_INTERNAL_SOURCE.order_id,
    customer_id = DBT_INTERNAL_SOURCE.customer_id,
    status = DBT_INTERNAL_SOURCE.status,
    updated_at = DBT_INTERNAL_SOURCE.updated_at
when not matched then insert
    (order_id, customer_id, status, updated_at)
values
    (order_id, customer_id, status, updated_at);

DBT_INTERNAL_DEST is the table and DBT_INTERNAL_SOURCE is the batch: incremental_predicates refer to them by these names. merge_update_columns limits the update set list. Databricks writes the same statement as update set * and insert *.

delete+insert and append: what dbt sends to Postgres

Runs with dbt:

-- delete+insert (the dbt-postgres default when unique_key is set)
delete from analytics.fct_orders
where (order_id) in (
    select distinct order_id
    from fct_orders__dbt_tmp as DBT_INTERNAL_SOURCE
);

insert into analytics.fct_orders (order_id, customer_id, status, updated_at)
(
    select order_id, customer_id, status, updated_at
    from fct_orders__dbt_tmp
);

-- append (no unique_key): only the insert runs

Two statements inside one transaction. Duplicate keys in the batch do not fail here: both copies are inserted, which is why the batch must be deduplicated first.

One batch, four ways to apply it

A two-row batch beside a three-row table, applied four ways: append leaves order 2 in the table twice, delete+insert and merge leave one row per order, and insert_overwrite by day replaces 12 and 13 June whole, which loses order 3.

  1. Before the run. The table holds three orders. The batch in fct_orders__dbt_tmp holds two rows: order 2 has shipped, and order 4 is new. These rows are made up for the picture.

  2. append. One insert. Order 2 is now in the table twice, once placed and once shipped. Cheap, and wrong for rows that change.

  3. delete+insert. Delete the table rows whose key is in the batch, here order 2. Then insert the batch. Four rows, one per order.

  4. merge. The same four rows from one statement: order 2 is updated where it sits, and order 4 is inserted. To find order 2, the warehouse reads the whole table unless a predicate narrows the search.

  5. insert_overwrite, by day. The batch touches 12 and 13 June, so both days are replaced whole. Order 3 was also placed on 12 June but is not in the batch: it is gone. Re-select all rows of every day you touch.

Read each step left to right: the batch, then the table after the statement ran. Every step starts again from the three rows of the first one.

insert_overwrite: what dbt sends to BigQuery

Runs with dbt:

-- partition_by={'field': 'event_date', 'data_type': 'date'}, dynamic partitions
declare dbt_partitions_for_replacement array<date>;

-- 1. the batch
create temporary table fct_events__dbt_tmp as (
    select ...  -- the model's SELECT, filter included
);

-- 2. which partitions does the batch touch?
set (dbt_partitions_for_replacement) = (
    select as struct array_agg(distinct event_date)
    from fct_events__dbt_tmp
);

-- 3. delete those partitions and insert the batch, in one statement
merge into analytics.fct_events as DBT_INTERNAL_DEST
using (select * from fct_events__dbt_tmp) as DBT_INTERNAL_SOURCE
on FALSE
when not matched by source
    and DBT_INTERNAL_DEST.event_date in unnest(dbt_partitions_for_replacement)
    then delete
when not matched then insert (event_id, event_date, customer_id, event_type)
    values (event_id, event_date, customer_id, event_type);

on FALSE means nothing ever matches, so every batch row is inserted and every table row in a replaced partition is deleted. Snowflake has no partitions to overwrite: there, insert_overwrite truncates and reloads the whole table.

microbatch: one query per day

The last strategy arrived in dbt 1.9. microbatch cuts an incremental model by time, like a loaf into slices, and runs one query per slice.

You tell dbt three things: event_time, the column that says when a row happened; batch_size, such as day; and begin, where a full build starts. You write no is_incremental() filter. dbt adds a time filter for each batch itself.

A normal run processes the current batch plus lookback earlier ones. The default lookback is 1, so a daily model reruns yesterday and today.

Batches are independent. They can run at the same time, dbt retry reruns only the failed ones, and a backfill is one command: dbt run --event-time-start "2024-09-01" --event-time-end "2024-09-04".

A normal microbatch run on 2 October 2024

One daily microbatch model with a lookback of 1, run on 2 October 2024: two boxes, one for the batch of 1 October and one for the batch of 2 October, each with the time filter dbt adds for it.

Each box is one batch and one query. The line under it is the filter dbt adds to every upstream ref or source that declares event_time. An upstream model without event_time is scanned in full for every batch.

The strategies side by side

StrategyWhat runsReads of the targetTwo batch rows, one keyDefault on
appendinsertnoneboth insertedPostgres without a key
delete+insertdelete by key, insertrows with batch keysboth insertedPostgres with a key
mergeone MERGEthe whole table, unless predicates narrow iterrorSnowflake, BigQuery, Databricks
insertoverwritereplace partitionsthe partitions in the batchboth insertedopt in (BigQuery, Spark)
microbatchone replace per time batchthe batch's time windowthe adapter's strategy decidesopt in, dbt 1.9+

Choose by the shape of change: rows that update need a key (merge or delete+insert); data that arrives by day suits insert_overwrite or microbatch.

Threads cannot beat the longest chain

Back to Nora's remark about threads. threads is the most models dbt works on at once. Think of checkout lanes in a shop: more lanes help only while there are customers ready to pay.

Two things limit it.

  • The graph. A model cannot start before its parents finish. So a run can never be shorter than its critical path: the slowest chain from a source to a mart. Extra threads sit idle.
  • The warehouse. A Snowflake warehouse runs 8 statements at once by default and queues the rest. Threads past that limit wait in the queue.

The picture shows SwiftKart's seven models on two threads. The red bars are the critical path.

Seven models on two threads

A timeline of two threads: thread 1 runs stg_customers, stg_orders, dim_customers and fct_customer_revenue; thread 2 runs stg_order_items, int_order_totals and fct_daily_revenue; the run ends at 140 seconds, the length of the critical path.

Read each lane left to right: one lane is one thread. Thread 1 idles from 45 s to 90 s, waiting for int_order_totals. The red chain is stg_order_items (30) + int_order_totals (60) + fct_customer_revenue (50) = 140 s.

A thread pool walking the DAG

PARENTS = {
    'stg_orders': [], 'stg_order_items': [], 'stg_customers': [],
    'int_order_totals': ['stg_orders', 'stg_order_items'],
    'dim_customers': ['stg_customers'],
    'fct_daily_revenue': ['int_order_totals'],
    'fct_customer_revenue': ['int_order_totals', 'dim_customers'],
}
SECONDS = {'stg_orders': 20, 'stg_order_items': 30, 'stg_customers': 10, 'int_order_totals': 60,
           'dim_customers': 15, 'fct_daily_revenue': 40, 'fct_customer_revenue': 50}

def depth(model):
    return 1 + max((depth(p) for p in PARENTS[model]), default=-1)

def run(threads):
    """A pool of `threads` workers: whenever one is free, start the next ready model."""
    done, running, clock, log = {}, {}, 0, []
    while len(done) < len(PARENTS):
        ready = sorted((depth(m), m) for m in PARENTS
                       if m not in done and m not in running and all(p in done for p in PARENTS[m]))
        while ready and len(running) < threads:
            _, m = ready.pop(0)
            running[m] = clock + SECONDS[m]
            log.append(f'{clock:>4} s  start {m}')
        clock = min(running.values())             # jump to the next model that finishes
        for m in [m for m, end in running.items() if end == clock]:
            done[m] = running.pop(m)
    return clock, log

for threads in (1, 2, 4):
    print(f'threads={threads}: {run(threads)[0]} s')
print()
print('\n'.join(run(2)[1]))

A simple model of the pool: ready models start shallowest first, then by name. One thread takes 225 s, the sum of all seven. Two reach the critical path, 140 s. Four add nothing. To go faster, shorten the critical path: make int_order_totals incremental, or split it.

Numbers to remember

NameValueWhat it is
Static parserat least 3 times faster, about 60% of real models (dbt's figures)Reads ref, source and config without a full Jinja render.
target/partialparse.msgpackthe state of partial parsingChanging --vars, profiles.yml, dbtproject.yml, packages or the dbt version forces a full parse.
uniqueid<resourcetype.<project.<nameFor example model.swiftkart.stgorders.
manifest.jsonwritten by nearly every commandAll but deps, clean, debug and init.
state:modified.body, .configs, .relation, .macros, .contractone kind of change eachTags and meta never count; a description counts only with persistdocs on. Removing or retyping a column of a model with an enforced contract is a breaking change: dbt raises an error here, before anything is built.
--defernever for ephemeral modelsWatch filters you apply only on development targets: they change the numbers you test.
CI schemadbtcloudpr123456 on the dbt platformIts jobs keep each run's artifacts and compare for you. On dbt Core, CI downloads production's manifest.json from object storage (S3, ADLS).
microbatch batchsizehour, day, month or yearEach adapter replaces a batch its own way: merge on Postgres, delete+insert on Snowflake and Redshift, insertoverwrite on BigQuery and Spark, replacewhere on Databricks.
threadsprofiles.yml or --threadsIn dbt v1 each thread runs its query on its own adapter connection.
MAXCONCURRENCYLEVEL8 on a Snowflake warehouseStatements run at once. Postgres caps connections with maxconnections; BigQuery has per-project concurrency limits.
dbt v2the Rust engineParsing is a different program and jobs no longer accept the partial-parse flags. A thread is an open warehouse connection, and threads: 0 lets dbt choose. It understands SQL, so it catches some errors before the warehouse. The Python engine is maintained as dbt v1.

What changed at SwiftKart

CI now downloads production's manifest and runs dbt build --select state:modified+ --defer --state prod-artifacts. Your two-file pull request builds the changed models and what sits below them, not all 400.

The team also reads the SQL behind each incremental model before choosing its strategy. And nobody asks for more threads first: they look for the critical path.

One question is left. Who starts dbt build every hour, after the load has landed, and tries again when it fails? That is a scheduler's job, and Module 9 begins with it: Lesson 9.1, DAGs, tasks and schedules.

In one line

dbt parses the project into a manifest, selects nodes (in CI, state:modified+ with --defer), compiles Jinja to SQL and runs it on threads; each incremental strategy is one statement with its own cost.

Interview corner

Walk me through what happens when you run dbt build.

dbt parses every SQL and YAML file, reading ref, source and config to build the DAG, with partial parsing re-reading only changed files. It writes the manifest, applies the selection, then compiles each selected node by rendering its Jinja with execute true. A pool of threads runs ready nodes through their materialisation macros, running each model's tests right after it and skipping the children of a failed test. Finally it writes run_results.json with status and timing per node.

How does Slim CI work, and what can go wrong with --defer?

CI downloads production's manifest and runs dbt build --select state:modified+ --defer --state prod-artifacts into a schema for the pull request. state:modified compares checksums, configs and contracts, and the + adds everything downstream. --defer makes refs to unselected parents that do not exist in the CI schema read production's relations. Things go wrong when the manifest is stale, when relationships tests compare CI and production tables, when dev-only filters change the data, or when someone uses state:modified without the +.

Which incremental strategy would you use for a 5 TB event table on BigQuery, and on Snowflake?

On BigQuery I would partition by event date and use insert_overwrite with dynamic partitions, or microbatch, because the default merge joins the batch to the whole destination and scans terabytes per run; if rows update by key I would keep merge but add incremental_predicates on the partition column. On Snowflake insert_overwrite replaces the whole table, so I would use merge with incremental_predicates and clustering on the event date, or microbatch, which Snowflake applies as delete+insert per batch. Either way I would deduplicate the batch and measure bytes or seconds per run before and after.

A dbt job with threads: 16 still takes 90 minutes. How do you find what to fix?

I read run_results.json (or the job's model timing chart) for each model's start and end, and find the critical path: the chain of models that ends last. If one 50-minute model sits on it, more threads cannot help; I would make it incremental, narrow its merge with predicates, or split it. I also check whether models queue in the warehouse: a Snowflake warehouse runs 8 statements at once by default, so 16 threads may just be waiting. Only after that would I resize the warehouse.