Nightly DAG: task status
elt_nightly, one column per run, final state of each task
Project 04 · Orchestration & CI/CD
Billing, product usage and CRM data are extracted every night and loaded into Snowflake by an Airflow DAG. dbt turns them into tested models, from staging views to a finance mart with monthly recurring revenue and churn. Every change goes through a pull request: CI lints the SQL, builds only the changed models and their children in a throwaway schema and runs their tests, and merging deploys to production. Terraform manages the warehouses, databases, roles and grants, so the platform is reviewed like the code that runs on it.
elt_nightly, one column per run, final state of each task
Sources to the reports that depend on them; amber outlines carry test warnings
Whole DAG, with the 14-run average. Sep 29 (red) stopped early.
Month-end MRR from fct_mrr
Oct 6: 413 of 415 passed, 2 warned
Nightly terraform plan checks for drift
CI checks and production deploys
Code review covers everything: the SQL, the DAG and the infrastructure.
01 · Extract
Python tasks on Airflow
Billing API, product events and CRM exports pulled nightly to S3 as JSON, in parallel, with retries and backoff.
02 · Load
Snowflake COPY INTO
Raw tables keep each file's rows plus load metadata. Loads are idempotent by file name.
03 · Transform
dbt
64 models, from staging views to incremental marts, with 415 tests and freshness checks on every source.
04 · Orchestrate
Apache Airflow
One nightly DAG with retries for flaky APIs, timeouts on long steps and alerts on failure.
05 · Test & deploy
GitHub Actions
Every pull request lints the SQL and builds only changed models and their children in a throwaway schema.
06 · Provision
Terraform
Warehouses, databases, roles and grants are code, reviewed and applied from the same pipeline.
state:modified+ against production's manifest and defer everything else to prod, so a typical check takes 6 to 8 minutes instead of a full rebuild.unique and relationships tests fail the build; softer checks only warn. The Sep 29 failure stopped bad numbers before the finance dashboard refreshed.terraform plan reports drift, like the grant someone changed by hand.A raw table as loaded, the MRR mart dbt builds from it, and the Airflow task history behind the status grid (the CSV download).
raw.billing_invoicesSnowflake table · loaded by COPY INTOpayloadvariant_file_namevarchar_file_rownumber_loaded_attimestamp_ltzmarts.fct_mrrdbt incremental · merge on month + accountmonthdateaccount_idvarcharmrr_usd / prev_mrr_usdnumber(12,2)mrr_change_usdnumber(12,2)movementvarcharnew, expansion, contraction, churn or flatdag_task_runsAirflow task history · the CSV downloadrun_datedatetask_idstringstatestringsuccess, failed or upstream_failedtry_numberintstarted_at / duration_stimestamp / intThe nightly DAG, the MRR model, the CI workflow and the Terraform for Snowflake.
The nightly Airflow DAG. Extracts fan out per source, then load, freshness checks and dbt build run in order.
"""Nightly ELT: extract to S3, COPY INTO Snowflake, dbt build, publish."""
from datetime import datetime, timedelta
from airflow.decorators import dag, task
from airflow.operators.bash import BashOperator
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
from include.extract import extract_to_s3 # writes JSON files to s3://raw-landing/<source>/<ds>/
DBT = {"cwd": "/opt/dbt", "env": {"DBT_TARGET": "prod"}, "append_env": True}
@dag(
schedule="0 2 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
max_active_runs=1,
dagrun_timeout=timedelta(hours=2),
default_args={"retries": 2, "retry_delay": timedelta(minutes=5), "retry_exponential_backoff": True},
tags=["elt", "finance"],
)
def elt_nightly():
@task(pool="api_extracts")
def extract(source: str, ds=None) -> str:
return extract_to_s3(source, ds)
files = extract.expand(source=["billing", "product_events", "crm"])
load_raw = SQLExecuteQueryOperator(
task_id="load_raw",
conn_id="snowflake_loader",
sql="sql/copy_into_raw.sql", # COPY INTO raw.<table> FROM @landing/<source>/{{ ds }}/
)
freshness = BashOperator(task_id="dbt_source_freshness", bash_command="dbt source freshness", **DBT)
staging = BashOperator(task_id="dbt_build_staging", bash_command="dbt build --select staging", **DBT)
marts = BashOperator(
task_id="dbt_build_marts",
bash_command="dbt build --select intermediate+ --exclude staging",
execution_timeout=timedelta(hours=1),
**DBT,
)
publish = BashOperator(task_id="publish_exposures", bash_command="python publish_exposures.py", **DBT)
@task
def notify_finance(ds=None):
from include.alerts import post_message
post_message("#finance-data", f"Finance mart refreshed for {ds}.")
files >> load_raw >> freshness >> staging >> marts >> publish >> notify_finance()
elt_nightly()
dbt model: MRR per account and month, with every month filled in so churn shows up as a drop to zero.
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key=['month', 'account_id'],
on_schema_change='append_new_columns'
) }}
with monthly as (
select account_id, month, sum(mrr_usd) as mrr_usd
from {{ ref('int_subscription_periods') }}
group by 1, 2
),
months as (
select distinct month from {{ ref('int_subscription_periods') }}
),
-- every account in every month from its first month on, so churn appears as zero
spine as (
select a.account_id, m.month
from (select account_id, min(month) as first_month from monthly group by 1) as a
join months as m on m.month >= a.first_month
),
filled as (
select s.account_id, s.month, coalesce(m.mrr_usd, 0) as mrr_usd
from spine as s
left join monthly as m using (account_id, month)
),
movements as (
select
month,
account_id,
mrr_usd,
coalesce(lag(mrr_usd) over (partition by account_id order by month), 0) as prev_mrr_usd
from filled
)
select
month,
account_id,
mrr_usd,
prev_mrr_usd,
mrr_usd - prev_mrr_usd as mrr_change_usd,
case
when prev_mrr_usd = 0 and mrr_usd > 0 then 'new'
when prev_mrr_usd > 0 and mrr_usd = 0 then 'churn'
when mrr_usd > prev_mrr_usd then 'expansion'
when mrr_usd < prev_mrr_usd then 'contraction'
else 'flat'
end as movement
from movements
where not (mrr_usd = 0 and prev_mrr_usd = 0) -- nothing to report after an account churns
{% if is_incremental() %}
and month >= (select dateadd(month, -1, max(month)) from {{ this }})
{% endif %}
GitHub Actions: pull requests build only what changed in a schema of their own; merges to main deploy dbt and apply Terraform.
name: analytics-ci
on:
pull_request:
paths: ["dbt/**", "infra/**"]
push:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
id-token: write # OIDC to AWS for the dbt artifacts bucket
contents: read
jobs:
dbt:
runs-on: ubuntu-latest
defaults:
run:
working-directory: dbt
env:
SNOWFLAKE_ACCOUNT: ${{ secrets.SNOWFLAKE_ACCOUNT }}
SNOWFLAKE_USER: ${{ secrets.SNOWFLAKE_CI_USER }}
SNOWFLAKE_PRIVATE_KEY: ${{ secrets.SNOWFLAKE_CI_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ARTIFACTS_ROLE }}
aws-region: us-east-1
- run: pip install -r requirements.txt
- run: sqlfluff lint models --dialect snowflake
- run: dbt deps
- run: aws s3 cp s3://analytics-dbt-artifacts/prod/manifest.json prod-state/manifest.json
- name: Build changed models and their children
if: github.event_name == 'pull_request'
env:
DBT_SCHEMA: pr_${{ github.event.number }}
run: dbt build --select state:modified+ --defer --state prod-state --target ci
- name: Deploy to production
if: github.ref == 'refs/heads/main'
run: |
dbt build --target prod
aws s3 cp target/manifest.json s3://analytics-dbt-artifacts/prod/manifest.json
terraform:
runs-on: ubuntu-latest
defaults:
run:
working-directory: infra
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init -input=false
- run: terraform plan -input=false -out=tfplan
- if: github.ref == 'refs/heads/main'
run: terraform apply -input=false tfplan
Terraform for Snowflake: warehouses from one map, a database, a role for dbt and a monthly credit limit.
terraform {
required_providers {
snowflake = {
source = "snowflakedb/snowflake"
version = "~> 1.0"
}
}
backend "s3" {
bucket = "analytics-terraform-state"
key = "snowflake/prod.tfstate"
region = "us-east-1"
}
}
locals {
warehouses = {
LOADING = { size = "XSMALL", auto_suspend = 60 }
TRANSFORM = { size = "SMALL", auto_suspend = 60 }
REPORTING = { size = "SMALL", auto_suspend = 300 }
CI = { size = "XSMALL", auto_suspend = 60 }
}
}
resource "snowflake_resource_monitor" "monthly" {
name = "ANALYTICS_MONTHLY"
credit_quota = 400
frequency = "MONTHLY"
start_timestamp = "2026-01-01 00:00"
notify_triggers = [75, 90]
suspend_trigger = 100
}
resource "snowflake_warehouse" "this" {
for_each = local.warehouses
name = "${each.key}_WH"
warehouse_size = each.value.size
auto_suspend = each.value.auto_suspend
auto_resume = true
initially_suspended = true
resource_monitor = snowflake_resource_monitor.monthly.name
}
resource "snowflake_database" "analytics" {
name = "ANALYTICS"
data_retention_time_in_days = 7
}
resource "snowflake_account_role" "transformer" {
name = "TRANSFORMER"
comment = "dbt runs as this role"
}
resource "snowflake_grant_privileges_to_account_role" "transformer_warehouse" {
account_role_name = snowflake_account_role.transformer.name
privileges = ["USAGE", "OPERATE"]
on_account_object {
object_type = "WAREHOUSE"
object_name = snowflake_warehouse.this["TRANSFORM"].name
}
}
A billing API retry sent one invoice twice. The unique test on fct_invoices failed, so the finance dashboard kept the previous day's numbers instead of showing double revenue. PR #477 deduplicated invoices and the next run was clean.
Slim CI built 6 models per pull request on average instead of 64, and stopped a broken accepted_values test (PR #475) before it reached production.
Making the largest marts incremental in PR #474 cut the median nightly run by about six minutes.
A grant changed by hand in the Snowflake UI showed up in the nightly terraform plan. It was added to the code instead of being silently reverted on the next apply.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as dag_task_runs.csv or read data.json.