Apache Airflow — DAG Authoring
When to Use
Load this skill when the user needs to:
- Write or review Airflow DAGs
- Use TaskFlow API, operators, or sensors
- Build task pipelines, TaskGroups, or dynamic task mapping
- Configure callbacks, pools, XComs, or cross-DAG dependencies
- Apply best practices or debug anti-patterns in DAG code
DAG Definition — Three Styles
1. Context Manager (classic)
python
import pendulum
from airflow.sdk import DAG
from airflow.providers.standard.operators.empty import EmptyOperator
with DAG(
dag_id="my_pipeline",
start_date=pendulum.datetime(2024, 1, 1, tz="UTC"),
schedule="@daily",
catchup=False,
max_active_runs=1,
default_args={
"retries": 2,
"retry_delay": pendulum.duration(minutes=5),
"owner": "data-team",
},
tags=["etl", "finance"],
doc_md="""## My Pipeline\nLoads daily finance data.""",
) as dag:
EmptyOperator(task_id="start")
2. @dag Decorator (recommended for TaskFlow)
python
from airflow.sdk import dag
import pendulum
@dag(
dag_id="my_pipeline",
start_date=pendulum.datetime(2024, 1, 1, tz="UTC"),
schedule="@daily",
catchup=False,
tags=["etl"],
)
def my_pipeline():
...
my_pipeline() # registers the DAG
3. Constructor (legacy, avoid in new code)
python
dag = DAG("my_dag", start_date=pendulum.datetime(2024, 1, 1), schedule="@daily")
task = BashOperator(task_id="t1", bash_command="echo hi", dag=dag)
Key DAG Parameters
| Parameter | Type | Description | |
|---|
dag_id | str | Unique identifier | |
start_date | datetime | First logical date to schedule (always use pendulum.datetime) | |
schedule | str / None | Cron, @daily, @hourly, timedelta, Dataset, None, @once, @continuous | |
catchup | bool | Run missed intervals since start_date. Default True — always set False unless intentional. | |
max_active_runs | int | Max concurrent DAG runs. Use 1 for sequential pipelines. | |
max_active_tasks | int | Max concurrently running tasks across all active runs | |
default_args | dict | Default params applied to every task (owner, retries, retry_delay, etc.) | |
tags | list[str] | UI filtering labels | |
params | dict | Runtime-configurable parameters exposed in UI | |
on_failure_callback | callable | Called on DAG run failure | |
sla_miss_callback | callable | Called when SLA is missed | |
render_template_as_native_obj | bool | Jinja renders to native Python types instead of strings | |
doc_md | str | Markdown docs shown in UI | |
TaskFlow API
The preferred modern style. @task wraps a Python function into an operator; return values pass automatically as XComs.
Basic Example
python
import json
import pendulum
from airflow.sdk import dag, task
@dag(
start_date=pendulum.datetime(2024, 1, 1, tz="UTC"),
schedule="@daily",
catchup=False,
)
def order_etl():
@task
def extract() -> dict:
return {"order_id": 1001, "amount": 299.99}
@task
def transform(order: dict) -> dict:
order["amount_with_tax"] = round(order["amount"] * 1.2, 2)
return order
@task
def load(order: dict) -> None:
print(f"Loading order {order['order_id']}: {order['amount_with_tax']}")
raw = extract()
enriched = transform(raw)
load(enriched)
order_etl()
multiple_outputs=True — unpack dict as separate XCom keys
python
@task(multiple_outputs=True)
def get_config() -> dict:
return {"host": "db.internal", "port": 5432, "db": "warehouse"}
cfg = get_config()
# downstream can reference cfg["host"], cfg["port"] individually
.override() — reuse task with different metadata
python
@task
def process(record: dict) -> dict:
return {**record, "processed": True}
step_a = process.override(task_id="process_customers")(customers_data)
step_b = process.override(task_id="process_orders")(orders_data)
Accessing template context inside @task
python
from airflow.sdk import get_current_context
@task
def my_task():
ctx = get_current_context()
ds = ctx["ds"] # logical date string: "2024-01-15"
ti = ctx["task_instance"]
logical_dt = ctx["logical_date"] # pendulum.DateTime
print(f"Running for {ds}")
Or as explicit kwargs:
python
@task
def my_task(ds=None, logical_date=None):
print(ds, logical_date)
Common Operators
BashOperator
python
from airflow.providers.standard.operators.bash import BashOperator
run_script = BashOperator(
task_id="run_script",
bash_command="dbt run --select +my_model --target prod",
env={"DBT_PROFILES_DIR": "/opt/airflow/dbt"},
cwd="/opt/airflow/dbt",
retries=1,
)
PythonOperator
python
from airflow.providers.standard.operators.python import PythonOperator
def transform_data(ds: str, **kwargs) -> None:
ti = kwargs["ti"]
data = ti.xcom_pull(task_ids="extract_task")
print(f"Processing {ds}: {data}")
transform = PythonOperator(
task_id="transform",
python_callable=transform_data,
op_kwargs={"extra_param": "value"}, # merged with context on call
)
BranchPythonOperator
python
from airflow.providers.standard.operators.python import BranchPythonOperator
def choose_branch(ds: str) -> str:
return "load_full" if ds.endswith("-01") else "load_incremental"
branch = BranchPythonOperator(
task_id="branch",
python_callable=choose_branch,
)
load_full = BashOperator(task_id="load_full", bash_command="echo full")
load_inc = BashOperator(task_id="load_incremental", bash_command="echo inc")
join = EmptyOperator(task_id="join", trigger_rule="none_failed_min_one_success")
branch >> [load_full, load_inc] >> join
SQLExecuteQueryOperator
python
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
run_sql = SQLExecuteQueryOperator(
task_id="merge_staging",
conn_id="trino_default",
sql="""
MERGE INTO gold.orders AS t
USING silver.orders_stage AS s ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET amount = s.amount
WHEN NOT MATCHED THEN INSERT VALUES (s.order_id, s.amount)
""",
autocommit=True,
)
HttpOperator
python
from airflow.providers.http.operators.http import HttpOperator
trigger_api = HttpOperator(
task_id="trigger_api",
http_conn_id="api_default",
endpoint="/v1/jobs/start",
method="POST",
data='{"job": "etl_run"}',
headers={"Content-Type": "application/json"},
response_check=lambda resp: resp.status_code == 202,
log_response=True,
)
TriggerDagRunOperator — cross-DAG trigger
python
from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator
trigger_downstream = TriggerDagRunOperator(
task_id="trigger_reporting_dag",
trigger_dag_id="reporting_pipeline",
conf={"source_dag_run_id": "{{ run_id }}", "ds": "{{ ds }}"},
wait_for_completion=True, # block until triggered DAG finishes
poke_interval=60,
failed_states=["failed"],
)
Sensors
Sensors wait for a condition to be met before allowing downstream tasks to proceed.
Sensor Modes
| Mode | Behavior | Use Case | |
|---|
poke (default) | Holds a worker slot continuously | Short waits (< 5 min) | |
reschedule | Releases slot between checks | Long waits (hours); saves worker slots | |
Always use `mode="reschedule"` for waits longer than a few minutes.
Core Parameters
python
sensor = MySensor(
task_id="wait_for_data",
poke_interval=60, # seconds between checks
timeout=3600, # fail after this many seconds
mode="reschedule", # release worker slot between pokes
soft_fail=False, # True = SKIPPED instead of FAILED on timeout
exponential_backoff=True, # progressively increase poke_interval
)
FileSensor
python
from airflow.providers.standard.sensors.file import FileSensor
wait_for_file = FileSensor(
task_id="wait_for_landing_file",
filepath="/data/landing/orders_{{ ds_nodash }}.csv",
poke_interval=300,
timeout=7200,
mode="reschedule",
)
HttpSensor
python
from airflow.providers.http.sensors.http import HttpSensor
wait_for_api = HttpSensor(
task_id="wait_for_api",
http_conn_id="api_default",
endpoint="/v1/status",
request_params={"date": "{{ ds }}"},
response_check=lambda resp: resp.json().get("status") == "ready",
poke_interval=60,
timeout=1800,
mode="reschedule",
)
ExternalTaskSensor — wait for another DAG
python
from airflow.providers.standard.sensors.external_task import ExternalTaskSensor
wait_upstream = ExternalTaskSensor(
task_id="wait_for_ingestion",
external_dag_id="ingestion_pipeline",
external_task_id="load_complete", # None = wait for whole DAG run
execution_date_fn=lambda dt: dt, # map this DAG's logical date to upstream's
timeout=3600,
mode="reschedule",
failed_states=["failed", "upstream_failed"],
)
@task.sensor Decorator
python
from airflow.sdk import task
from airflow.sdk.types import PokeReturnValue
@task.sensor(poke_interval=60, timeout=3600, mode="reschedule")
def wait_for_partition(ds: str) -> PokeReturnValue:
from my_hooks import HiveHook
hook = HiveHook(hive_conn_id="hive_default")
ready = hook.check_for_named_partition("db", "orders", f"dt={ds}")
return PokeReturnValue(is_done=ready, xcom_value=ds if ready else None)
Task Dependencies
python
# Basic chaining
extract >> transform >> load
# Fan-out / Fan-in
extract >> [transform_a, transform_b] >> join
# Reverse arrow
join << [transform_a, transform_b]
# Sequential list
from airflow.sdk import chain
chain(t1, t2, t3, t4)
# Pairwise (lists must be equal length)
chain(extract, [clean_a, clean_b], [load_a, load_b], report)
# Cross-product dependencies
from airflow.sdk import cross_downstream
cross_downstream([source_a, source_b], [target_x, target_y])
# Equivalent to: source_a >> [target_x, target_y]; source_b >> [target_x, target_y]
Trigger Rules
| Rule | Meaning | |
|---|
all_success (default) | All direct upstream tasks succeeded | |
all_failed | All upstream failed | |
all_done | All upstream finished (any state) | |
all_skipped | All upstream skipped | |
one_success | At least one upstream succeeded | |
one_failed | At least one upstream failed | |
one_done | At least one upstream finished | |
none_failed | No upstream failed (success or skip OK) | |
none_skipped | No upstream skipped | |
none_failed_min_one_success | No failures, at least one success (use after branching) | |
always | Run regardless of upstream state | |
python
# Correct join after branching
join = EmptyOperator(
task_id="join",
trigger_rule="none_failed_min_one_success",
)
# Watcher pattern: alert on any upstream failure
from airflow.exceptions import AirflowException
@task(trigger_rule="one_failed", retries=0)
def watcher():
raise AirflowException("A pipeline task failed — see upstream logs.")
# Wire watcher to all other tasks
list(dag.tasks) >> watcher()
TaskGroups
Organize related tasks into collapsible UI groups.
Decorator Style (recommended)
python
from airflow.sdk import task, task_group
@dag(schedule="@daily", start_date=pendulum.datetime(2024, 1, 1), catchup=False)
def my_pipeline():
@task_group(group_id="ingest", default_args={"retries": 3})
def ingest_group():
@task
def fetch_orders(): ...
@task
def fetch_customers(): ...
fetch_orders()
fetch_customers()
@task_group(group_id="transform")
def transform_group():
@task
def clean(): ...
@task
def enrich(): ...
clean() >> enrich()