Data orchestration: Airflow, Dagster, and Prefect in practice
Airflow vs Dagster vs Prefect with hands-on code: DAGs, assets, flows, scheduling, retries, observability, and when to choose each orchestrator.
Table of Contents
It is 6:55 on a Monday and your phone has fourteen Slack messages. The overnight pipeline failed at 2:13; nobody noticed until the sales team opened the dashboard. The server cron is still running, but script 3 of 7 died and the other six wrote partial data. You are, once again, the human orchestrator.
Orchestration is not running scripts on a clock. It is knowing what depends on what, what happened, what can be retried, and which data was left inconsistent. Airflow, Dagster, and Prefect solve that problem with three different philosophies, and choosing well matters more than learning all three syntaxes.
The problem is not cron
Cron knows one thing: launch a command at a given time. It does not know that the revenue model needs ingestion to finish, it does not retry with backoff, it cannot tell a transient failure from corrupt data, and it leaves no queryable record of what happened at 2:13.
An orchestrator adds the missing layer:
- Graph: explicit dependencies between steps.
- State: what ran, with which parameters, and what it produced.
- Retries: with limits, delays, and criteria.
- Backfills: reprocess past dates without copy-paste.
- Observability: logs, duration, lineage, and alerts.
The difference between a script and a pipeline is the difference between a query and a product: someone else will depend on it at 3 a.m.
Three mental models: DAG, asset, flow
Airflow thinks in tasks. A DAG is a graph of operators executed in order; whatever they produce is a side effect. Dagster thinks in assets: the table or file you materialize is the center, and tasks are the means. Prefect thinks in flows: Python functions that call other functions, with state and observability wrapped around them.
| Concept | Airflow | Dagster | Prefect |
|---|---|---|---|
| Unit of work | Task | Asset or op | Task |
| Graph | DAG | Asset graph | Flow |
| Execution | DagRun | Run | Flow run |
| Schedule | Timetable or cron | ScheduleDefinition |
Deployment schedule |
| Backfill | CLI/UI | Partitions and backfill | Retroactive runs |
| dbt | Cosmos or Bash | DbtProjectComponent |
prefect-dbt or shell |
None is “better” in the abstract. The question is which model fits your team and the way it already thinks about data.
Airflow: the standard you inherited
Airflow is the veteran, and the one your company most likely already runs. The current version (3.4 at the time of writing) uses airflow.sdk for the DAG and standard providers for operators. To try it locally:
uv venv && source .venv/bin/activate
uv pip install apache-airflow
airflow standalone
A DAG with TaskFlow and a BashOperator that invokes dbt:
from datetime import timedelta
import pendulum
from airflow.providers.standard.operators.bash import BashOperator
from airflow.sdk import dag, task
@dag(
dag_id="daily_revenue",
schedule="0 6 * * *",
start_date=pendulum.datetime(2026, 1, 1, tz="UTC"),
catchup=False,
default_args={"retries": 2, "retry_delay": timedelta(minutes=5)},
tags=["revenue", "dbt"],
)
def daily_revenue():
@task
def extract(ds=None):
print(f"Extracting orders for {ds}")
build = BashOperator(
task_id="dbt_build",
bash_command="cd /opt/dbt/shop && dbt build --select +fct_revenue",
execution_timeout=timedelta(minutes=30),
)
extract() >> build
daily_revenue()
Airflow parses the DAG on every cycle, so top-level code must be cheap: no database connections or HTTP calls there. schedule replaced schedule_interval in Airflow 3, and catchup=False prevents a new DAG from firing months of historical runs. Data passing uses XCom, which is meant for small metadata, not DataFrames.
Its strength is the ecosystem: hundreds of providers and integrations with Kubernetes, Snowflake, Spark, dbt, and almost anything else. Its cost is operational: a metadata database, scheduler, webserver, and workers to maintain.
Dagster: assets as first-class citizens
Dagster flips the model. You do not describe “run this script”; you describe the asset you want to materialize and its dependencies. That makes the catalog, lineage, and checks part of the system instead of an afterthought.
uvx create-dagster@latest project shop
cd shop
uv run dg dev
import pandas as pd
import dagster as dg
@dg.asset(retry_policy=dg.RetryPolicy(max_retries=2, delay=60))
def raw_orders():
return pd.read_csv("data/orders.csv")
@dg.asset
def clean_orders(raw_orders: pd.DataFrame):
return raw_orders.dropna(subset=["order_id", "total"])
@dg.asset
def daily_revenue(clean_orders: pd.DataFrame):
return (
clean_orders.assign(date=pd.to_datetime(clean_orders["created_at"]).dt.date)
.groupby("date", as_index=False)["total"]
.sum()
)
@dg.asset_check(asset=daily_revenue)
def revenue_is_positive(daily_revenue: pd.DataFrame):
negatives = int((daily_revenue["total"] < 0).sum())
return dg.AssetCheckResult(passed=negatives == 0, metadata={"negatives": negatives})
daily_schedule = dg.ScheduleDefinition(
name="daily_revenue_schedule",
cron_schedule="0 6 * * *",
target=[daily_revenue],
)
defs = dg.Definitions(
assets=[raw_orders, clean_orders, daily_revenue],
asset_checks=[revenue_is_positive],
schedules=[daily_schedule],
)
Dependencies come from function arguments: daily_revenue receives clean_orders, and Dagster draws the edge. Asset checks are quality tests with results visible in the catalog. Partitions let you reprocess a specific day without rerunning all history, and backfills are a first-class operation.
For dbt, the current integration is declared in YAML:
type: dagster_dbt.DbtProjectComponent
attributes:
project: '{{ context.project_root }}/dbt'
select: "+fct_revenue"
Every dbt model appears as an asset, with its lineage and tests. It is the deepest integration of the three, and also the one that most asks you to adopt its mental model.
Prefect: Python first, minimal friction
Prefect feels like writing normal Python with decorators. There is no separate DAG or operator layer: a @flow calls @task, and Prefect records the state of every call.
uv init prefect-lab && cd prefect-lab
uv add prefect
uv run prefect server start
In another terminal:
uv run prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api
from prefect import flow, task
@task(retries=3, retry_delay_seconds=60)
def extract(date: str) -> list[dict]:
return [{"order_id": 1, "total": 120.0}]
@task
def transform(orders: list[dict]) -> list[dict]:
return [o for o in orders if o["total"] > 0]
@task
def load(orders: list[dict]) -> int:
return len(orders)
@flow(log_prints=True)
def daily_revenue(date: str = "2026-12-05"):
orders = extract(date)
clean = transform(orders)
print(f"{load(clean)} orders loaded")
if __name__ == "__main__":
daily_revenue.serve(name="daily-revenue", cron="0 6 * * *")
Run uv run python flow.py in another terminal. .serve() keeps a process listening and running the flow on schedule. For production, flow.deploy() attaches the flow to a work pool and lets a worker claim runs; that is where Docker, Kubernetes, or your own machines come in. Prefect’s dynamic model shines when the graph depends on the data: .map() fans out over a list of dates and .submit() parallelizes without declaring the graph in advance.
For dbt, the prefect-dbt collection wraps the CLI and captures artifacts; for simple pipelines, a @task that runs dbt build via subprocess is perfectly valid.
Dependencies and data passing
The syntax changes, but the problem is always the same: pass the output of one step to the next without turning the orchestrator into a database.
- Airflow:
t1 >> t2declares the edge. Data travels through XCom; for anything larger than a small JSON, write to S3 or a table and pass the path. - Dagster: function arguments are the dependency. I/O managers decide where an asset is stored (memory, Parquet, warehouse) and keep the graph from depending on a DataFrame in RAM.
- Prefect: return values flow from task to task;
.submit()and.map()add concurrency. For large volumes, store externally and pass references.
The golden rule is idempotency: a step must produce the same result if it runs twice. If your task does a plain insert without a merge or a key, the first retry duplicates rows and the orchestrator gets blamed for a design bug.
Scheduling, catchup, and backfills
Airflow uses a logical date: the 6:00 run processes the interval that ended at 6:00, not the moment it executes. With catchup=False only the latest interval runs; with True, it fills all history since start_date. Backfills are launched from the CLI or UI.
Dagster combines schedules with partitions. If you define a daily partition, backfilling a month is a catalog operation, and a schedule can be built from a partitioned job with build_schedule_from_partitioned_job. It is the most comfortable model when reprocessing is routine.
Prefect accepts cron, interval, or rrule on a deployment, and lets you launch runs with past dates from the UI or API. It does not have Dagster’s partition-centric model, but for dynamic flows it is more than enough.
In all three, set the timezone explicitly. A financial pipeline that runs “at midnight” without a timezone is a guaranteed incident on daylight-saving day.
Retries, timeouts, and alerts
Retrying without criteria makes an incident worse. A network timeout deserves a retry; a quality test failing because data is missing does not.
- Airflow:
retries,retry_delay, andexecution_timeoutper task;on_failure_callbackfor Slack or PagerDuty. While waiting, the task sits inup_for_retry; after the last attempt it becomesfailed. - Dagster:
RetryPolicy(max_retries=2, delay=60)on the asset; failures are tied to a specific materialization. Alerts are configured in Dagster+ or through webhooks. - Prefect:
@task(retries=3, retry_delay_seconds=60, timeout_seconds=3600)plus automations for state changes.
Beyond retries, define a dead-letter path: what happens to data that failed three times. If the answer is “it is lost”, you do not have a pipeline, you have a leak.
Observability: knowing what happened at 2:13
The operational question is not “did it fail?” but “what failed, with which data, what was produced, and what is downstream?”.
Airflow offers grid and graph views, per-task logs, and metrics via StatsD or OpenTelemetry. Dagster adds the asset catalog: every materialization stores metadata, checks, and lineage, so you can see a table’s health without opening five tools. Prefect shows the flow-run graph, logs, and automations on state changes.
Instrument at least four things: duration, rows processed, data freshness, and failure rate. If you also emit lineage with OpenLineage, the day a schema changes you can answer which dashboards are affected without guessing.
Local vs cloud: where each one runs
| Local | Managed | |
|---|---|---|
| Airflow | airflow standalone or Docker Compose |
MWAA, Cloud Composer, Astronomer |
| Dagster | dg dev |
Dagster+ |
| Prefect | prefect server start |
Prefect Cloud |
All three run locally for development and on a managed service in production. The real cost is not just the subscription: add workers, a metadata database, log storage, and someone’s time to upgrade versions and patch dependencies. Start local, migrate when the pipeline has users and needs on-call.
When to choose each one
Airflow if it already exists, your team knows it, and you have very heterogeneous tasks (Spark, Kubernetes, SQL, APIs). It is the least surprising option for a large team with a managed cloud offering.
Dagster if data, not scripts, is the center of your world: dbt, partitions, backfills, lineage, and checks. It is the best choice when “which tables exist and when were they updated?” should be a question the tool answers.
Prefect if your flows are dynamic Python, change often, and you want little infrastructure. It is the lowest-friction option for a small team that already writes Python and does not want a new DSL.
If the problem is running containers on Kubernetes, Argo Workflows may fit better; if it is coordinating long-running stateful workflows, Temporal is another category. Choose by problem, not by GitHub stars.
Common errors and checklist
| Error | Why it hurts | Prevention |
|---|---|---|
| Heavy code at DAG definition | Airflow runs it on every parse | Move logic inside tasks |
| XCom with DataFrames | Bloats the metadata database | Store in S3 or a table, pass the path |
Accidental catchup=True |
Fires months of runs | Set it explicitly on every DAG |
| Non-idempotent retries | Duplicate rows | merge, unique keys, or upsert |
| No alerts | You hear about it from sales | On-call alerts and thresholds |
| Only tested locally | Missing secrets, network, deps | CI with the same runtime |
| Orchestrating every dbt model | Hundreds of tasks and cost | dbt build --select or Cosmos with judgment |
Checklist.
- Does the graph declare real dependencies, not just execution order?
- Is every task idempotent?
- Do retries distinguish transient errors from data errors?
- Are there timeouts and a destination for terminal failures?
- Are backfills tested before you need them?
- Do alerts reach someone who can act?
- Do secrets live in a manager, not the repo?
- Can you answer what the 2:13 run produced?
The best orchestrator is not the one with the most features, but the one that lets someone at 2:13 know what failed, what can be retried, and which data was left half-written. Orchestration is, in the end, how a team sleeps at night.
Related articles
By relevance
The modern data analytics stack in 2026: from giant Excel files to the AI-powered lakehouse
Informative guide to the 2026 data stack: DuckDB, Polars, Iceberg, Parquet, AI, log observability, and how to read large files fast.
OpenTelemetry + Grafana hands-on: end-to-end observability that actually works
Hands-on OpenTelemetry and Grafana guide: signals, Collector, Python and Go instrumentation, Tempo/Loki/Mimir, queries, alerts, and cost.
Data Analysis for Backend Engineers: Using Metrics to Make Better Technical Decisions
Master data analysis as a backend engineer. Learn to collect meaningful metrics, analyze performance data, avoid common pitfalls, and make technical decisions backed by evidence instead of hunches.
Data Extraction, SQL & Automation in Go: Building Scalable Data Systems
Master data engineering in pure Go. Learn SQL querying, data extraction from multiple sources, transformation pipelines, automation workflows, and scientific data processing—all without external dependencies.