Airflow Cheatsheet
Apache Airflow reference: schedule syntax, data intervals explained properly, TaskFlow patterns, template variables, CLI commands and the traps everyone hits.
Schedule syntax
The schedule argument accepts a cron string, a preset, a timedelta, or a timetable object.
| Value | Meaning |
|---|---|
| None | Never scheduled. Triggered manually or by another DAG. Use this for target DAGs of TriggerDagRunOperator. |
| "@once" | Run exactly one time, then never again. |
| "@hourly" | Equivalent to 0 * * * *. |
| "@daily" | Equivalent to 0 0 * * * — midnight in the DAG timezone. |
| "@weekly" | Equivalent to 0 0 * * 0 — midnight on Sunday. |
| "@monthly" | Equivalent to 0 0 1 * * — midnight on the 1st. |
| "@yearly" / "@annually" | Equivalent to 0 0 1 1 *. |
| "30 4 * * 1-5" | Any five-field cron expression. Fields are minute, hour, day-of-month, month, day-of-week. |
| timedelta(hours=6) | Relative schedule: the next run is scheduled a fixed delta after the previous data interval, so it does not align to wall-clock boundaries the way cron does. |
| CronTriggerTimetable("0 2 * * *", timezone="Asia/Kolkata") | Cron semantics where the run fires *at* the cron time rather than at the end of an interval. Use it when a schedule must track local time through DST. |
| Datasets / asset list | Schedule on data rather than time: the DAG runs when every dataset it depends on has been updated by a producer task. |
┌─ minute 0-59
│ ┌─ hour 0-23
│ │ ┌─ day of month 1-31
│ │ │ ┌─ month 1-12
│ │ │ │ ┌─ day of week 0-6 (0 = Sunday)
│ │ │ │ │
30 4 * * 1-5 04:30 Monday to Friday
*/15 * * * * every 15 minutes
0 */4 * * * every 4 hours, on the hour
0 9 1 * * 09:00 on the 1st of every month
0 22 * * 6 22:00 every Saturday
# Day-of-month AND day-of-week are OR-ed when both are restricted:
# "0 0 13 * 5" = the 13th of the month, AND every Friday.A DAG timezone comes from start_date. Pass a timezone-aware datetime (pendulum.datetime(2026, 1, 1, tz="Asia/Kolkata")) or your cron runs in UTC no matter what the server clock says.
Data intervals — the thing everyone gets wrong
A run is named after the interval of data it covers, and executes once that interval has closed.
data_interval_start 2026-03-01 00:00 <- logical_date, {{ ds }} = 2026-03-01
data_interval_end 2026-03-02 00:00
run actually starts 2026-03-02 00:00 + scheduler latency
So on the morning of March 2nd, the newest completed run is labelled
March 1st. That is correct, not a lag: March 1st's data was only whole
at midnight.
Consequences:
* Write partitions with {{ ds }}, never with datetime.now().
* A sensor waiting for a March 1st file should run in the March 1st
DAG run, which starts on March 2nd. Waiting for "today" is a bug.
* "Where is today's run?" -> it appears tomorrow. If you need the run
to fire at the START of the period, use CronTriggerTimetable.| Concept | Meaning |
|---|---|
| logical_date | The timestamp identifying the run. Equals data_interval_start for cron-based schedules. Formerly, and still colloquially, "execution date". |
| data_interval_start / _end | The half-open window [start, end) of data the run covers. These are what you should filter on. |
| catchup | When true, Airflow creates every missed run between start_date and now on unpause. When false, only the most recent interval is scheduled. |
| max_active_runs | How many runs of this DAG may execute concurrently. Set to 1 when the DAG writes to a shared target and backfills must be sequential. |
| depends_on_past | A task instance waits for the same task in the previous run to succeed. Powerful for incremental state; deadlocks a backfill the moment one old run fails. |
| start_date | The beginning of the first data interval. Must be static — a dynamic value like datetime.now() moves every time the file is parsed and the DAG may never trigger. |
| end_date | Optional last interval. Cleaner than deleting a DAG when a pipeline is being retired. |
Unpausing a DAG with catchup=True and a start_date two years in the past will immediately queue several hundred runs. Set catchup=False while developing, and add max_active_runs before you ever set it back to True.
Template variables and macros
Jinja templating works in templated fields only — bash_command, sql, op_kwargs, most operator string arguments, and anything listed in an operator’s template_fields.
| Variable | Value |
|---|---|
| {{ ds }} | Logical date as YYYY-MM-DD. The single most-used variable. |
| {{ ds_nodash }} | YYYYMMDD — for Hive-style partition paths and S3 prefixes. |
| {{ ts }} | Logical date as an ISO 8601 timestamp with timezone. |
| {{ ts_nodash_with_tz }} / {{ ts_nodash }} | Compact timestamp forms for filenames. |
| {{ data_interval_start }} / {{ data_interval_end }} | Pendulum datetimes for the run window. Prefer these over ds when you need a real timestamp comparison. |
| {{ prev_data_interval_start_success }} | Start of the last *successful* run’s interval. Useful for "everything since we last worked" incremental loads. |
| {{ dag }} / {{ dag_run }} / {{ task }} / {{ ti }} | The objects themselves — e.g. {{ dag_run.conf["region"] }} reads config passed at trigger time. |
| {{ run_id }} | Identifier of the run, e.g. scheduled__2026-03-01T00:00:00+00:00. |
| {{ params.x }} | Values from the DAG’s params, overridable in the trigger form. |
| {{ var.value.my_key }} | An Airflow Variable. Every reference is a metadata-DB read at render time. |
| {{ var.json.my_key.field }} | A JSON Variable, parsed. Store one JSON blob rather than ten variables to cut DB hits. |
| {{ conn.my_conn_id.host }} | Fields of a Connection — host, login, password, schema, port, extra. |
| {{ macros.ds_add(ds, -7) }} | Date arithmetic on a YYYY-MM-DD string. |
| {{ macros.datetime }} / {{ macros.timedelta }} / {{ macros.uuid }} | The standard library modules, exposed inside templates. |
run_etl = BashOperator(
task_id="run_etl",
bash_command=(
"spark-submit /opt/jobs/etl.py "
"--start {{ data_interval_start }} "
"--end {{ data_interval_end }} "
"--out s3://lake/orders/dt={{ ds }}/"
),
)
load = SQLExecuteQueryOperator(
task_id="load",
conn_id="redshift",
sql="""
DELETE FROM orders WHERE order_date = '{{ ds }}';
COPY orders FROM 's3://lake/orders/dt={{ ds_nodash }}/'
IAM_ROLE '{{ var.value.redshift_role }}' FORMAT AS PARQUET;
""",
)Templates render at task execution time, not at parse time. A Jinja string sitting in a plain Python variable is never rendered — it only works inside a templated field of an operator.
TaskFlow and operator patterns
from __future__ import annotations
import pendulum
from airflow.decorators import dag, task, task_group
@dag(
dag_id="orders_daily",
schedule="0 2 * * *",
start_date=pendulum.datetime(2026, 1, 1, tz="Asia/Kolkata"),
catchup=False,
max_active_runs=1,
default_args={"retries": 2, "retry_delay": pendulum.duration(minutes=5)},
tags=["orders", "daily"],
doc_md="Loads yesterday's orders into the warehouse.",
)
def orders_daily():
@task
def extract(data_interval_start=None, data_interval_end=None) -> list[str]:
# Airflow injects context keys by name — no **kwargs juggling needed.
return list_keys(start=data_interval_start, end=data_interval_end)
@task
def transform(key: str) -> dict:
return {"key": key, "rows": load_and_clean(key)}
@task
def load(results: list[dict]) -> None:
write_to_warehouse(results)
# Dynamic task mapping: one transform task per key, decided at runtime.
load(transform.expand(key=extract()))
orders_daily()| Decorator / pattern | Use |
|---|---|
| @task | Turns a function into a task. The return value becomes an XCom; arguments become dependencies automatically. |
| @task.branch | Return the task_id (or list of ids) to follow. Everything else downstream is skipped. |
| @task.short_circuit | Return False to skip everything downstream. The clean way to say "nothing to do today". |
| @task.virtualenv / @task.external_python | Run the function in an isolated interpreter with its own dependencies — the escape hatch for library conflicts with Airflow itself. |
| @task.docker / @task.kubernetes | Run the function inside a container image. |
| @task.sensor | Turn a function returning a truthy value (or a PokeReturnValue) into a sensor. |
| @task_group | Group tasks into a collapsible unit in the UI. Replaced SubDAGs, which were removed. |
| .expand(x=[...]) | Dynamic task mapping: one task instance per element, expanded at run time. |
| .partial(y=1).expand(x=[...]) | Fix some arguments, map over the rest. |
| .expand_kwargs([{...}, {...}]) | Map over full keyword dicts when several arguments vary together. |
| chain(a, b, c) / cross_downstream([a,b], [c,d]) | Readable wiring helpers from airflow.models.baseoperator — better than long >> chains. |
| Common operator | Notes |
|---|---|
| EmptyOperator | No-op marker for fan-in and fan-out points. Named DummyOperator before 2.4. |
| BashOperator / PythonOperator | The workhorses. bash_command is templated; a trailing space matters if the command ends in .sh (Jinja treats it as a template file otherwise). |
| SQLExecuteQueryOperator | The generic SQL operator that replaced the per-database ones (PostgresOperator, MySqlOperator and friends). |
| TriggerDagRunOperator | Fires another DAG. Set wait_for_completion=True when the downstream result matters; otherwise it returns immediately. |
| ExternalTaskSensor | Waits for a task in another DAG *for a matching logical date*. Mismatched schedules need execution_delta or execution_date_fn or it waits forever. |
| S3KeySensor / SqlSensor | Poll for an object or a query result. Always set timeout — a sensor without one holds a worker slot indefinitely. |
| SparkSubmitOperator / EmrAddStepsOperator + EmrStepSensor | Submit Spark work to a standalone cluster or to EMR, then wait on the step. |
| DatabricksSubmitRunOperator / DatabricksRunNowOperator | Submit an ephemeral job cluster run, or trigger an existing job. |
| KubernetesPodOperator | Run any image as a pod. The most portable escape hatch when no provider operator exists. |
Use mode="reschedule" on any sensor whose wait is measured in minutes: the task releases its worker slot between pokes instead of holding it. For long waits, prefer a deferrable operator (deferrable=True) so the wait moves to the triggerer process entirely.
Trigger rules
What a task does when its upstream tasks finish in a state other than success.
| Rule | Task runs when |
|---|---|
| all_success | Every direct upstream succeeded. The default. |
| all_failed | Every direct upstream failed or was upstream-failed. Used for failure-handling branches. |
| all_done | Every upstream finished, whatever the outcome. The correct rule for cleanup and teardown tasks. |
| all_skipped | Every upstream was skipped. |
| one_success | At least one upstream succeeded; fires as soon as that happens. |
| one_failed | At least one upstream failed; fires without waiting for the rest. Good for alerting. |
| one_done | At least one upstream succeeded or failed. |
| none_failed | No upstream failed — successes and skips both allowed. |
| none_failed_min_one_success | No upstream failed and at least one succeeded. The rule you want for a join task after a branch. |
| none_skipped | No upstream was skipped. |
| always | Runs unconditionally, ignoring upstream state entirely. |
A branch skips its unchosen paths, and the skip propagates downstream. A join task after a branch therefore needs none_failed_min_one_success — with the default all_success it will be skipped every single run.
CLI commands worth memorising
airflow dags list # every parsed DAG
airflow dags list-import-errors # first stop when a DAG is missing
airflow dags test my_dag 2026-03-01 # run the whole DAG locally, no scheduler
airflow tasks test my_dag my_task 2026-03-01 # one task, no DB state written
airflow tasks list my_dag --tree # structure as parsed
airflow dags trigger my_dag -c '{"region":"sg"}' # manual run with conf
airflow dags pause my_dag / unpause my_dag
airflow dags backfill my_dag -s 2026-03-01 -e 2026-03-07
airflow tasks states-for-dag-run my_dag scheduled__2026-03-01T00:00:00+00:00
airflow tasks clear my_dag -t "load_.*" -s 2026-03-01 -e 2026-03-07 # re-runairflow db migrate # apply schema migrations (was: db upgrade)
airflow db check # can it reach the metadata DB at all
airflow info # versions, providers, paths — attach to bug reports
airflow standalone # local scheduler + webserver + SQLite, one command
airflow dags reserialize # force re-serialisation after an upgrade
airflow connections add my_conn --conn-uri 'postgres://user:pw@host:5432/db'
airflow connections list / export connections.json
airflow variables set my_key my_value ; airflow variables export vars.json
airflow pools set etl_pool 4 "limits concurrent ETL tasks"
airflow providers list # which provider packages are installed| Config knob | Effect |
|---|---|
| core.parallelism | Global cap on running task instances across the whole installation. |
| core.max_active_tasks_per_dag | Default per-DAG task concurrency (was dag_concurrency). |
| core.max_active_runs_per_dag | Default concurrent runs per DAG. |
| core.dagbag_import_timeout | Seconds allowed to import one DAG file before it is abandoned. Raise it if heavy top-level code is timing out — then delete the heavy top-level code. |
| scheduler.min_file_process_interval | Minimum seconds between re-parsing the same DAG file. Raising it reduces scheduler CPU on large deployments. |
| scheduler.parsing_processes | How many files the DAG processor parses in parallel. |
| celery.worker_concurrency | Task slots per Celery worker. |
| Env var form | Any config key can be set as AIRFLOW__SECTION__KEY — e.g. AIRFLOW__CORE__PARALLELISM=64. Double underscores separate section from key. |
Pitfalls
| Trap | Why it hurts | Do this instead |
|---|---|---|
| Top-level code in a DAG file | Everything outside a task body runs on every parse cycle — every 30 seconds, per file, for every scheduler process. A database query there becomes thousands of queries a day. | Move work inside @task functions. Keep imports light; do heavy imports inside the function. |
| Dynamic start_date | datetime.now() or days_ago(1) moves the interval boundary on every parse, so the schedule can never close an interval and the DAG appears stuck. | A fixed, timezone-aware pendulum.datetime(...). |
| datetime.now() inside a task | Re-running or backfilling a run produces different data than the original run did. The pipeline stops being reproducible. | Use data_interval_start / {{ ds }} — every re-run then produces identical output. |
| Large data through XCom | XComs are rows in the metadata database. Pushing a DataFrame bloats the DB and slows the whole scheduler. | Write to object storage and pass the path. Configure a custom XCom backend if you must pass more than kilobytes. |
| Sensors in poke mode for long waits | Each poking sensor occupies a worker slot for its entire wait, so a handful of them can deadlock the pool. | mode="reschedule", or a deferrable operator with the triggerer running. |
| catchup left on by accident | Unpausing floods the scheduler with historical runs and, worse, floods whatever the DAG writes to. | Set catchup=False explicitly, and cap max_active_runs. |
| ExternalTaskSensor across different schedules | It looks for the upstream task at the *same* logical date. Hourly waiting on daily never matches and simply times out. | Set execution_delta or execution_date_fn, or switch to dataset/asset scheduling. |
| Mutable default_args shared between DAGs | A dict defined at module scope and reused is shared state; one DAG mutating it changes the other. | Build default_args inside each DAG factory. |
| Timezone-naive datetimes | Airflow rejects or silently coerces them, and DST boundaries then produce duplicate or missing runs. | Always use pendulum with an explicit tz. |
Moving to Airflow 3
The differences most likely to break an existing 2.x DAG.
schedule_intervaland the separatetimetableargument are gone — everything is passed throughschedule.execution_dateand its derived context keys are removed. Uselogical_date,data_interval_startanddata_interval_end.- Datasets were renamed to Assets, with an
Assetclass and an@assetdecorator; data-aware scheduling itself works the same way. - SubDAGs, deprecated for years in 2.x, are removed. Task groups are the replacement.
- Task code talks to a Task Execution API rather than to the metadata database directly, so workers no longer need database credentials — a real security improvement, and the reason task code should import from the task SDK rather than from Airflow internals.
- The API server serves the UI and REST API together, replacing the standalone webserver process.
- Before upgrading: run the upgrade check tooling for your version, remove every deprecated import, and confirm your provider packages have Airflow 3 compatible releases.
Managed services lag the open-source release. Check which Airflow versions your MWAA, Composer or Astronomer environment offers before planning a migration — the environment version, not the library version, is what constrains you.
Airflow Cheatsheet · https://ctarunsai.github.io/cheatsheets/airflow/ · updated 28 Aug 2026 · Tarun Chitta
About this cheatsheet
Airflow is two things at once: a scheduler with an opinionated model of time, and a Python library for wiring tasks together. Nearly every confusing bug lives in the first half, so this sheet spends most of its space there.
The central idea is the data interval. A DAG run does not represent "now" — it represents the window of data that has just finished being produced. A daily DAG covering 2026-03-01 starts running *after* midnight on 2026-03-02, and {{ ds }} inside it is 2026-03-01, not the date the run started. Once that clicks, the whole off-by-one family of bugs disappears: partitions written to the wrong day, sensors waiting for a file that will not exist for 24 hours, backfills that quietly skip the most recent day.
The rest is patterns. TaskFlow (@dag / @task) removes most PythonOperator boilerplate and makes XCom look like ordinary function arguments; dynamic task mapping with .expand() replaces the loop that used to generate tasks at parse time. Trigger rules decide what happens when an upstream task fails or is skipped, which is where "why did my cleanup task never run" usually ends.
Everything below targets Airflow 2.x, which is what most production installs and managed services such as MWAA and Composer run. The final section lists the changes that matter if you are moving to Airflow 3.