Apache Airflow: DAGs, Operators, Scheduling
Master Apache Airflow: DAGs, operators, sensors, XCom, scheduling, backfilling, connections, variables, and production patterns for data pipelines.
Introduction
Apache Airflow orchestrates data pipelines as directed acyclic graphs (DAGs): you declare tasks and their dependencies in Python, and Airflow’s scheduler decides when each task runs, its executor runs it, and the metadata database records what happened. The model is simple; production is not. Most Airflow incidents trace back to a handful of misunderstandings — start_date semantics, catchup surprises, sensors eating worker slots, XCom misused as a data channel.
This guide covers the pieces that matter day to day: DAG definition (classic and TaskFlow API), the operators you will actually use, sensors, XCom, scheduling and backfilling, connections and variables, executors, pools, testing, and the mistakes that bite new deployments. Examples target Airflow 2.x APIs; where Airflow 3 changed something, the notes call it out. For a hands-on recipe focused on scheduling and monitoring DAGs, see Schedule and Monitor DAGs with Apache Airflow.
A word on scope: this is about authoring and operating DAGs, not installing Airflow — assume a running scheduler and workers, local or managed (MWAA, Cloud Composer, Astronomer, self-hosted on Kubernetes). Everything below behaves identically across them, which is part of the point of writing portable DAGs — pipelines that read the same whether they run on your laptop or in a managed service.
Core Concepts
Before any code, the vocabulary needs to be solid — most Airflow confusion is actually vocabulary confusion.
DAG: Directed Acyclic Graph — a collection of tasks with dependencies
Task: A unit of work (run a script, call an API, execute SQL)
Operator: A template for creating tasks (BashOperator, PythonOperator, etc.)
Task Instance: A specific run of a task at a specific time
DAG Run: A specific execution of a DAG at a specific time
Scheduler: Process that decides when to run tasks
Executor: Component that executes tasks (Sequential, Local, Celery, Kubernetes)
Worker: Process that runs task instances
XCom: Cross-task communication (small data passing between tasks)
Hook: Interface to external systems (S3Hook, SnowflakeHook, PostgresHook)
Connection: Stored credentials for external systems
Variable: Key-value configuration stored in metadata DB
The two relationships that matter most: a DAG Run is one execution of the whole graph (identified by its logical date, which is the start of the interval it covers, not the time it actually ran — this trips everyone up), and a Task Instance is one run of one task inside a DAG Run. Retries create new task instances inside the same DAG run; backfills create new DAG runs.
DAG Runs, Logical Dates, and Data Intervals
Airflow schedules by data interval, not by wall clock. A daily DAG covering January 1st creates a DAG run whose logical date is January 1st — but the run actually executes at the end of the interval, January 2nd at midnight. Everything downstream inherits this: {{ ds }} renders the interval start (January 1st), not the execution moment. This is deliberate: your pipeline processes “yesterday’s data”, so the run is named after the data it covers.
The consequences ripple through operations. Backfills are just creating runs for each logical date in the range. catchup means “create runs for every interval between start_date and now”. max_active_runs caps how many of those can run in parallel. And when a DAG seems “one day behind” — it isn’t; the Jan-1 run is Jan-2’s 00:00 execution, named for the data it processes.
Three details complete the mental model. First, schedule=None makes a DAG manual-only — no intervals get created, but ds still resolves to the execution date on triggered runs. Second, late deployments combine badly with catchup: deploying on July 1st a daily DAG with start_date of January 1st creates ~180 queued runs instantly. Third, depends_on_past=True forces each run to wait for the previous interval to succeed — correct for incremental pipelines where order matters, wrong when you want parallel backfills.
DAG Basics
Every Airflow DAG has two contracts: identity (dag_id, start_date, schedule) and behavior (default_args, catchup, max_active_runs). Get default_args right once and it applies to every task — retries, failure emails, depends_on_past.
Simple DAG
# dags/simple_dag.py
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
default_args = {
"owner": "data-team",
"depends_on_past": False,
"retries": 2,
"retry_delay": timedelta(minutes=5),
"email_on_failure": False,
"email_on_retry": False,
}
dag = DAG(
"simple_etl",
default_args=default_args,
description="Simple ETL pipeline",
schedule="0 2 * * *", # Daily at 2 AM
start_date=datetime(2026, 1, 1),
catchup=False,
max_active_runs=1,
tags=["etl", "daily"],
)
extract = BashOperator(
task_id="extract",
bash_command="python /opt/etl/extract.py --date {{ ds }}",
dag=dag,
)
def transform(**context):
import pandas as pd
date = context["ds"]
df = pd.read_csv(f"/data/raw/{date}/orders.csv")
df["total"] = df["subtotal"] + df["tax"]
df.to_csv(f"/data/processed/{date}/orders.csv", index=False)
transform_task = PythonOperator(
task_id="transform",
python_callable=transform,
dag=dag,
)
load = BashOperator(
task_id="load",
bash_command="python /opt/etl/load.py --date {{ ds }}",
dag=dag,
)
extract >> transform_task >> load
Two details here are worth internalizing. First, {{ ds }} is a Jinja template Airflow renders at execution time — it works in bash_command because that parameter is templated, but it does not work inside a Python callable’s body (see the XCom section for why that matters). Inside transform, the equivalent is context["ds"]. Second, catchup=False combined with start_date is the single most important default to set deliberately: with catchup on, deploying this DAG on July 1st creates runs for every day since January 1st, all at once.
TaskFlow API (Airflow 2.x)
TaskFlow removes the boilerplate: decorate a function with @task, return values flow to downstream tasks via XCom automatically, and the DAG itself is a decorated Python function. For new pipelines this should be the default style.
# dags/taskflow_dag.py — Modern TaskFlow API
from airflow.decorators import dag, task
from datetime import datetime
@dag(
schedule="0 2 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
tags=["etl", "taskflow"],
)
def orders_pipeline():
@task
def extract(date: str) -> dict:
import requests
resp = requests.get(f"https://api.example.com/orders?date={date}")
return resp.json()
@task
def transform(raw_data: dict) -> list[dict]:
orders = []
for order in raw_data["orders"]:
orders.append({
"order_id": order["id"],
"total": order["subtotal"] + order["tax"] + order["shipping"],
"status": order["status"],
})
return orders
@task
def load(orders: list[dict], date: str) -> None:
from airflow.providers.postgres.hooks.postgres import PostgresHook
hook = PostgresHook(postgres_conn_id="warehouse")
for order in orders:
hook.run(
"INSERT INTO orders (order_id, total, status, load_date) VALUES (%s, %s, %s, %s) "
"ON CONFLICT (order_id) DO UPDATE SET total=EXCLUDED.total, status=EXCLUDED.status",
parameters=(order["order_id"], order["total"], order["status"], date),
)
raw = extract("{{ ds }}")
cleaned = transform(raw)
load(cleaned, "{{ ds }}")
Notice the upsert in load — ON CONFLICT DO UPDATE makes the task idempotent, which is the property that makes retries and backfills safe. A task that can run twice for the same logical date and produce the same final state is a task you can always re-run without thinking.
When to Use Airflow
Airflow earns its operational weight when:
- Pipelines have real dependencies — extraction must finish before transform, transform before load, and upstream tables before downstream aggregates.
- You need backfill and retry semantics — data platforms live on reprocessing, and Airflow’s interval-based scheduling was built for it.
- Workflows need calendar awareness — “run this for each day” with a logical date per run is Airflow’s core abstraction.
- You already operate Python infrastructure — DAGs are Python, testing DAGs is Python, the mental model stays in one language.
It’s the wrong tool for event-driven sub-minute orchestration (use a queue + workers), for notebook-style interactive work (use the notebook), or when a cron job on one machine genuinely covers the need. Adding Airflow to run one daily script is how teams end up maintaining a scheduler instead of a pipeline.
Operators
Operators are task templates. The mistake is defaulting to PythonOperator for everything — specialized operators (Snowflake, Spark, dbt) give you provider-managed logging, templated parameters, and hooks that handle authentication, for free.
Common operators
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from airflow.operators.email import EmailOperator
from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator
from airflow.providers.amazon.aws.operators.s3 import S3CopyObjectOperator
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
from airflow.operators.empty import EmptyOperator
# Bash: run shell commands
run_script = BashOperator(
task_id="run_script",
bash_command="python /opt/jobs/process.py --date {{ ds }} --env prod",
)
# Python: call Python functions
process_data = PythonOperator(
task_id="process_data",
python_callable=my_function,
op_kwargs={"date": "{{ ds }}", "batch_size": 1000},
)
# Snowflake: execute SQL
run_sql = SnowflakeOperator(
task_id="run_sql",
sql="MERGE INTO orders USING staging_orders ON orders.id = staging_orders.id WHEN MATCHED THEN UPDATE ...",
snowflake_conn_id="snowflake_prod",
)
# Spark: submit Spark jobs
spark_job = SparkSubmitOperator(
task_id="spark_job",
conn_id="spark_default",
application="/opt/jobs/transform.py",
application_args=["--input", "s3://data/{{ ds }}/"],
conf={"spark.executor.memory": "4g", "spark.executor.cores": "2"},
)
# Email: send notifications
notify = EmailOperator(
task_id="notify",
to="data-team@company.com",
subject="Pipeline completed for {{ ds }}",
html_content="<p>Daily ETL completed successfully.</p>",
)
# Empty: no-op for grouping (was DummyOperator before Airflow 2.4)
start = EmptyOperator(task_id="start")
end = EmptyOperator(task_id="end")
A note on imports: airflow.operators.dummy and DummyOperator were deprecated in Airflow 2.4 and removed in Airflow 3 — use airflow.operators.empty.EmptyOperator. If you see DummyOperator in older code, it’s the same no-op with a worse name.
Branching
BranchPythonOperator returns the task_id(s) to execute; everything else on that branch is skipped. The critical piece is the join task’s trigger_rule — default all_success would never run because the skipped sibling counts as not-success. none_failed (or none_failed_min_one_success) lets the flow reconverge.
from airflow.operators.python import BranchPythonOperator
from airflow.operators.empty import EmptyOperator
def check_date(**context):
date = context["ds"]
day_of_week = datetime.strptime(date, "%Y-%m-%d").weekday()
if day_of_week == 6: # Sunday
return "weekly_aggregation"
return "daily_aggregation"
branch = BranchPythonOperator(
task_id="branch",
python_callable=check_date,
dag=dag,
)
daily = BashOperator(task_id="daily_aggregation", bash_command="...", dag=dag)
weekly = BashOperator(task_id="weekly_aggregation", bash_command="...", dag=dag)
join = EmptyOperator(task_id="join", trigger_rule="none_failed", dag=dag)
branch >> [daily, weekly] >> join
Sensors
Sensors poll until a condition is true — a file appears, an upstream DAG finishes, a SQL check passes. The decision that matters is mode: in poke mode the sensor holds a worker slot the entire wait, which means ten sensors waiting an hour each can starve a small pool. reschedule frees the slot between checks and is the right default for anything longer than a couple of minutes.
from airflow.sensors.filesystem import FileSensor
from airflow.sensors.s3 import S3KeySensor
from airflow.sensors.sql import SqlSensor
from airflow.sensors.external_task import ExternalTaskSensor
from airflow.sensors.date_time import DateTimeSensor
# Wait for a file to appear
wait_for_file = FileSensor(
task_id="wait_for_file",
filepath="/data/raw/{{ ds }}/orders.csv",
poke_interval=60, # Check every 60 seconds
timeout=3600, # Give up after 1 hour
mode="poke", # or "reschedule" to free worker slot
dag=dag,
)
# Wait for S3 object
wait_for_s3 = S3KeySensor(
task_id="wait_for_s3",
bucket_key="raw/{{ ds }}/orders.parquet",
bucket_name="my-data-bucket",
aws_conn_id="aws_default",
poke_interval=300,
timeout=7200,
dag=dag,
)
# Wait for SQL condition
wait_for_data = SqlSensor(
task_id="wait_for_data",
sql="SELECT COUNT(*) FROM staging WHERE load_date = '{{ ds }}' AND status = 'ready'",
conn_id="warehouse",
poke_interval=60,
timeout=3600,
dag=dag,
)
# Wait for another DAG to complete
wait_for_upstream = ExternalTaskSensor(
task_id="wait_for_upstream",
external_dag_id="ingestion_pipeline",
external_task_id="load_to_warehouse",
check_existence=True,
poke_interval=300,
timeout=7200,
dag=dag,
)
Two production notes. First, always set timeout deliberately — a sensor without a sane timeout is a stuck DAG run. Second, check_existence=True on ExternalTaskSensor makes the sensor fail fast if the upstream DAG was deleted, instead of polling a ghost forever.
XCom (Cross-Task Communication)
XCom pushes small values into the metadata database for downstream tasks to pull. With TaskFlow it’s implicit — whatever a task returns lands in XCom. The rule that survives every incident review: XCom is for metadata (counts, paths, flags, IDs), never for the data itself. Its ceiling is a few KB per value, and every XCom write is a row in the metadata DB — passing a DataFrame through it is how schedulers get slow.
# XCom passes small data between tasks. For large data, use external storage.
@task
def extract():
# Small data: return directly (passed via XCom)
return {"total_orders": 1500, "total_revenue": 45000.00}
@task
def validate(stats):
if stats["total_orders"] < 1:
raise ValueError("No orders found")
return stats
@task
def report(stats):
print(f"Orders: {stats['total_orders']}, Revenue: ${stats['total_revenue']}")
# For large data, use external storage (S3, GCS)
@task
def extract_large(date: str):
import pandas as pd
from airflow.providers.postgres.hooks.postgres import PostgresHook
hook = PostgresHook(postgres_conn_id="warehouse")
df = hook.get_pandas_df(f"SELECT * FROM orders WHERE date = '{date}'")
path = f"/tmp/orders_{date}.parquet"
df.to_parquet(path)
return path # Pass the path, not the data
@task
def transform_large(path):
import pandas as pd
df = pd.read_parquet(path)
# Transform...
return path
Note the templating correction versus naive examples: {{ ds }} is only rendered in operator template fields, never inside a Python function body. In TaskFlow, accept the date as a parameter (date: str) and pass "{{ ds }}" at the call site — the decorator templates the argument before invoking the function.
If you’re maintaining DAGs written with classic operators instead of TaskFlow, XCom is explicit rather than implicit: tasks call context["ti"].xcom_push(key="stats", value=...) and downstream callables read context["ti"].xcom_pull(task_ids="extract", key="stats"). BashOperator exposes only the last line of stdout via XCom (do_xcom_push=True), which is handy for scripts that print a JSON summary on their final line. In Jinja fields you can pull inline with {{ ti.xcom_pull(task_ids='extract', key='stats') }} — the same retrieval TaskFlow hides behind function arguments. Reach for explicit push/pull when a task emits several named values rather than one return value.
Scheduling and Backfilling
Scheduling in Airflow is interval-based: with schedule="@daily" and start_date of January 1st, the run for January 1st fires at the end of that interval (January 2nd 00:00). This is the most-asked “why didn’t my DAG run” question — a daily DAG deployed today produces its first run tomorrow at midnight, not immediately.
# Schedule presets
dag = DAG(
"scheduled_pipeline",
schedule="@daily", # Daily at midnight
# schedule="@hourly", # Every hour
# schedule="@weekly", # Weekly on Sunday
# schedule="@monthly", # Monthly on the 1st
# schedule="0 2 * * 1-5", # 2 AM on weekdays (cron)
# schedule="*/15 * * * *", # Every 15 minutes
# schedule=None, # Manual trigger only
start_date=datetime(2026, 1, 1),
catchup=True, # Backfill missing runs
max_active_runs=1, # Only one run at a time
)
catchup=True plus an old start_date is the classic footgun: deploy a daily DAG in July with a January start_date and you just scheduled ~180 runs at once — against a small worker pool that’s an outage. Set catchup=False on new DAGs and backfill deliberately when you actually want historical runs.
Backfilling
# Backfill a date range
airflow dags backfill orders_pipeline \
--start-date 2026-01-01 \
--end-date 2026-01-31
# Trigger a single manual run
airflow dags trigger orders_pipeline --execution-date 2026-06-01
airflow dags backfill runs the range through the scheduler with your DAG’s normal dependency logic; airflow dags trigger creates one run on demand. Watch out for max_active_runs: a backfill on a DAG capped at 1 runs sequentially — fine, just slow. Before mass backfills, verify the pipeline is idempotent (upserts, not appends) or you will backfill duplicates into production tables.
Pools and Concurrency Control
max_active_runs caps whole DAG runs, but pressure often comes from tasks: fifty parallel tasks hitting the same warehouse or API is a self-inflicted rate-limit storm. Pools solve this — a named semaphore (default_pool exists out of the box) that limits how many task instances using that pool can run concurrently:
heavy_query = SnowflakeOperator(
task_id="heavy_query",
sql="SELECT ...",
snowflake_conn_id="warehouse_prod",
pool="warehouse_queries", # create it in Admin → Pools with N slots
pool_slots=2, # this task weighs 2 of N slots
)
Weighted slots (pool_slots) let one pool budget different task sizes — a reporting query costing 4 slots and a metadata check costing 1 coexist under the same ceiling. Typical pools: one per external system (snowflake_prod, rest_api, gpu_queue) sized to what the downstream tolerates. During backfills this matters double — the pool prevents the historical burst from DDoSing your own warehouse.
Related knobs worth knowing: max_active_tasks on the DAG limits concurrent task instances within one DAG, and parallelism/max_active_tasks_per_dag in airflow.cfg set deployment-wide ceilings. The hierarchy that actually applies per task: pool slots → DAG max_active_tasks → executor capacity.
Connections and Variables
Credentials and environment-specific config live in the metadata database, not in DAG files. Connections carry full connection specs (host, port, login, extras); Variables carry simple key-values. Hooks consume connections so tasks never see raw credentials.
# Connections: stored in Airflow metadata DB or environment variables
# Set via UI: Admin → Connections
# Or via CLI: airflow connections add ...
from airflow.providers.postgres.hooks.postgres import PostgresHook
# Use connection in a task
def load_data(**context):
hook = PostgresHook(postgres_conn_id="warehouse_prod")
conn = hook.get_conn()
cursor = conn.cursor()
cursor.execute("INSERT INTO ... VALUES (%s)", (context["ds"],))
conn.commit()
# Variables: key-value config stored in metadata DB
from airflow.models import Variable
def get_config():
batch_size = Variable.get("batch_size", default_var=1000)
api_url = Variable.get("api_url")
return {"batch_size": int(batch_size), "api_url": api_url}
# Environment variable fallback
# AIRFLOW_VAR_API_URL=https://api.example.com
api_url = Variable.get("api_url") # Falls back to AIRFLOW_VAR_API_URL
Two operational points. First, AIRFLOW_VAR_* and AIRFLOW_CONN_* environment variables override the database — the clean way to inject secrets from Kubernetes or CI without touching Airflow storage. Second, every Variable.get() call at DAG-parse time is a metadata-DB query on every parse of every file — read variables inside the task function (runtime), never at module top level, or you will find your scheduler doing thousands of queries per second just re-parsing DAGs.
Executors and Deployment Topologies
The executor decides where task instances run, and the choice is mostly decided for you by scale:
- SequentialExecutor — one task at a time, SQLite backend. Demo and tutorial only; it can’t run tasks in parallel at all.
- LocalExecutor — parallelism via processes on the scheduler’s machine. The right answer for single-node setups and small teams; your ceiling is that machine’s RAM and CPU.
- CeleryExecutor — distributes tasks across a Celery worker fleet via a broker (RabbitMQ/Redis). The classic horizontal-scaling answer; you gain worker independence and lose simplicity — one more cluster to operate.
- KubernetesExecutor — every task instance is a Pod. Per-task isolation, per-task resources, elastic scale; tasks that need 32GB don’t pay for pods that need 1GB. Requires Kubernetes operations maturity.
The hybrid worth knowing: KubernetesExecutor for heterogeneous workloads, CeleryKubernetesExecutor (or Celery workers + KubernetesPodOperator) when you want one foot in each world — Celery for bulk small tasks, K8s pods for the heavy or special-dependency ones. Whatever you pick, the scheduler is the component to monitor: DAG parse time, heartbeat freshness, and queued-vs-running task counts predict trouble earlier than any task log.
Testing DAGs
DAGs are Python code and should be tested like Python code — most Airflow bugs are actually import-time bugs that break parsing, not runtime bugs.
# tests/test_dags.py — run in CI alongside unit tests
import pytest
from airflow.models import DagBag
def test_no_import_errors():
dag_bag = DagBag(dag_folder="dags/", include_examples=False)
assert len(dag_bag.import_errors) == 0, f"DAG import failures: {dag_bag.import_errors}"
def test_catchup_disabled():
dag_bag = DagBag(dag_folder="dags/", include_examples=False)
for dag in dag_bag.dags.values():
assert dag.catchup is False, f"{dag.dag_id} has catchup enabled"
def test_dag_loaded():
dag_bag = DagBag(dag_folder="dags/", include_examples=False)
assert "simple_etl" in dag_bag.dags
The DagBag import test catches the most common production failure — a DAG that fails to parse never appears in the UI, and the first symptom is a silent “my DAG is gone” report. Layer on top: unit-test your Python callables directly (they’re plain functions), and use dag.test() in Airflow 2.5+ to execute a DAG end-to-end against mocked external systems before deploying.
Best Practices
- Use TaskFlow API for new DAGs — cleaner, less boilerplate than traditional operators
- Set
catchup=Falsefor new DAGs — avoid accidental backfills of years of data - Use
max_active_runs=1for pipelines that shouldn’t overlap — prevents race conditions - Use sensors with
mode="reschedule"for long waits — frees worker slots - Pass large data via external storage (S3, GCS), not XCom — XCom is for small metadata
- Use
retriesandretry_delayindefault_args— transient failures are common - Use
retry_exponential_backoff=True— avoid hammering failing APIs - Store credentials in Connections, not in code — use Airflow UI or CLI
- Use Variables for environment-specific config — not hardcoded values
- Tag your DAGs —
tags=["etl", "daily", "prod"]for filtering in UI - Keep DAG files under 1000 lines — split complex pipelines into separate DAGs
- Use
ExternalTaskSensorfor cross-DAG dependencies — don’t duplicate upstream logic - Read Variables inside tasks, not at module level — top-level
Variable.get()runs on every parse - Write idempotent tasks — upserts and deletes-before-inserts make retries and backfills safe
Common Mistakes
- Using
datetime.now()asstart_date: DAGs never start because the scheduler looks for the next run after start_date. Use a fixed date. - Setting
catchup=Trueaccidentally: Airflow tries to run every missed run since start_date. Usecatchup=Falsefor new DAGs. - Passing large data through XCom: XCom stores data in the metadata DB. Use S3/GCS paths instead.
- Not setting
max_active_runs: overlapping runs cause race conditions and duplicate data. - Hardcoding credentials: use Connections and Variables. Never put passwords in DAG files.
- Using
PythonOperatorfor everything: use specialized operators (SnowflakeOperator, SparkSubmitOperator) for better logging and error handling. - Expecting
{{ ds }}to render inside a Python function body: templates render in operator fields only. Passcontext["ds"]or a templated argument instead. - Running
airflow dags run: the command isairflow dags trigger—dags rundoesn’t exist and fails silently on some aliases.
Operations: SLAs, Alerts, and Monitoring
Airflow’s own observability splits into three mechanisms that answer different questions:
slaparameter — a deadline measured from the run’s logical date.sla=timedelta(hours=2)on a task means “this task must finish within 2h of the interval start or flag a miss”. SLAs land in thesla_misstable and surface in the UI — good for hard freshness commitments on daily tables.- Callbacks —
on_failure_callbackandon_success_callbackondefault_argsfire Python functions on task outcomes;on_failure_callbackon the DAG itself catches run-level failure. This is where Slack/PagerDuty/webhook alerting lives — one function, reused across every DAG. - Scheduler metrics — Airflow emits StatsD metrics (or OpenTelemetry in 2.8+):
dag_processing.total_parse_time,scheduler_heartbeat,executor.open_slots. Alerting on parse-time growth or a stale heartbeat catches the failures where tasks never even queue.
A working alert setup is simpler than it looks: on_failure_callback pointing at a function that posts the DAG id, run date, failed task, and log URL to your on-call channel covers 90% of incidents. SLAs handle freshness promises. Scheduler metrics handle the platform itself.
Airflow 2 to 3 Migration Notes
If you are running Airflow 2.x and eyeing 3.x, the changes that reach these examples:
DummyOperatoris gone —EmptyOperator(shown throughout) is the replacement; theairflow.operators.dummymodule no longer exists.schedule_intervalwas already deprecated in 2.x in favor ofschedule— in 3.x onlyscheduleexists, plus a newtimetableconcept for custom calendars (trading days, fiscal quarters).- The
execution_datenaming is gone in favor oflogical_date— code readingcontext["execution_date"]should readcontext["logical_date"]. airflow dags backfillgained a proper CLI in 3.x (in 2.x it lived underairflow dags backfillwith slightly different flags) — verify flag names against your installed version before scripting.- Providers moved to versioned packages (
apache-airflow-providers-*) — pin them separately from core, because their releases no longer follow core’s cadence.
The migration worth planning isn’t the code — it’s the DAGs relying on implicit behaviors (catchup defaults, execution_date semantics). Run the DagBag tests above against the new version in CI before upgrading the scheduler.
See Also
- Schedule and Monitor DAGs with Apache Airflow — hands-on scheduling recipe
- Complete Guide to Data Pipeline Architecture
- Complete Guide to dbt Data Transformations
- Complete Guide to Data Quality
- Companion resources — runnable DAG examples: ETL, TaskFlow, branching, sensors, XCom
Further Reading
- Apache Airflow documentation — concepts, operators, and scheduler internals
- TaskFlow tutorial — official TaskFlow walkthrough
- Airflow 3.0 release notes — breaking changes including
DummyOperatorremoval - Astronomer: Airflow best practices — field-tested operational guidance
Frequently Asked Questions
What is a DAG in Airflow?
A Directed Acyclic Graph — a collection of tasks with defined dependencies. Tasks execute in order based on the dependency graph. "Acyclic" means no circular dependencies.
What is the difference between schedule and start_date?
start_date is when the DAG's first run is eligible to execute. schedule determines how often it runs after that. The scheduler only creates runs for dates >= start_date at the specified interval.
What is XCom?
Cross-task communication. Tasks can push and pull small data (a few KB) through XCom. For larger data, write to external storage (S3, GCS) and pass the file path via XCom.
What is the difference between poke and reschedule sensor modes?
In poke mode, the sensor occupies a worker slot while waiting. In reschedule mode, the sensor releases the worker slot between checks. Use reschedule for long waits (>1 minute) to avoid blocking workers.
Should I use TaskFlow API or traditional operators?
TaskFlow API (Airflow 2.x) is cleaner and handles XCom automatically through function return values. Use it for new DAGs. Traditional operators are still needed for specialized cases like SparkSubmitOperator or SnowflakeOperator.
Related Resources
Data Pipeline Architecture: Batch, Streaming, Lambda, Kappa
Design batch and streaming data pipelines — working Airflow, Flink and dbt code, Lambda vs Kappa trade-offs, and a decision table for ETL vs ELT.
Guidedbt: Models, Tests, Macros, Materializations
Learn dbt for data transformations: models, tests, macros, materializations, seeds, snapshots, and production patterns for analytics engineers.
GuideData Quality Guide: Validation, Profiling, Monitoring
Master data quality: validation frameworks, profiling, schema enforcement, anomaly detection, and pipeline checks with Great Expectations, Pandera, and Soda.
RecipeSchedule and Monitor DAGs with Apache Airflow
Define, schedule, and monitor Airflow DAGs with operators, sensors, XCom, task dependencies, and the TaskFlow API.