Lab: A First Airflow 3 DAG with the TaskFlow API
Install Airflow 3.4 with its constraints file, run its metadata database and a small warehouse in a PostgreSQL container, and write a daily extract, transform and load DAG with the TaskFlow API, an explicit data-interval timetable, dynamic task mapping and a connection from the environment. Test one run with airflow dags test, then let the scheduler run it.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Install Airflow with its constraints file
- Step 2: Start PostgreSQL in a container
- Step 3: Point Airflow at the database
- Step 4: Write the DAG
- Step 5: Check that Airflow can parse it
- Step 6: Test one run with airflow dags test
- Step 7: Let the scheduler run it
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Pipeline Orchestration
- What an Orchestrator Should and Should Not Do Concept · 20 min
- Lab: A First Airflow 3 DAG with the TaskFlow API Lab · 30 min
- Logical Dates, Partitions and Backfills Worked example · 25 min
- Lab: Retries, Sensors, Assets and Alerts Lab · 25 min
- The Asset-Centric Alternative: Dagster Worked example · 20 min
- Check: Orchestration Failure Scenarios Knowledge check · 8 questions
What you will learn
- Model a pipeline as a DAG of tasks or data assets with explicit dependencies, schedules and data intervals.
- Compare task-centric and asset-centric orchestration (Airflow and Dagster as examples) and run an orchestrator locally with containers.
Prerequisites: ETL/ELT Pipeline Design
01. Goal and setup
In this lab you build a daily pipeline for a small shop: for each day it extracts the orders of three regions, totals them per region and loads the totals into a warehouse table. You write it as an Airflow 3 DAG with the TaskFlow API, in which Python functions decorated with @task become tasks. You run one day with airflow dags test, which needs no scheduler, and then let the scheduler create and run a run on its own.
Airflow keeps its state in a metadata database. Its default, SQLite, is meant for development only, so the lab runs PostgreSQL 17, as production would, in a Docker container, with a second database, warehouse, standing in for the data warehouse. You need Docker, Python 3.12 and uv, a fast Python package installer (pip with the same flags also works). Tested with apache-airflow 3.4.0, its Postgres provider 7.1.1, the standard provider 1.21.0 and postgres:17-alpine. Everything stays inside one folder.
orchestration-lab/
├── .venv/ Airflow and its providers
├── env.sh step 3: settings every terminal needs
├── wait_for_runs.sh step 7: waits for runs to finish
├── airflow/ AIRFLOW_HOME: airflow.cfg, logs/
│ └── dags/orders_daily.py step 4: the DAG
└── data/ raw/ and clean/ files written by the tasks02. Step 1: Install Airflow with its constraints file
Airflow depends on more than a hundred packages, and an untested combination of their newest versions can break at import time. The project therefore publishes a constraints file for each Airflow and Python version, with the exact versions its CI tested together. The [postgres] extra adds the Postgres provider: operators and hooks for external systems ship as separate provider packages, such as apache-airflow-providers-postgres, so each can be upgraded on its own. The [graphviz] extra lets airflow dags show print the graph.
mkdir orchestration-lab && cd orchestration-lab
uv venv --python 3.12 .venv
CONSTRAINTS=https://raw.githubusercontent.com/apache/airflow/constraints-3.4.0
uv pip install --python .venv/bin/python "apache-airflow[postgres,graphviz]==3.4.0" \
--constraint "$CONSTRAINTS/constraints-3.12.txt"Resolved 138 packages in 5.71s
Installed 138 packages in 48.92s03. Step 2: Start PostgreSQL in a container
Start PostgreSQL with a user lab and a first database airflow, then create warehouse. The -p 127.0.0.1:5433:5432 option publishes the server only on your own machine, on port 5433, so it does not clash with a PostgreSQL you may already run on 5432. pg_isready confirms that the server accepts connections; if it says "no response", wait a few seconds and run it again.
docker run --name orch-pg -d -p 127.0.0.1:5433:5432 \
-e POSTGRES_USER=lab -e POSTGRES_PASSWORD=orch-lab-pw -e POSTGRES_DB=airflow \
postgres:17-alpine
sleep 5
docker exec orch-pg pg_isready -U lab -d airflow
docker exec orch-pg psql -U lab -d airflow -c "CREATE DATABASE warehouse"/var/run/postgresql:5432 - accepting connections
CREATE DATABASE04. Step 3: Point Airflow at the database
Airflow reads its settings from airflow.cfg and from environment variables named AIRFLOW__<SECTION>__<KEY>, which win over the file. Save the settings below as env.sh. AIRFLOW_HOME keeps Airflow's files in the lab folder instead of ~/airflow, and LocalExecutor runs tasks as processes on this machine.
The last line defines a connection, the record Airflow uses to reach an external system. A variable named AIRFLOW_CONN_<CONN_ID> creates the connection warehouse only in the environment of the processes that read it; it is not stored in the database or shown in the UI. The password sits in a file because this is a throwaway lab database. In production the same lookup by connection ID goes to a secrets backend such as HashiCorp Vault, and the DAG code does not change.
# Source this file in every terminal: source env.sh
source .venv/bin/activate
export AIRFLOW_HOME="$PWD/airflow" # config, logs and dags/ live here
export LAB_DATA="$PWD/data" # where the tasks write their files
export AIRFLOW__CORE__LOAD_EXAMPLES=False
export AIRFLOW__CORE__EXECUTOR=LocalExecutor
export AIRFLOW__API__HOST=127.0.0.1 # keep the UI and API on this machine
DB=lab:[email protected]:5433 # a lab-only password
export AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=postgresql+psycopg2://$DB/airflow
# A connection defined as an environment variable: AIRFLOW_CONN_<CONN_ID>
export AIRFLOW_CONN_WAREHOUSE=postgres://$DB/warehousesource env.sh
airflow version
airflow db migrate 2>&1 | grep -o "Database migration done!"3.4.0
Database migration done!airflow db migrate created Airflow's tables in the airflow database. Every terminal you open for this lab needs source env.sh first.
05. Step 4: Write the DAG
Run mkdir -p airflow/dags and save the file below as airflow/dags/orders_daily.py. The notes after it explain each decision.
"""Daily orders pipeline: extract -> transform -> load, one run per day."""
import json
import os
import random
from datetime import timedelta
from pathlib import Path
import pendulum
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.sdk import CronDataIntervalTimetable, dag, task
DATA = Path(os.environ["LAB_DATA"])
REGIONS = ["north", "south", "west"]
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=pendulum.datetime(2026, 11, 1, tz="UTC"),
catchup=False,
default_args={"retries": 2, "retry_delay": timedelta(seconds=10)},
tags=["lab"],
)
def orders_daily():
@task
def extract(region: str, *, data_interval_start, data_interval_end) -> str:
"""Pretend to call the shop API for one region and one day."""
day = data_interval_start.date()
rng = random.Random(f"{day}/{region}") # same day + region, same orders
orders = [
{"order_id": f"{region[0]}{day:%m%d}-{i}",
"amount": round(rng.uniform(5, 120), 2)}
for i in range(rng.randint(20, 40))
]
out = DATA / "raw" / f"day={day}" / f"{region}.jsonl"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("".join(json.dumps(o) + "\n" for o in orders))
print(f"extract {region}: {len(orders)} orders for "
f"{data_interval_start} to {data_interval_end}")
return str(out.relative_to(DATA)) # a small XCom: a path, not the rows
@task
def transform(paths: list[str], *, data_interval_start) -> dict:
day = data_interval_start.date()
totals = []
for path in paths:
lines = (DATA / path).read_text().splitlines()
rows = [json.loads(line) for line in lines]
totals.append({"region": Path(path).stem, "orders": len(rows),
"revenue": round(sum(r["amount"] for r in rows), 2)})
out = DATA / "clean" / f"day={day}" / "region_totals.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(totals))
print(f"transform: {len(totals)} region totals for {day}")
return {"path": str(out.relative_to(DATA)), "regions": len(totals)}
@task
def load(summary: dict, *, data_interval_start) -> int:
day = data_interval_start.date()
totals = json.loads((DATA / summary["path"]).read_text())
hook = PostgresHook(postgres_conn_id="warehouse") # from AIRFLOW_CONN_WAREHOUSE
with hook.get_conn() as conn, conn.cursor() as cur: # one transaction
cur.execute("""CREATE TABLE IF NOT EXISTS region_revenue (
day date, region text, orders int, revenue numeric(10, 2),
PRIMARY KEY (day, region))""")
cur.execute("DELETE FROM region_revenue WHERE day = %s", (day,))
for t in totals:
cur.execute("INSERT INTO region_revenue VALUES (%s, %s, %s, %s)",
(day, t["region"], t["orders"], t["revenue"]))
print(f"load: replaced {len(totals)} rows for {day}")
return len(totals)
paths = extract.expand(region=REGIONS) # dynamic task mapping: one per region
load(transform(paths))
orders_daily()- The schedule is an explicit data-interval timetable. In Airflow 3, a bare cron string such as
"@daily"usesCronTriggerTimetable, whose runs are points in time:data_interval_startanddata_interval_endare equal.CronDataIntervalTimetablegives each run the whole day, from midnight to midnight, and starts it after the day ends.catchup=False(the Airflow 3 default, written out here) stops the scheduler from creating a run for every day sincestart_date; lesson 3 covers catch-up. - Tasks receive their dates from the run. A keyword-only parameter named after a context key, such as
data_interval_start, is filled in by Airflow. No task calls the clock, so a run for 15 November always processes 15 November. - Return values are XComs, and passing them creates the edges.
load(transform(paths))makestransformupstream ofloadbecauseloadconsumes its result. Each value is small: a path relative toLAB_DATA, or a dictionary with a path and a count. The rows themselves stay in files and in the warehouse. expandis dynamic task mapping.extract.expand(region=REGIONS)creates oneextracttask instance per region when the run starts, numbered bymap_index, andtransformreceives the list of their results. If the list came from an earlier task, the number of instances would follow the data.- The load replaces its own day.
PostgresHooklooks up thewarehouseconnection, and thewithblock runs the delete and the inserts as one transaction, so a rerun replaces the day instead of adding a second copy. Idempotent Writes and a Safe Backfill covers this pattern.default_argsgives every task two retries; lesson 4 shows retries at work.
06. Step 5: Check that Airflow can parse it
Confirm that the file imports cleanly and that the graph is the one you meant. tasks list prints the tasks alphabetically, which says nothing about the order they run in; the edges from dags show do.
airflow dags list-import-errors
airflow tasks list orders_daily
airflow dags show orders_daily | grep -- '->'No data found
extract
load
transform
extract -> transform
transform -> load07. Step 6: Test one run with airflow dags test
airflow dags test runs every task of one DAG run in a single process, with no scheduler, and records the run in the metadata database. The date you give becomes the run's logical date, and for this kind of hand-started run Airflow infers the data interval from the timetable: the last complete day before 16 November 00:00, which is 15 November. The extract prints its interval so you can check. Save the long log to a file and search it.
airflow dags test orders_daily 2026-11-16 > test-run.log 2>&1; echo "exit code $?"grep '^extract' test-run.log | sort
grep -E '^(transform|load):' test-run.log
grep -o 'Returned value was: [^[]*' test-run.log | sed 's/ *$//' | sortexit code 0extract north: 38 orders for 2026-11-15 00:00:00+00:00 to 2026-11-16 00:00:00+00:00
extract south: 31 orders for 2026-11-15 00:00:00+00:00 to 2026-11-16 00:00:00+00:00
extract west: 37 orders for 2026-11-15 00:00:00+00:00 to 2026-11-16 00:00:00+00:00
transform: 3 region totals for 2026-11-15
load: replaced 3 rows for 2026-11-15
Returned value was: 3
Returned value was: {'path': 'clean/day=2026-11-15/region_totals.json', 'regions': 3}
Returned value was: raw/day=2026-11-15/north.jsonl
Returned value was: raw/day=2026-11-15/south.jsonl
Returned value was: raw/day=2026-11-15/west.jsonlThe mapped extracts can finish in any order, so the first command sorts them. The "Returned value" lines are exactly what went into XCom: three short paths, a small dictionary and a count. Now look at the warehouse.
docker exec orch-pg psql -U lab -d warehouse -c \
"SELECT * FROM region_revenue ORDER BY day, region" day | region | orders | revenue
------------+--------+--------+---------
2026-11-15 | north | 38 | 2298.82
2026-11-15 | south | 31 | 1854.56
2026-11-15 | west | 37 | 2255.47
(3 rows)Run the same test again and count the rows. Because the load deletes the day before inserting it, the second run leaves three rows with the same total instead of six.
airflow dags test orders_daily 2026-11-16 > test-run-2.log 2>&1; echo "exit code $?"
docker exec orch-pg psql -U lab -d warehouse -c \
"SELECT count(*) AS rows, sum(revenue) AS revenue FROM region_revenue"exit code 0
rows | revenue
------+---------
3 | 6408.85
(1 row)08. Step 7: Let the scheduler run it
In a second terminal, start Airflow. airflow standalone runs the scheduler, the DAG processor, the API server and the triggerer together, for development only. The password for the user admin is in airflow/simple_auth_manager_passwords.json.generated, and the UI is at http://localhost:8080. Wait for "Airflow is ready".
cd orchestration-lab && source env.sh
airflow standalonestandalone | Database ready
standalone | Airflow is readyNew DAGs start paused. In terminal 1, save the helper below as wait_for_runs.sh (it polls airflow dags list-runs until enough runs have finished), then unpause the DAG. With catchup=False the scheduler creates one scheduled run, for the most recent complete day.
#!/usr/bin/env bash
# Usage: ./wait_for_runs.sh DAG_ID RUN_ID_PREFIX COUNT
# Waits until COUNT runs of DAG_ID whose run_id starts with the prefix have finished.
dag=$1 prefix=$2 want=$3
while true; do
finished=$(airflow dags list-runs "$dag" -o plain 2>/dev/null \
| awk -v p="$prefix" 'index($2, p) == 1 && ($3 == "success" || $3 == "failed")' \
| wc -l)
[ "$finished" -ge "$want" ] && break
sleep 10
done
echo "$dag: $finished finished run(s) whose id starts with $prefix"chmod +x wait_for_runs.sh
airflow dags unpause orders_daily > /dev/null
./wait_for_runs.sh orders_daily scheduled__ 1
airflow dags list-runs orders_daily -o plain | awk '{print $2, $3, $5}'orders_daily: 1 finished run(s) whose id starts with scheduled__
run_id state logical_date
manual__2026-11-16T10:32:12.769557+00:00 success 2026-11-16T00:00:00+00:00
scheduled__2026-11-16T00:00:00+00:00 success 2026-11-15T00:00:00+00:00The manual__ run is your test from step 6. The scheduled__ run was created by the scheduler; its ID carries the end of its interval, and its logical date is the start. List the state of each task instance in it.
RUN=$(airflow dags list-runs orders_daily -o plain | awk '/ scheduled__/ {print $2}')
airflow tasks states-for-dag-run orders_daily "$RUN" -o plain \
| awk 'NR > 1 {print $3, $4, $7}' | sed 's/ *$//' | sortextract success 0
extract success 1
extract success 2
load success
transform successAll five task instances succeeded. Leave Airflow running for the next lesson. To stop, press Ctrl+C in terminal 2 and run docker stop orch-pg; docker start orch-pg brings the database back.
09. Check your understanding
10. Apply it
Turn this DAG into the first half of the skill practice:
- replace the generated orders with your own source, such as the extractor from the flaky API lab, keeping the path-only XComs;
- add a
testtask afterloadthat queries the warehouse for the day and fails if a region is missing or a total is negative; - move the region list into an Airflow Variable, and check the graph with
airflow dags show; - run the DAG in containers, as the practice asks. Follow the official Compose setup for 3.4.0 (download
docker-compose.yaml, createdags,logs,pluginsandconfig, writeAIRFLOW_UIDto.env, rundocker compose up airflow-init, thendocker compose up) and copy the DAG intodags/. Inside the containers, add the volume./data:/opt/airflow/datatox-airflow-commonand setLAB_DATAto/opt/airflow/data, create the database withdocker compose exec postgres psql -U airflow -c "CREATE DATABASE warehouse", and pointAIRFLOW_CONN_WAREHOUSEatpostgres:5432, user and passwordairflow. It needs 4 GB of memory; untested here.
11. Review prompt
Without looking back, explain: why Airflow is installed with a constraints file; what AIRFLOW_HOME and AIRFLOW_CONN_WAREHOUSE do; why the DAG uses CronDataIntervalTimetable rather than "@daily"; how TaskFlow turns return values into both XComs and edges; what expand creates at run time; and why running the test twice leaves three rows, not six.
References
- Apache Airflow: Installation from PyPI (constraints files)
- Apache Airflow: Pythonic Dags with the TaskFlow API
- Apache Airflow: Timetables
- Apache Airflow: Dynamic Task Mapping
- Apache Airflow: Managing Connections
- Apache Airflow: Set up a Database Backend
- Apache Airflow: Quick Start (airflow standalone)
- PostgreSQL provider for Apache Airflow
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.