Beginner20 min · 11 challenges

Deploying dbt: Beginner

It is 3pm at GitLab and a data engineer has changed the model behind the revenue dashboard. On her laptop the change builds into a schema only she can see. At 6am tomorrow the same files build into production on a schedule, and if one test fails, the build has to pick up where it stopped.

Dev and Prod Targets

Daily Life
Interviews

A model file never says which schema it builds into. stg_orders.sql selects from source('raw', 'orders'), other models reach it through ref('stg_orders'), and dbt writes in the schema when it renders the SQL. That schema comes from outside the project. This lets one set of model files build a copy for an engineer to test and another copy that dashboards read.

The profile holds the targets

dbt_project.yml names a profile, here profile: shop. dbt reads that profile from profiles.yml, a file kept on the machine that runs dbt, usually in the ~/.dbt/ folder of the user's home directory. The file stays out of the project's repository, so the credentials in it are never committed with the models. Each entry under outputs is a target: a warehouse connection plus the schema that models build into. The target: line names the target dbt uses when a command does not ask for another.

shop:
target: dev
outputs:
dev:
schema: dbt_ana
prod:
schema: analytics

Every dbt command accepts --target to choose a target by name. With no flag, dbt run builds into dbt_ana. dbt run --target prod builds the same models into analytics. The SELECT inside each model is identical on both runs. The schema in each relation dbt writes changes, and every ref() resolves inside the chosen schema, so a dev model reads dev parents and a prod model reads prod parents.

CommandTargetstg_orders is built infct_orders reads stg_orders from
dbt rundevdbt_anadbt_ana
dbt run --target prodprodanalyticsanalytics

A private schema for every engineer

Each person gets a dev schema of their own: dbt_ana, dbt_raj, dbt_mei. If 3 engineers shared one dev schema, Raj's run would replace the fct_orders Ana was halfway through checking, and neither could trust what they queried. Production has one schema and one writer. Dashboards and other teams read analytics, so a table there changes only when the agreed process builds it from reviewed code. Many teams keep the prod target only in the profile on the machine that runs the scheduled build, so no laptop holds credentials that can write to production.

✓dev target
  • Run by one engineer, many times a day
  • Builds into a schema named for that person
  • Read only by its owner while a change is checked
  • Often limited to recent rows
✗prod target
  • Run by the scheduled job
  • Builds into the shared schema
  • Read by dashboards and other teams
  • Always holds the full data

The target inside a model

Jinja renders before any SQL reaches the warehouse, and dbt hands it the active target as a variable named target. target.name holds the target's name from the profile and target.schema holds its schema. A model can test target.name in an if block and render differently on each target. The most common use is building dev on a slice of the data: a dev build runs many times a day, and only production needs the full history.

orders
stg_orderstable
depends on orders
select
order_id,
amount,
order_date
from {{ source('raw', 'orders') }}
{% if target.name == 'dev' %}
where order_date >= date '2024-09-01'
{% endif %}
raw.orders5 rows
order_id
amount
order_date
1
40
2024-08-28
2
75
2024-08-30
3
20
2024-09-01
4
90
2024-09-01
5
55
2024-09-02
dev.stg_orders0 rows
order_id
amount
order_date

$ dbt run --target dev

1 / 9
The same model built on dev and then on prod: the if block becomes a where clause on one target and nothing on the other.

The first step runs on dev. target.name == 'dev' is true, so the if block renders to where order_date >= date '2024-09-01' and stg_orders holds orders 3 through 5, the 3 rows dated on or after September 1. The second step runs on prod. The condition is false, the block renders to nothing, and stg_orders holds all 5 orders. Nothing in the model file changed between the 2 runs.

TIP
Keep target branches to how much data a model reads. A branch that changes business logic, such as a different revenue formula on prod, means production runs SQL that no dev build ever produced or tested.
Loading the challenge

Each answer depends on the order of events: Jinja sees the target before the warehouse sees any SQL, so each target gets its own compiled query from one file. After a dev run, and again after a prod run, read the compiled model in target/compiled/. The only differences between the 2 should be the ones your if blocks put there.

Practicing with targets

Add a second output named full to your profile, beside dev, with the schema dbt_ana_full. Build into each, once with no flag and once with --target full, and query both schemas to see the same tables in 2 places. Then add a dev-only where to one model and confirm that the row counts differ by exactly the rows the filter drops. Keep the full target afterwards: the rehearsal at the end of this lesson uses it as a stand-in for production.

✓Do
  • Give every engineer a dev schema named for them
  • Make dev the default target, so a bare command never writes to prod
  • Keep prod credentials on the machine that runs the schedule
✗Don't
  • Commit a profiles.yml holding passwords to the repository
  • Share one dev schema among several engineers
  • Change business logic based on target.name
With targets in place, the remaining question is how much of the project one command builds. By default a command builds every model, and the next section narrows that.

Selecting Part of the DAG

Daily Life
Interviews

Unless told otherwise, dbt run builds every model in the project, as does dbt build. That suits the daily production build. It wastes time while you work on one model in a project of 400, where checking a change to 2 tables can mean waiting on a full build. The --select flag, -s for short, limits a command to the nodes it names, and a + on either side of a name extends the selection along the lineage.

The project used here

raw table
raw.orders
raw table
raw.customers
table model
stg orders
table model
stg customers
table model
fct orders
table model
daily revenue

Each arrow runs from a node to a model that selects from it. fct_orders joins both staging models, and daily_revenue groups fct_orders by order date.

A + before or after a name follows the lineage

A plain name selects that model and nothing else. A + before the name adds every ancestor up to the sources, and a + after it adds every descendant down to the last model. Ancestors include parents of parents, not only the models one step up.

CommandModels built
dbt run --select fct_ordersfct_orders
dbt run --select +fct_ordersstg_orders, stg_customers, fct_orders
dbt run --select fct_orders+fct_orders, daily_revenue
dbt run --select +fct_orders+stg_orders, stg_customers, fct_orders, daily_revenue
dbt run --select stg_orders+stg_orders, fct_orders, daily_revenue

dbt still runs whatever is selected in ref() order: +fct_orders builds both staging models before fct_orders, and stg_orders+ leaves stg_customers out because nothing flows from stg_orders into it.

An unselected parent keeps its last build

Selection decides which tables get rebuilt. A selected model still reads its parents, and a parent left out of the selection holds whatever its last build put there. The animation plays a full run, inserts order 5 into raw.orders, then runs 3 selections.

customers
orders
stg_customerstable
depends on customers
stg_orderstable
depends on orders
fct_orderstable
depends on stg_orders and stg_customers
daily_revenuetable
depends on fct_orders
select
o.order_id,
o.order_date,
o.amount,
c.region
from {{ ref('stg_orders') }} as o
join {{ ref('stg_customers') }} as c
on o.customer_id = c.customer_id
dev.fct_orders0 rows
order_id
order_date
amount
region
dev.daily_revenue0 rows
order_date
revenue
orders

$ dbt run

1 / 21
A full run, then an order inserted and 3 selections: the model alone, with its parents, with its children.
StepCommandfct_orders rowsdaily_revenue on 2024-07-03
1dbt run490 revenue, 1 order
2order 5 inserted, then dbt run --select fct_orders490 revenue, 1 order
3dbt run --select +fct_orders590 revenue, 1 order
4dbt run --select fct_orders+5145 revenue, 2 orders

Step 2 is the one that catches people out. fct_orders was rebuilt after order 5 landed in raw.orders, yet it still has 4 rows. fct_orders reads stg_orders, a table last built in step 1, before order 5 arrived. Step 3 adds the parents, so stg_orders picks up order 5 and fct_orders reaches 5 rows. daily_revenue was not selected, so it still reports 90 for 2024-07-03. Step 4 adds the children, and daily_revenue shows 145 from 2 orders that day.

TIP
If stg_orders were a view, step 2 would already show 5 rows: a view runs its query each time it is read, so it keeps no stored copy to fall behind. Gaps in a selection matter where the parents are tables or incremental models.

Choosing a selection

Which selector for which change
  • ▸You changed a model's SQL: put + after its name, so every model reading it picks up the change.
  • ▸New data landed under a model: put + before its name, so its parents reread the sources.
  • ▸You only want to know the model builds: select it alone, and it reads its parents as they stand.
  • ▸Your dev schema is empty: put + before the name, since a model alone has no parent tables to read.

dbt build --select follows the same rules and also runs the tests on the selected models, each test right after the model it checks, so a failing test still stops that model's selected children.

Loading the challenge

Writing a selector comes down to asking where the stale tables are. If they sit above the model, because new data arrived in the sources, the + goes before the name. If they sit below it, because you changed the model's SQL, the + goes after it. When both are stale, use both.

Practicing selection

Pick a model in a project you know. Before running anything, write down which models the bare name should build. Do the same with + in front of the name and with + behind it, then with both together. Then run dbt ls --select with each of the 4 forms. It prints every node a selector matches, including sources and tests, without building any of them, so each wrong guess shows up next to the right list.

Run Artifacts

Daily Life
Interviews

When a command finishes, its terminal output scrolls away, but dbt has also written files recording what it read and what it did. They land in the target/ folder inside the project, next to the compiled SQL. Long after the terminal is closed, these files answer which models ran, which failed, how long each took, and how the project's nodes connect.

PathWritten byWhat it records
target/manifest.jsonEvery command that reads the projectEach node: its type, config, schema, SQL and the nodes it depends on
target/run_results.jsonCommands that execute nodes, such as run, build and testOne result per node: status, timing, and for tests the count of failing rows
target/compiled/compile, run, build, testEach model and test as its SELECT, after Jinja renders
target/run/run, build, testThe full statement sent, with the create around the SELECT

manifest.json: the project as dbt read it

The manifest is one JSON object describing the whole project. Each node has a unique id that prefixes its own name with its type and the project name, so fct_orders in the shop project is model.shop.fct_orders. Under that id sit its materialization, the schema it builds into on this run's target, and depends_on, the list of nodes it reads from. parent_map holds every node's lineage in one direction at the top level of the file, and child_map holds it in the other.

{
"nodes": {
"model.shop.fct_orders": {
"resource_type": "model",
"schema": "dbt_ana",
"config": {
"materialized": "table"
},
"depends_on": {
"nodes": [
"model.shop.stg_orders"
]
}
}
},
"child_map": {
"model.shop.stg_orders": [
"model.shop.fct_orders"
]
}
}

The + selectors from the previous section walk this same graph: stg_orders+ is stg_orders plus everything reachable from it through child_map. When a selection builds a model you did not expect, the maps show which reference tied the 2 together.

run_results.json: one entry per node

run_results.json holds the outcome of the last command that executed nodes. Its results list has one entry per node the command ran or skipped, each with the node's unique id, its status, its execution_time in seconds, and for a test the number of rows it returned in failures. Under args sits the command that produced the file, with its flags.

{
"results": [
{
"unique_id": "test.shop.source_not_null_raw_orders_customer_id.4b8a9c1d2e",
"status": "fail",
"failures": 1,
"execution_time": 0.41
},
{
"unique_id": "model.shop.stg_orders",
"status": "skipped",
"execution_time": 0
},
{
"unique_id": "model.shop.fct_orders",
"status": "skipped",
"execution_time": 0
}
],
"args": {
"which": "build"
}
}
StatusNodeWhat happened
successmodelIts SQL ran and the table or view was built
errormodelThe warehouse rejected its SQL
skippedmodel or testSomething upstream failed, so this node never ran
passtestThe test query returned 0 rows
failtestThe test query returned rows, counted in failures
errortestThe test query itself could not run

Each new command that writes these files replaces them. After a failed nightly build, a dbt test run on the same machine overwrites the build's run results with its own, and the record of what the build did is gone. Production jobs copy target/ to lasting storage after every run for that reason.

TIP
Add target/ to .gitignore. The artifacts describe one run on one machine against one target, and a manifest committed from Ana's laptop would say dbt_ana where production builds into analytics.
Loading the challenge

Screen and file report the same result in 2 spellings: a test that prints Failed is stored as fail, and a model that prints Skipped is stored as skipped. The file can therefore stand in for a terminal nobody was watching, and dbt retry reads its statuses to decide what to rerun.

Reading artifacts as practice

Run a build on your dev target and open target/run_results.json. Find the entry with the largest execution_time, then open that model's file in target/run/ and read the full statement it sent. Find the same model in manifest.json and follow its depends_on list up to the sources. One pass through a real project teaches the files' shape better than a list of their fields.

Retrying a Failed Build

Daily Life
Interviews

A nightly build has 300 nodes. Node 280 is a test that finds a null customer id, and the 20 nodes that depend on it are skipped. Once the data is fixed, running dbt build again rebuilds the 279 nodes that already succeeded before it reaches the 21 that did not. dbt retry runs only those 21.

dbt retry works from the last run_results.json

You do not pass dbt retry a selection. It opens target/run_results.json, the file the failed command left, and reads 2 things from it: the command that ran, and the status of every node. It reruns that command, in lineage order, over every node whose status was error or fail, plus every node marked skipped, and leaves each success and pass alone. It reads the project as it stands now, so a corrected model file is picked up, and it writes a new run_results.json when it finishes, so a second failure can be retried in turn.

In the animation, the build's first node is a not_null test on raw.orders.customer_id. Order 4 has no customer id, so the test fails and both models are skipped. Order 4 is then deleted from the raw table, and dbt retry runs.

orders
not_null customer_id
stg_orderstable
depends on orders
fct_orderstable
depends on stg_orders
select
order_id,
customer_id,
order_date,
amount,
amount > 50 as is_large
from {{ ref('stg_orders') }}
raw.orders4 rows
order_id
customer_id
order_date
amount
1
101
2024-07-01
40
2
102
2024-07-01
75
3
101
2024-07-02
20
4
null
2024-07-03
90
dev.fct_orders0 rows
order_id
customer_id
order_date
amount
is_large

$ dbt build

1 / 12
A build stopped by a source test, the bad row removed, and dbt retry finishing only the nodes that had not passed.
After dbt build
nodestatus
not_null on customer_idfail
stg_ordersskipped
fct_ordersskipped
After dbt retry
nodestatus
not_null on customer_idpass
stg_orderssuccess
fct_orderssuccess

fct_orders ends with 3 rows, orders 1 to 3. Every node reran here because the failure sat at the very start of the lineage, before anything had succeeded. Retry saves work in proportion to how much of the build passed before the failure.

When the fix lives under a node that passed

Retry reruns the nodes that did not succeed. It has no way to know which nodes your fix touched. Take the project from the selection section, add a not_null test on stg_customers.region, and say customer 103 arrives in raw.customers with no region.

NodeStatus after dbt buildRerun by dbt retry?
stg_orderssuccessNo
stg_customerssuccessNo
not_null on stg_customers.regionfailYes
fct_ordersskippedYes
daily_revenueskippedYes

The table stg_customers built successfully with the null in it, and only then did its test run. Fix the region in raw.customers and run dbt retry: it reruns the test against the stg_customers table from the failed build, which still holds the null, and the test fails again. The fix sits upstream of a node that passed, so the rebuild has to start at that node. dbt build --select stg_customers+ rebuilds stg_customers from the corrected source and tests it, then builds fct_orders and daily_revenue behind it.

TIP
Retry fits a fix in a model file when the edited model is one that failed or was skipped. It fits a fix in raw data when the failing test reads the source directly, as in the animation, or when every model between them is a view.
When retry is the wrong command
  • ▸The last command succeeded: retry finds nothing to rerun and finishes without building anything.
  • ▸Another command ran since the failure: retry repeats whichever command wrote run_results.json last.
  • ▸The fix sits under a node that succeeded: run dbt build with that node and a + after it instead.
Loading the challenge

Retry and a + selector answer different questions. Retry asks which nodes did not succeed. The selector asks which tables are stale. When the 2 lists match, retry is shorter to type and cannot be mistyped. When they differ, the selector is the one that matches the data.

Practicing a recovery

On your dev target, add a not_null test to a staging model and put a null into a source table you control. Run dbt build, read the statuses in run_results.json, and write down what dbt retry will rerun before changing anything. Correct the source and retry. If the test fails again, you have reproduced the case above, and the rebuild starts from the model that passed.

Running dbt on a Schedule

Daily Life
Interviews
Dashboards read the prod schema, and a prod table is only as current as the last prod build. A scheduled job takes the person out of that loop. A scheduler starts the job at fixed times on a machine set up for production. The job checks out the code and runs dbt against the prod profile, then reports how the run ended.
loader
Raw loads
scheduler
dbt source freshness
ERRORstop job and alert
scheduler
dbt build --target prod
ERRORstop, alert, save target/IDEMPOTENCYrerun rebuilds same tables
warehouse
analytics schema
SLAcurrent by 07:00
BI tool
Dashboards

The daily job: the loader lands raw data by 05:30, the job starts at 06:00, the freshness check gates the build, and dashboards read the prod schema from 07:00.

SettingValue
Schedule0 6 * * *, which is 06:00 every day
Codethe latest commit on the main branch
Profileone whose default target is prod
Step 1dbt source freshness
Step 2dbt build --target prod, only if step 1 passed
On failurestop, alert the team, save target/

0 6 * * * is a cron expression: minute 0, hour 6, any day of the month, any month, any day of the week. The hour is read in the scheduler's time zone, so teams usually run the server on UTC and write every job time in UTC to remove the doubt.

Conditions for a safe schedule

A schedule repeats whatever the job does, mistakes included, every day with nobody watching. Each condition below closes one way that repetition can go wrong.
  • It builds reviewed codeThe job checks out main, so a model reaches production only after someone reviewed and merged it.
  • Only the job writes to prodThe prod target lives in the scheduler's profile, and engineers build into their own schemas.
  • A second run changes nothingTable models rebuild from scratch, and an incremental model that keeps only rows newer than the latest in {{ this }} adds none when nothing new arrived.
  • Tests run inside the builddbt build tests each model before its children, so a failed check stops bad rows short of the tables dashboards read.
  • Sources are checked firstdbt source freshness fails the job when a loader is late, instead of building today's tables from yesterday's data.
  • Runs never overlapThe schedule leaves room for the longest build, and the scheduler refuses to start a run while the last one is going.
  • A failure reaches a persondbt exits with a nonzero code on failure, the job alerts on it, and the saved run_results.json shows what to retry.

A late loader, worked through

The freshness check reads 2 settings from the source's YAML. loaded_at_field names a timestamp column the loader fills as it writes each row, and error_after sets how old the newest value in that column may be. dbt source freshness selects the maximum of that column, subtracts it from the current time, and exits with a nonzero code when the gap is past the limit.

sources:
- name: raw
schema: raw
tables:
- name: orders
config:
loaded_at_field: loaded_at
freshness:
error_after:
count: 12
period: hour

Say the loader lands raw.orders by 05:30 on most days and the build takes 40 minutes, so dashboards are current by 06:40. One morning the loader finishes at 06:15. At 06:00 the newest loaded_at in raw.orders is still yesterday's 05:30 load, 24.5 hours old and past the 12-hour limit, so dbt source freshness exits with an error. The job stops before dbt build, the alert goes out, and every prod table still holds yesterday's correct data. An engineer reruns the job at 06:20, when the newest row is 5 minutes old, and the tables are current by 07:00. The failure cost 20 minutes of delay. Building on the stale source would have published tables that looked current and were not.

TIP
Leave --full-refresh out of the daily command. It rebuilds every incremental model from its full history, turning a short increment into the hours the first run took. Run it by hand, on purpose, when a model's logic changes.
Loading the challenge

When a test fails in a scheduled build, the model it checks has already been rebuilt, but every model after it keeps the rows from its previous run. Dashboards reading those later tables see yesterday's complete data instead of today's broken data, which is the safe failure the conditions above aim for. Whether dbt retry or a + selector finishes the job depends on where the fix lands, as the previous section showed.

Practicing a deployment

You can rehearse the whole job on your own machine. Use the full target from the first section, write a short script that runs dbt source freshness and then dbt build --target full, stopping if the first command fails, and give it a cron entry a few minutes ahead. Corrupt one source row and let the job run. Once it has run, read run_results.json and recover.

PUTTING IT ALL TOGETHER

> A data engineer at GitLab changes how fct_orders assigns each order's region. She builds fct_orders+ on her dev target, where a target.name filter keeps the build to recent rows, reads the compiled SQL, and merges. At 06:00 the scheduled job builds main into the prod schema. A not_null test on stg_customers.region fails, fct_orders and daily_revenue are skipped, and the alert links the saved run_results.json.

Her dev build and the 06:00 build ran the same files: the profile on each machine chose the schema, and target.name chose the slice.
fct_orders+ was the right selection for a SQL change, because the stale tables sat below the model she edited.
run_results.json showed stg_customers as success and its test as fail, which told her the bad row came in through raw.customers.
Because stg_customers had succeeded, she rebuilt with stg_customers+ after fixing the raw row instead of running dbt retry.
Dashboards kept yesterday's daily_revenue all morning, since the failed test stopped the build before the tables they read.
KEY TAKEAWAYS
A target in profiles.yml decides the schema a build writes to, and the model files stay the same on dev and prod.
target.name lets Jinja render a dev-only filter, so a dev build reads a slice and prod reads everything.
A + before a name adds every ancestor and a + after it adds every descendant; an unselected table parent keeps its last build.
manifest.json records the project's nodes and lineage; run_results.json records each node's status in the last command.
dbt retry reads the last run_results.json and reruns every node that did not succeed there, skipped nodes included.
A fix under a node that succeeded needs a selector starting at that node, because retry will not rebuild it.
A safe schedule runs a freshness check, then builds merged code into prod with the tests inside the build. Runs never overlap, and a failure sends an alert.
Official dbt resources

dbt enables data analysts and engineers to transform their data using the same practices that software engineers use to build applications. github.com/dbt-labs/dbt-core

dbt and the dbt logo are trademarks of dbt Labs, LLC.

One dbt project built into dev and prod, in part or whole, resumed after a failure, and run every day.

Category
dbt
Difficulty
beginner
Duration
20 minutes
Challenges
11 hands-on challenges

Topics covered: Dev and Prod Targets, Selecting Part of the DAG, Run Artifacts, Retrying a Failed Build, Running dbt on a Schedule

Lesson Sections

  1. Dev and Prod Targets (concepts: Targets and environments)

    The profile holds the targets A private schema for every engineer The target inside a model Practicing with targets With targets in place, the remaining question is how much of the project one command builds. By default a command builds every model, and the next section narrows that.

  2. Selecting Part of the DAG (concepts: Node selection)

    The project used here A + before or after a name follows the lineage An unselected parent keeps its last build Choosing a selection Practicing selection

  3. Run Artifacts (concepts: Run artifacts)

    manifest.json: the project as dbt read it run_results.json: one entry per node Reading artifacts as practice

  4. Retrying a Failed Build (concepts: Run artifacts)

    dbt retry works from the last run_results.json When the fix lives under a node that passed Practicing a recovery

  5. Running dbt on a Schedule (concepts: Running dbt in production)

    Dashboards read the prod schema, and a prod table is only as current as the last prod build. A scheduled job takes the person out of that loop. A scheduler starts the job at fixed times on a machine set up for production. The job checks out the code and runs dbt against the prod profile, then reports how the run ended. Conditions for a safe schedule A schedule repeats whatever the job does, mistakes included, every day with nobody watching. Each condition below closes one way that repetition can