medium.com 9 min read Original Source

The Complete Guide to dbt Slim CI (with video tutorial)

Introduction to dbt Slim CI

Most dbt Core teams I talk to have the same CI setup: none.

Or, more charitably, they have a GitHub Action that runs dbt build on the whole project every time someone opens a pull request. It takes forty minutes, rebuilds 800 models nobody touched, burns a pleasing amount of warehouse credit, and gets quietly disabled the week someone has a deadline.

Embedded content

dbt Cloud and Orchestra users get Slim CI out of the box. dbt Core users get a blog post about uploading manifest.json to S3 and a weekend of YAML. That gap is why so many Core projects ship straight to production and find out what broke from the finance team.

This article closes the gap. We’ll build dbt Core CI/CD in layers, each one fixing the problem the last one leaves behind:

  1. A basic CI job that triggers on a pull request
  2. Slim CI: only build what changed, deferring to production state
  3. One isolated environment per pull request
  4. Deploy on merge, plus queueing so CI/CD survives a busy team
  5. The macros that clean up the schemas CI leaves behind

The examples use GitHub, dbt Core and Orchestra, but the dbt half is portable. The macros, selectors and commands work whatever runs them.

Basic dbt Core CI: triggering a job on a pull request

Start with the dumbest thing that works: when a PR opens, run dbt against a non-production target.

dbt needs somewhere to write that isn’t prod, so add a second target to your profile. You could create a separate connection for CI, but a second target in the same profile is simpler and keeps credentials in one place.

yaml

my_project:
  target: prod
  outputs:
    prod:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('SNOWFLAKE_USER') }}"
      password: "{{ env_var('SNOWFLAKE_PASSWORD') }}"
      database: analytics
      warehouse: transforming
      schema: public
    ci:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('SNOWFLAKE_USER') }}"
      password: "{{ env_var('SNOWFLAKE_PASSWORD') }}"
      database: analytics_ci
      warehouse: ci
      schema: ci
my_project:
  target: prod
  outputs:
    prod:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('SNOWFLAKE_USER') }}"
      password: "{{ env_var('SNOWFLAKE_PASSWORD') }}"
      database: analytics
      warehouse: transforming
      schema: public
    ci:
      type: snowflake
      account: "{{ env_var('SNOWFLAKE_ACCOUNT') }}"
      user: "{{ env_var('SNOWFLAKE_USER') }}"
      password: "{{ env_var('SNOWFLAKE_PASSWORD') }}"
      database: analytics_ci
      warehouse: ci
      schema: ci

Call it ci, dev, staging, whatever. The name matters later because a macro will key off it.

The next decision matters more than it looks: do not build a second pipeline for CI. The usual failure is a CI job that slowly drifts away from production. It ends up on a different dbt version, with different environment variables and a different runtime. Then CI passes and prod still breaks, because CI was never testing prod.

So parameterise the production pipeline instead. In Orchestra this means adding pipeline inputs to the existing dbt pipeline:

  • dbt_command: required, defaults to build for production
  • dbt_branch: required, defaults to main
  • dbt_ci_schema_suffix: optional, empty in production

Wire those into the dbt Core task: the command field, the branch field, and an environment variable DBT_CI_SCHEMA_SUFFIX set from the third input. Create a CI environment alongside Production as well. Production runs exactly as before, because every input falls back to its default. CI runs the same task on the same infrastructure, with different arguments.

Then trigger it from GitHub. Orchestra publishes a run-pipeline action that calls a pipeline, or a single task inside it, with an API key:

yaml

name: dbt CI
on:
  pull_request:
    branches: [main]
    paths:
      - 'models/**'
      - 'seeds/**'
      - 'macros/**'
      - 'dbt_project.yml'
jobs:
  dbt-ci:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Orchestra pipeline
        uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: CI
          task_ids: run_dbt
          poll_interval: 20
          cancel_on_exit: true
          run_inputs: |
            {
              "dbt_command": "build --target ci",
              "dbt_branch": "${{ github.head_ref }}"
            }
name: dbt CI
on:
  pull_request:
    branches: [main]
    paths:
      - 'models/**'
      - 'seeds/**'
      - 'macros/**'
      - 'dbt_project.yml'
jobs:
  dbt-ci:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Orchestra pipeline
        uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: CI
          task_ids: run_dbt
          poll_interval: 20
          cancel_on_exit: true
          run_inputs: |
            {
              "dbt_command": "build --target ci",
              "dbt_branch": "${{ github.head_ref }}"
            }

Three inputs here do the important work.

task_ids: run_dbt runs only the dbt task. If your production pipeline also does Fivetran syncs and Power BI refreshes around dbt, CI skips them. cancel_on_exit: true means cancelling the GitHub job also kills the Orchestra run. Otherwise an abandoned PR keeps running and spending credits. The paths filter stops the job firing when someone edits the README.

This works. It’s also slow, because it builds everything.

Slim CI with state:modified and — defer

The point of Slim CI is to build only what the pull request changed, plus whatever sits downstream of it, and to read everything else from production.

dbt does this with two flags. --state points at a previous run’s artifacts so dbt can work out what changed. --defer tells dbt to resolve ref() to production objects for anything it isn’t building.

The hard part has never been the flags. It’s getting production’s manifest.json into the CI container. Every DIY guide ends the same way: upload artifacts to S3 or GCS after each prod run, download them at the start of each CI run, and hope nobody changes the bucket policy. That’s file storage you now operate so dbt can compare two JSON files.

Orchestra stores the artifacts from each dbt Core task run and exposes the latest successful default-branch run at a path called latest_production. When the CI job starts, production state is already in the container. You reference it like any other state directory.

Here is the sequence I’d run in CI:

bash

dbt clone --state latest_production --target ci
dbt build --full-refresh --selector modified_incremental --defer --state latest_production --target ci
dbt build -s state:modified+ --defer --state latest_production --target ci
dbt clone --state latest_production --target ci
dbt build --full-refresh --selector modified_incremental --defer --state latest_production --target ci
dbt build -s state:modified+ --defer --state latest_production --target ci

Each line has a job.

dbt clone creates zero-copy clones of production objects in the CI location. You start from an exact copy of prod rather than an empty schema. This is about as close as CI gets to rehearsing the next production run.

The full refresh of modified incrementals is the step most CI setups miss. Teams either run incremental models once, which tests only the incremental branch, or full-refresh them, which tests only the full-refresh logic. You want both. If someone’s change makes a full refresh fan out rows, you want to find out in the PR, not during a backfill.

state:modified+ is the classic Slim CI selector: everything changed and everything downstream, built and tested on top of the clones. For incremental models this second pass runs the incremental path, so both paths get tested.

The full refresh uses a selector so the command stays readable. Put this in selectors.yml:

yaml

selectors:
  - name: modified_incremental
    description: Modified incremental models, plus modified ancestors of any incremental model.
    definition:
      intersection:
        - method: state
          value: modified
        - method: config.materialized
          value: incremental
          parents: true
selectors:
  - name: modified_incremental
    description: Modified incremental models, plus modified ancestors of any incremental model.
    definition:
      intersection:
        - method: state
          value: modified
        - method: config.materialized
          value: incremental
          parents: true

Now update the workflow’s run_inputs. The dbt task adds a dbt prefix to the command, so the first command leaves it off and the later, semicolon-separated ones include it. It’s a small thing, and it will catch you out once.

yaml

env:
      COMMON: "--defer --state latest_production --target ci"
    # ...
          run_inputs: |
            {
              "dbt_command": "clone --state latest_production --target ci; dbt build --full-refresh --selector modified_incremental ${{ env.COMMON }}; dbt build -s state:modified+ ${{ env.COMMON }}",
              "dbt_branch": "${{ github.head_ref }}"
            }
env:
      COMMON: "--defer --state latest_production --target ci"
    # ...
          run_inputs: |
            {
              "dbt_command": "clone --state latest_production --target ci; dbt build --full-refresh --selector modified_incremental ${{ env.COMMON }}; dbt build -s state:modified+ ${{ env.COMMON }}",
              "dbt_branch": "${{ github.head_ref }}"
            }

Open a PR that changes nothing and you should see dbt clone run, then both builds report nothing to do. That empty run is the proof that state comparison works. The debug logs will show the latest_production state being loaded.

One schema per pull request with generate_schema_name

With one PR open at a time, this setup is fine. With five, it falls apart.

Every PR writes into the same CI schema. PR 41 clones fct_orders, PR 42 overwrites it with a different version, and PR 41’s tests now run against PR 42’s model. CI goes flaky, and a flaky CI gets ignored. Two engineers, or one engineer and three coding agents, is enough to hit this.

The fix is to give each pull request its own schema, so they never touch the same warehouse objects. dbt Cloud does this with schemas like dbt_pr_123. In dbt Core you override the built-in generate_schema_name macro.

Put this in macros/generate_schema_name.sql. The file name matters less than the macro name. You’re overriding a dbt built-in, so the macro has to be called exactly generate_schema_name or nothing happens.

sql

<button data-code="{% macro generate_schema_name(custom_schema_name, node) -%}
{%- set default_schema = target.schema -%}
{%- if target.name == "ci" -%}
{# CI schema format: _, e.g. ci_123 #}
{{ default_schema }}_{{ env_var('DBT_CI_SCHEMA_SUFFIX') }}
{%- elif custom_schema_name is none -%}
{{ default_schema }}
{%- else -%}
{{ default_schema }}_{{ custom_schema_name | trim }}
{%- endif -%}
{%- endmacro %}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

{% macro generate_schema_name(custom_schema_name, node) -%}
    {%- set default_schema = target.schema -%}
    {%- if target.name == "ci" -%}
        {# CI schema format: <ci target schema>_<PR number>, e.g. ci_123 #}
        {{ default_schema }}_{{ env_var('DBT_CI_SCHEMA_SUFFIX') }}
    {%- elif custom_schema_name is none -%}
        {{ default_schema }}
    {%- else -%}
        {{ default_schema }}_{{ custom_schema_name | trim }}
    {%- endif -%}
{%- endmacro %}
{% macro generate_schema_name(custom_schema_name, node) -%}
    {%- set default_schema = target.schema -%}
    {%- if target.name == "ci" -%}
        {# CI schema format: <ci target schema>_<PR number>, e.g. ci_123 #}
        {{ default_schema }}_{{ env_var('DBT_CI_SCHEMA_SUFFIX') }}
    {%- elif custom_schema_name is none -%}
        {{ default_schema }}
    {%- else -%}
        {{ default_schema }}_{{ custom_schema_name | trim }}
    {%- endif -%}
{%- endmacro %}

On the ci target every model lands in ci_<PR number>. On any other target the macro behaves like dbt’s default. This version also collapses custom schemas into one per-PR schema in CI. That’s usually what you want, though you could keep them separate if your project relies on them.

The PR number comes from the third pipeline input we set up earlier, so add one line to the workflow’s run_inputs:

json

"dbt_ci_schema_suffix": "${{ github.event.pull_request.number }}"
"dbt_ci_schema_suffix": "${{ github.event.pull_request.number }}"

Now PR 289 builds into ci_289 and nothing else. Reviewers can query a PR’s models directly in the warehouse, which beats reading SQL diffs and trying to picture the output.

Deploying on merge and queueing CI/CD at scale

CI tells you a change is safe. CD ships it. Since the production pipeline already takes parameters, deploying on merge is mostly another trigger.

yaml

name: dbt Deploy
on:
  push:
    branches: [main]
    paths: ['models/**', 'seeds/**', 'macros/**', 'dbt_project.yml']
  workflow_dispatch:
jobs:
  dbt-deploy:
    runs-on: ubuntu-latest
    env:
      COMMON: "--defer --state latest_production --target prod"
    steps:
      - uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: Production
          task_ids: run_dbt
          poll_interval: 20
          run_inputs: |
            {
              "dbt_command": "build --full-refresh --selector modified_incremental ${{ env.COMMON }}; dbt build -s state:modified+ ${{ env.COMMON }}",
              "dbt_branch": "main"
            }
name: dbt Deploy
on:
  push:
    branches: [main]
    paths: ['models/**', 'seeds/**', 'macros/**', 'dbt_project.yml']
  workflow_dispatch:
jobs:
  dbt-deploy:
    runs-on: ubuntu-latest
    env:
      COMMON: "--defer --state latest_production --target prod"
    steps:
      - uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: Production
          task_ids: run_dbt
          poll_interval: 20
          run_inputs: |
            {
              "dbt_command": "build --full-refresh --selector modified_incremental ${{ env.COMMON }}; dbt build -s state:modified+ ${{ env.COMMON }}",
              "dbt_branch": "main"
            }

No clone this time. It full-refreshes the changed incrementals and builds state:modified+ against production. There is a window where production tables are being rewritten. If that matters to you, a blue-green swap of databases or schemas on Snowflake is the grown-up answer. That’s a topic for another article.

Now the scale problem, which nobody hits until they do.

Most production dbt pipelines run with a concurrency limit of one, and for good reason: two runs writing the same incremental tables at the same time is how you get duplicate rows. But the default behaviour when the limit is reached is to skip the new run. So if a PR merges while the hourly production run is in progress, the deploy is skipped. The change is merged, the pipeline is green, and it isn’t in production. Nobody notices until someone asks why the new column is missing.

On a busy team this happens every week. Skipping is the wrong default once CD exists. You want deploys to wait in line.

Orchestra’s concurrency settings handle this with an on_limit policy:

yaml

configuration:
  concurrency:
    max_active: 1
    on_limit: QUEUE
configuration:
  concurrency:
    max_active: 1
    on_limit: QUEUE

There are three policies:

  • SKIP (the default): the new run is marked Skipped and never starts.
  • QUEUE: every waiting run is queued and starts in arrival order as a slot frees up.
  • QUEUE_LATEST: only the newest waiting run is kept, and older waiting runs are skipped.

Each fits a different situation. In Production, QUEUE means every merge is deployed in order, after the scheduled run finishes. In CI, QUEUE_LATEST is the better fit. If someone pushes four commits to a PR in five minutes, you only care about the last one, and the other three are wasted warehouse spend.

Concurrency is counted per pipeline and per environment, and for Git-backed pipelines per branch too. So each PR’s CI runs queue separately and never block production. You can also set a different limit per environment by pointing max_active at an environment variable:

yaml

configuration:
  concurrency:
    max_active: ${{ ENV.PIPELINE_CONCURRENCY }}
    on_limit: QUEUE
configuration:
  concurrency:
    max_active: ${{ ENV.PIPELINE_CONCURRENCY }}
    on_limit: QUEUE

Set PIPELINE_CONCURRENCY to 1 in Production and something higher in CI, and the same pipeline gets strict serialisation in prod and parallel PRs in CI. Two caveats: queued runs expire after 24 hours, and pausing a pipeline skips whatever is waiting.

This is the part DIY CI tends to get wrong. You can write a GitHub Actions concurrency group, but it only knows about GitHub-triggered runs. It has no idea the scheduled production run is in progress. The queue has to sit wherever all the runs are coordinated: the scheduled ones, the merges, the backfills, the CI. That’s the control plane argument in miniature. Something has to see every run of a pipeline before it can line them up.

Macros to drop unnecessary CI schemas

One schema per PR is great until you open the warehouse six months later and find 400 of them. ci_12, ci_13 and so on, each a frozen copy of a project that no longer exists, with storage being billed.

Clean up when the PR closes. Add a macro, macros/drop_ci_schema.sql, that reuses generate_schema_name, so cleanup always targets the same schema that CI built:

sql

{% macro drop_ci_schema() %}
    {% set schema = generate_schema_name(none, none) | trim %}
    {% do adapter.drop_schema(api.Relation.create(database=target.database, schema=schema)) %}
    {{ log("Dropped schema " ~ schema, info=true) }}
{% endmacro %}
{% macro drop_ci_schema() %}
    {% set schema = generate_schema_name(none, none) | trim %}
    {% do adapter.drop_schema(api.Relation.create(database=target.database, schema=schema)) %}
    {{ log("Dropped schema " ~ schema, info=true) }}
{% endmacro %}

Calling generate_schema_name instead of rebuilding the name by hand is the important design choice. If you change the naming convention later, cleanup follows it automatically. Otherwise you end up with a cleanup job that drops the wrong schema, or no schema at all.

Then trigger it when the pull request closes, whether it was merged or abandoned:

yaml

name: CI Cleanup
on:
  pull_request:
    types: [closed]
    branches: [main]
jobs:
  drop-ci-schema:
    runs-on: ubuntu-latest
    if: github.event.pull_request.head.repo.full_name == github.repository
    steps:
      - uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: CI
          task_ids: run_dbt
          poll_interval: 20
          run_inputs: |
            {
              "dbt_command": "run-operation drop_ci_schema --target ci",
              "dbt_branch": "main",
              "dbt_ci_schema_suffix": "${{ github.event.pull_request.number }}"
            }
name: CI Cleanup
on:
  pull_request:
    types: [closed]
    branches: [main]
jobs:
  drop-ci-schema:
    runs-on: ubuntu-latest
    if: github.event.pull_request.head.repo.full_name == github.repository
    steps:
      - uses: orchestra-hq/[email protected]
        with:
          api_key: ${{ secrets.ORCHESTRA_API_KEY }}
          pipeline_id: ${{ vars.ORCHESTRA_DBT_PIPELINE_ID }}
          environment: CI
          task_ids: run_dbt
          poll_interval: 20
          run_inputs: |
            {
              "dbt_command": "run-operation drop_ci_schema --target ci",
              "dbt_branch": "main",
              "dbt_ci_schema_suffix": "${{ github.event.pull_request.number }}"
            }

The if condition is there because pull requests from forks can’t read repository secrets, so the job would fail anyway.

On dbt 1.12 and later you can skip the macro and pass SQL straight to run-operation:

json

"dbt_command": "run-operation --sql 'drop schema if exists {{ target.schema }}_${{ github.event.pull_request.number }} cascade' --target ci"
"dbt_command": "run-operation --sql 'drop schema if exists {{ target.schema }}_${{ github.event.pull_request.number }} cascade' --target ci"

It’s shorter, but I’d still use the macro. The inline version hard-codes the naming convention a second time, which is exactly the drift the macro avoids.

Where this leaves your dbt CI/CD

Add it all up and you have a dbt Core project with every PR built in isolation and only the changed models built against real production state. Merges deploy in order without being skipped, and cleanup runs automatically. CI that takes minutes instead of forty gets used rather than switched off. With agents now opening a share of the pull requests, it’s also how you keep up without your warehouse bill doing something alarming.

My view is that every team running dbt Core in production should have at least the first three layers, whatever tooling they use. Queueing becomes essential the moment more than one person merges in a day. Cleanup is twenty lines of YAML and Jinja that save you a very awkward storage conversation later.

The thread through all of it is that the hard parts of CI/CD were never the dbt commands. They were state management, sequencing and coordination, which is a control plane’s job.

That’s what we built Orchestra to be: a serverless control plane that manages dbt state for you, runs the same pipeline across CI and production, and queues runs across every trigger. If you’re running dbt Core and want Slim CI without the S3 bucket and the weekend of YAML, try Orchestra. The dbt CI/CD guide in the docs has everything above, ready to copy.