Apache Airflow courseLesson 11 of 11
Apache Airflow course · Lesson 11 of 11
Top 50 Apache Airflow Interview Questions and Answers
Top 50 Apache Airflow 3 interview questions with answers: DAGs, TaskFlow, scheduling, assets, backfills, executors, testing and migration.
On this page
These 50 Airflow interview questions cover DAG parsing, TaskFlow and operators, dependencies and trigger rules, dynamic task mapping, scheduling and assets, backfills, deferrable tasks, executors, testing, CI/CD and Airflow 3 migration. They are grouped from beginner (freshers) to advanced (experienced). Each question has one clear answer in plain words, with an example where it helps and the mistakes interviewers watch for.
Question list
Show all 50 questions
- How does a Python file become a DAG in Airflow 3? Explain parsing and the DAG processor
- TaskFlow API vs classic operators: what does
@taskactually do? - Operators, hooks and providers: how do they fit together?
- Connections and Variables: how should DAGs get credentials and configuration?
- How do you declare task dependencies, and what do
chainandcross_downstreamdo? - What are task groups, and why did they replace SubDAGs?
- How do
partial()andexpand()work in dynamic task mapping, and what is a map index? - How does Jinja templating work in Airflow, and which macros should you know?
- What can you pass to
schedule, and what does each option create? - TriggerDagRunOperator, ExternalTaskSensor or assets: how do you choose for cross-DAG dependencies?
- How do TaskFlow tasks pass values: return values,
multiple_outputsand named XComs? - What are pools, and how do you use them to protect a shared system?
- How do callbacks and notifiers work, and where do they run?
- How do you write DAG integrity tests that catch broken DAGs before merge?
- What do the task instance states mean, and which ones signal a problem?
- What are trigger rules, and which ones do you actually use?
- How does branching work in Airflow, and why is the join task often skipped?
- Short-circuit, branch or
AirflowSkipException: how do you skip work cleanly? - What are setup and teardown tasks, and how are they different from an
all_donecleanup? - Generating many DAGs from config vs dynamic task mapping: when do you use each?
- How do Params work, and how do you trigger a DAG with validated inputs?
CronTriggerTimetablevsCronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?- How do scheduler-managed backfills work in Airflow 3?
- Manual and API-triggered runs in Airflow 3: why can
logical_datebeNone? - How does asset-aware scheduling work, and how do you combine asset conditions?
- What do the
@assetdecorator,MetadataandAssetAliasadd on top of plain asset outlets? - Which sensor settings matter, and how do you write a sensor with
@task.sensor? - How do priority weights and
weight_ruledecide what runs first? - How do you configure retries, backoff, timeouts and the 3.3 retry policies?
- SLAs were removed in Airflow 3. How do Deadline Alerts replace them?
- How do multiple executors work, and how do you route a task to a specific one?
- KubernetesPodOperator vs KubernetesExecutor vs virtualenv tasks: how do you isolate dependencies?
- What are DAG bundles and DAG versioning in Airflow 3?
- How do secrets backends work in Airflow 3, and what is the lookup order?
- How do you test task logic and run a DAG end to end with
dag.test()? - What does a good CI/CD pipeline for Airflow DAGs look like?
- MWAA, Cloud Composer or Astronomer: what are the trade-offs of managed Airflow?
- Why is DAG parsing slow, and how do you keep parse time low?
- How do you map a whole task group, filter inputs and limit fan-out?
- How do
AssetWatcherand event-driven scheduling work? - What is asset partitioning in Airflow 3.2+, and when would you use it?
- How does the triggerer work, and how would you write a deferrable operator?
- How do custom and object-storage XCom backends work?
- How do Airflow’s concurrency limits stack, from
parallelismdown to a single task? - What is the Edge Executor, and when would you use it?
- How do you scale and make the scheduler highly available?
- What are the Task SDK and the Task Execution API, and why do they matter?
- How do you design DAGs so any past interval can be reprocessed safely?
- Walk through migrating a real Airflow 2 deployment to Airflow 3. What breaks first?
- What are zombie tasks (heartbeat timeouts), and how do you debug them?
Beginner Airflow interview questions (freshers)
1. How does a Python file become a DAG in Airflow 3? Explain parsing and the DAG processor
The DAG processor finds the Python files in each DAG bundle and runs them. Every DAG that a file creates is turned into JSON and saved in the metadata database. The scheduler and the API server only ever read that saved copy; they never import your file. Workers load the file again only when they actually run a task. That is why slow top-level code in a DAG file hurts the whole system.
Parsing is a loop, and it never stops:
- Discover. Every
[dag_processor] refresh_interval(300 s by default) the processor lists the files in each configured bundle. It skips paths matched by.airflowignore, which uses glob syntax by default in 3.x (regexp was the 2.x default). In safe mode it only parses files whose text contains both “airflow” and “dag”. - Execute. Child processes (
parsing_processes, default 2) import each file. A file is re-parsed at most everymin_file_process_interval(30 s). Each import is cut off afterdagbag_import_timeout(30 s). - Serialise. Each DAG found is written to the
serialized_dagtable. If the structure changed, a new DAG version is recorded too (see What are DAG bundles and DAG versioning in Airflow 3?). Errors are saved as import errors and shown in the UI. - Schedule. The scheduler builds runs and task instances from the serialised DAG. Workers re-import the file at run time to get the real Python callables.
| Component | Imports your file? |
|---|---|
| DAG processor | Yes, every few seconds |
| Scheduler | No (reads serialised JSON) |
| API server / UI | No |
| Worker | Yes, once per task try |
In Airflow 3 the DAG processor is its own required component, started with airflow dag-processor (see Airflow architecture: scheduler, executor, workers, metadata DB, API server). Because your file runs on every parse, anything at module level, such as API calls or Variable.get, runs again and again (see Why is DAG parsing slow, and how do you keep parse time low?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3
# Layout: dags/orders_daily.py (valid) and dags/broken_dag.py (two tasks named "a")
import time
from airflow.dag_processing.dagbag import DagBag
start = time.perf_counter()
bag = DagBag(dag_folder="dags") # 3.x DagBag no longer takes include_examples
print(f"parsed in {time.perf_counter() - start:.2f}s")
print("dags:", sorted(bag.dag_ids))
for path, err in bag.import_errors.items():
print("import error:", path.split("/")[-1], "->", err.strip().splitlines()[-1])
Common mistakes:
- Thinking the scheduler imports DAG files in Airflow 3. It reads serialised DAGs; the DAG processor does the parsing.
- Thinking a file is parsed once at deploy time. Parsing is continuous.
- Hiding a broken DAG with
.airflowignoreinstead of fixing the import error.
Learn more: Airflow DAG Fundamentals, TaskFlow and Dynamic DAGs
2. TaskFlow API vs classic operators: what does @task actually do?
@task turns a Python function into an operator. Calling that function inside a DAG creates a task and returns a placeholder (an XComArg), not a real value. When you pass the placeholder to another task, Airflow adds the dependency for you and fetches the value through XCom when the task runs. Classic operators are still the best choice for ready-made integrations, and you can mix both styles in one DAG.
In Airflow 3 the authoring imports live in airflow.sdk: dag, task, DAG, TaskGroup, Asset, Variable, BaseOperator and others. Old paths such as airflow.decorators are deprecated.
What @task gives you:
- Implicit dependencies.
load(transform(extract()))buildsextract >> transform >> load. - Implicit XCom. The return value is pushed as
return_value. Arguments that areXComArgs are resolved before the function runs. - Typed, testable functions. The business logic is plain Python, and
.functiongives you the raw callable for unit tests (see How do you test task logic and run a DAG end to end withdag.test()?). - Variants.
@task.bash,@task.branch,@task.short_circuit,@task.sensor,@task.virtualenv,@task.docker,@task.kubernetes. Each one wraps the matching operator.
How the two styles talk to each other:
| From | To | How |
|---|---|---|
| Classic operator | TaskFlow | Pass op.output (an XComArg) |
| TaskFlow | Classic | Pass the XComArg into a templated field, or use ti.xcom_pull in Jinja |
| Either | Either | >> / << work on operators and on XComArgs |
Calling a decorated function does not run it. Inside the DAG body, double(3) only adds a task to the DAG. The body runs at parse time; task code runs on a worker.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 (apache-airflow-providers-standard)
from datetime import datetime
from airflow.sdk import dag, task
from airflow.providers.standard.operators.bash import BashOperator
from airflow.providers.standard.operators.python import PythonOperator
def _count_rows(**context):
# classic style: return value is pushed to XCom as "return_value"
return 3
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def mixed_styles():
count = PythonOperator(task_id="count_rows", python_callable=_count_rows)
@task
def double(n: int) -> int: # TaskFlow: args are pulled from XCom for you
return n * 2
notify = BashOperator(
task_id="notify",
bash_command="echo doubled={{ ti.xcom_pull(task_ids='double') }}",
)
doubled = double(count.output) # .output is an XComArg for the classic task
doubled >> notify # XComArg works with >> as well
dag_obj = mixed_styles()
if __name__ == "__main__":
print(dag_obj.test().state)
Common mistakes:
- Expecting
result = extract()to hold real data inside the DAG body. - Returning a large DataFrame from
@task. Return values become XComs (see What are XComs, and what are their limits?, How do TaskFlow tasks pass values: return values,multiple_outputsand named XComs?). - Wrapping
PythonOperatoraround a provider hook when a provider operator already exists.
Learn more: Airflow DAG Fundamentals, TaskFlow and Dynamic DAGs
3. Operators, hooks and providers: how do they fit together?
A hook knows how to talk to an outside system. It reads an Airflow connection and gives back a logged-in client. An operator defines what one task does, and usually calls a hook inside its execute() method. Providers are separate pip packages, each with its own version, that ship the hooks, operators, sensors, triggers and connection types for one system, such as AWS or Snowflake.
| Layer | Responsibility | Example |
|---|---|---|
| Connection | Credentials and endpoint, stored outside code | snowflake_default |
| Hook | Turns a connection into a client; reusable | S3Hook, PostgresHook |
| Operator | A unit of work with parameters, templated fields and retries | S3CopyObjectOperator |
| Sensor / Trigger | Waits for a condition (see Which sensor settings matter, and how do you write a sensor with @task.sensor?, How does the triggerer work, and how would you write a deferrable operator?) |
S3KeySensor |
| Provider | Package that bundles all of the above | apache-airflow-providers-amazon |
Key points:
- Even “core” operators sit in providers in Airflow 3.
BashOperator,PythonOperatorandEmptyOperatorlive inapache-airflow-providers-standard, so import them fromairflow.providers.standard.... - Providers are released on their own schedule. Pin them in a constraints file, so an upgrade happens on purpose and a rebuild does not change them silently.
- A custom operator subclasses
BaseOperatorand implementsexecute(context). Usetemplate_fieldsto choose which attributes Jinja renders. The constructor runs at parse time, so keep it cheap and do I/O only inexecute. - Write a hook when several operators or tasks need the same client logic. Write an operator when a team repeats the same task shape. A plain
@taskthat calls the hook is often enough.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
import json
import os
from datetime import datetime, timezone
from airflow.sdk import BaseHook, BaseOperator, dag
# A connection defined as an environment variable (JSON form); in production it
# would live in a secrets backend. The conn_id is the part after AIRFLOW_CONN_.
os.environ["AIRFLOW_CONN_INVENTORY_API"] = json.dumps(
{"conn_type": "http", "host": "inventory.internal", "login": "svc", "password": "s3cret",
"extra": {"page_size": 500}}
)
class InventoryHook(BaseHook):
"""Hook: knows HOW to talk to the system. Reusable by many operators."""
def __init__(self, conn_id: str = "inventory_api"):
super().__init__()
self.conn_id = conn_id
def get_client_config(self) -> dict:
conn = self.get_connection(self.conn_id)
return {"base_url": f"https://{conn.host}", "user": conn.login,
"page_size": conn.extra_dejson.get("page_size", 100)}
class InventorySnapshotOperator(BaseOperator):
"""Operator: WHAT one task does, using the hook."""
template_fields = ("snapshot_date",)
def __init__(self, snapshot_date: str, conn_id: str = "inventory_api", **kwargs):
super().__init__(**kwargs)
self.snapshot_date = snapshot_date
self.conn_id = conn_id
def execute(self, context):
cfg = InventoryHook(self.conn_id).get_client_config()
print(f"GET {cfg['base_url']}/snapshot?date={self.snapshot_date} "
f"as {cfg['user']} page_size={cfg['page_size']}")
return {"date": self.snapshot_date, "rows": 1200}
@dag(schedule="@daily", start_date=datetime(2026, 1, 1), catchup=False)
def inventory_snapshot():
InventorySnapshotOperator(task_id="snapshot", snapshot_date="{{ ds }}")
dag_obj = inventory_snapshot()
if __name__ == "__main__":
print(dag_obj.test(logical_date=datetime(2026, 3, 1, tzinfo=timezone.utc)).state)
Common mistakes:
- Opening network connections in an operator’s
__init__, which runs at every parse. - Hard-coding credentials in the operator instead of using a
conn_id. - Saying “Airflow processes the data”. Hooks and operators usually tell another system to do the work.
Learn more: Airflow Operators, Hooks, Providers, Branching and Trigger Rules
4. Connections and Variables: how should DAGs get credentials and configuration?
A Connection stores how to reach a system: its type, host, login, password, port and extra JSON settings. Code looks it up by conn_id. A Variable is a simple key and value setting. Both can come from a secrets backend, from environment variables (AIRFLOW_CONN_*, AIRFLOW_VAR_*) or from the metadata database. Read them inside tasks or templates, never in the top-level DAG code, which runs on every parse.
Lookup order: the secrets backend first, if one is configured (see How do secrets backends work in Airflow 3, and what is the lookup order?), then environment variables, then the metadata database. Each environment gets its own values under the same IDs, so one DAG file works in dev, staging and prod.
Ways to read them:
| Where | Syntax | When it runs |
|---|---|---|
| Task code | Variable.get("k", deserialize_json=True, default=...) |
Task run time |
| Hook | self.get_connection(conn_id) |
Task run time |
| Jinja | {{ var.value.k }}, {{ var.json.k.field }}, {{ conn.my_id.host }} |
Rendered just before execute |
| Module top level | Variable.get(...) outside a task |
Every parse: avoid |
In Airflow 3, task code can no longer query the metadata DB. Variable.get and get_connection in a task go through the Task Execution API (see What are the Task SDK and the Task Execution API, and why do they matter?), or through a secrets backend configured for workers.
Good practice:
- Keep secrets in a secrets backend and plain settings in Variables or code. Don’t store one huge JSON Variable that every DAG reads.
- Values of connection passwords and of Variables whose names contain words like
password,secretortokenare masked in task logs. Treat masking as a safety net, not a design. - Use one
conn_idnaming convention across environments, for examplewarehouseeverywhere, with different values.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
# In real deployments these come from a secrets backend or the UI; env vars keep the demo self-contained.
import os
from datetime import datetime
from airflow.sdk import Variable, dag, task
from airflow.providers.standard.operators.bash import BashOperator
os.environ["AIRFLOW_VAR_EXPORT_CONFIG"] = '{"region": "eu-west-1", "batch_size": 5000}'
os.environ["AIRFLOW_CONN_WAREHOUSE"] = "postgres://etl_user:pa55word@wh.internal:5432/analytics"
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def config_demo():
@task
def read_config():
# Read inside the task (at run time), never at module top level.
cfg = Variable.get("export_config", deserialize_json=True)
missing = Variable.get("not_set_yet", default="fallback")
print("batch_size:", cfg["batch_size"], "| missing:", missing)
show = BashOperator(
task_id="templated",
bash_command=(
"echo region={{ var.json.export_config.region }} "
"host={{ conn.warehouse.host }} schema={{ conn.warehouse.schema }}"
),
)
read_config() >> show
dag_obj = config_demo()
if __name__ == "__main__":
print(dag_obj.test().state)
Common mistakes:
- Calling
Variable.getat module level. That is a lookup on every parse, for every file. - Putting passwords in Variables or DAG code instead of connections or a secrets backend.
- Editing connections in the UI when they actually come from a secrets backend. The UI shows only DB-stored values.
Learn more: Airflow XCom, Variables, Connections and Secrets
5. How do you declare task dependencies, and what do chain and cross_downstream do?
Write a >> b (or b << a), or pass a TaskFlow task’s output into another task, which sets the order for you. chain() links tasks in a sequence; given two lists of the same length, it pairs them one to one. cross_downstream() connects every task in one list to every task in another list. Label only puts a name on an arrow in the UI; it does not change anything.
| Pattern | Code | Edges |
|---|---|---|
| Linear | a >> b >> c |
a→b, b→c |
| Fan-out / fan-in | a >> [b, c] >> d |
a→b, a→c, b→d, c→d |
| Pairwise | chain(a, [b1, b2], [c1, c2]) |
a→b1, a→b2, b1→c1, b2→c2 |
| All-to-all | cross_downstream([b1, b2], [c1, c2]) |
4 edges |
| Linear between lists | chain_linear([a, b], [c, d]) |
Each task in a list links to every task in the next list |
Rules interviewers check:
[b, c] >> [d, e]is aTypeError, because Python cannot shift a list by a list. Usecross_downstreamorchain_linear.- Dependencies only order tasks. Whether a downstream task runs depends on its trigger rule (see What are trigger rules, and which ones do you actually use?).
- Dependencies cannot cross DAGs. For that, use assets,
TriggerDagRunOperatororExternalTaskSensor(see TriggerDagRunOperator, ExternalTaskSensor or assets: how do you choose for cross-DAG dependencies?). - A cycle is caught at parse time and becomes an import error.
setupandteardowntasks add a special kind of relationship (see What are setup and teardown tasks, and how are they different from anall_donecleanup?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import DAG, Label, chain, cross_downstream
from airflow.providers.standard.operators.empty import EmptyOperator
with DAG("deps_demo", schedule=None, start_date=datetime(2026, 1, 1), catchup=False) as dag:
start, end = EmptyOperator(task_id="start"), EmptyOperator(task_id="end")
extract = [EmptyOperator(task_id=f"extract_{s}") for s in ("crm", "erp")]
clean = [EmptyOperator(task_id=f"clean_{s}") for s in ("crm", "erp")]
checks = [EmptyOperator(task_id=f"check_{c}") for c in ("rows", "nulls")]
publish = EmptyOperator(task_id="publish")
# chain() with equal-length lists pairs them element-wise: extract_crm >> clean_crm, ...
chain(start, extract, clean)
# cross_downstream: every clean task feeds every check task (2 x 2 edges)
cross_downstream(clean, checks)
# >> with a list fans in; Label only annotates the edge in the UI
checks >> Label("all checks passed") >> publish >> end
if __name__ == "__main__":
for t in sorted(dag.tasks, key=lambda t: t.task_id):
print(f"{t.task_id:12} -> {sorted(t.downstream_task_ids)}")
Common mistakes:
- Writing
[a, b] >> [c, d]and being surprised by the error. - Expecting
chain(a, [b1, b2], [c1, c2, c3])to work. Adjacent lists must be the same length. - Adding edges “just in case”. Every extra edge serialises work that could run in parallel.
6. What are task groups, and why did they replace SubDAGs?
A task group is a box in the UI that folds related tasks together and adds a prefix to their ids, such as ingest_crm.load. It does not change scheduling at all: the tasks stay in the same DAG and use the same executor and limits. SubDAGs used to run a separate DAG, which caused scheduling problems and deadlocks. They were removed in Airflow 3.0, and task groups replace them.
What task groups give you:
- Reuse. A
@task_groupfunction is a template. Call it once per source with.override(group_id=...)to stamp out identical pipelines. - Group-level
default_args. For example, give everything in the ingest groupretries=2. - Dependencies on the whole group.
group_a >> group_bconnects group_a’s leaf tasks to group_b’s root tasks. - Readable graphs. Fifty tasks become five boxes.
- Mapping. A task group can be mapped with
expand()to repeat a whole sub-pipeline per input (see How do you map a whole task group, filter inputs and limit fan-out?).
What they don’t do:
- They add no separate concurrency limit or pool. Use pools (see What are pools, and how do you use them to protect a shared system?) or
max_active_tis_per_dagrun. - They don’t isolate failures. A failure inside a group propagates like any other.
prefix_group_id=Falseremoves the prefix, but then task_ids must be unique across the whole DAG.
SubDAGs versus task groups:
| SubDAG (removed in 3.0) | Task group | |
|---|---|---|
| Scheduling | Separate DAG run | Same DAG run |
| Concurrency issues | Could deadlock the worker slots | None |
| UI | Separate view | Collapsible in the graph |
| Status in 3.x | Gone | Recommended |
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import dag, task, task_group
@task
def extract(source: str) -> str:
return f"s3://raw/{source}/"
@task
def validate(path: str) -> str:
return path
@task
def load(path: str) -> None:
print("loading", path)
@task_group(default_args={"retries": 2}) # group-level defaults apply to its tasks
def ingest(source: str):
load(validate(extract(source)))
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def ingest_sources():
@task
def publish():
print("all sources loaded")
groups = [ingest.override(group_id=f"ingest_{s}")(s) for s in ("crm", "billing")]
groups >> publish()
dag_obj = ingest_sources()
if __name__ == "__main__":
print(sorted(dag_obj.task_ids))
print("retries:", dag_obj.get_task("ingest_crm.load").retries)
print("publish upstream:", sorted(dag_obj.get_task("publish").upstream_task_ids))
print(dag_obj.test().state)
Common mistakes:
- Expecting a task group to limit concurrency or retry as a unit.
- Using a short task id in a branch’s return value when the task lives inside a group.
- Calling task groups “SubDAGs” or proposing SubDAGs in Airflow 3.
7. How do partial() and expand() work in dynamic task mapping, and what is a map index?
expand() creates one task copy for each item in a list or dictionary, and that list can come from an earlier task while the DAG runs. partial() sets the arguments that are the same for every copy. Each copy gets a number called map_index (0, 1, 2 and so on). A later task that takes the mapped output receives all the results together, as a list it can loop over.
Mapping happens at run time. The DAG file says “one copy of export per region”, and the scheduler creates the copies after list_regions has pushed its list. The DAG’s shape stays fixed, so parsing stays fast (compare Q531).
The building blocks:
| API | Effect |
|---|---|
.partial(fmt="parquet") |
Constant arguments, plus task settings such as retries or pool |
.expand(region=[...]) |
One instance per element. Several expand arguments give a cross product |
.expand_kwargs([{...}, {...}]) |
One instance per dict: explicit pairs, no cross product |
xcom_arg.zip(other) |
Pair two lists by position before expanding |
map_index_template="{{ ... }}" |
Human-readable label in the UI instead of 0/1/2 |
Behaviour to remember:
- An empty list creates no instances, and the mapped task is marked
skipped. - The downstream “reduce” task gets a
LazySelectSequence. Iterate it or calllist()on it once; don’t index into it over and over. [core] max_map_length(1024 by default) caps the number of instances. Cap concurrency withmax_active_tis_per_dagormax_active_tis_per_dagrun.- Each instance retries, fails and can be cleared on its own. You can rerun index 2 without touching 0 and 1.
- Only arguments that are mapped can vary per instance. Task settings such as
retries,poolandqueuego inpartial()and apply to all instances.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import dag, task
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def mapping_basics():
@task
def list_regions() -> list[str]:
return ["eu", "us", "apac"] # decided at run time, not parse time
# partial(): constant for every copy. expand(): one copy per element.
@task(map_index_template="{{ task.op_kwargs['region'] }}") # nicer UI label than 0/1/2
def export(region: str, fmt: str) -> int:
rows = {"eu": 120, "us": 300, "apac": 80}[region]
print(f"export {region} as {fmt}: {rows} rows")
return rows
@task
def total(counts) -> None: # receives a lazy sequence of all results
print("total rows:", sum(counts))
counts = export.partial(fmt="parquet").expand(region=list_regions())
total(counts)
# expand over two lists = cross product; expand_kwargs = explicit pairs
@task
def copy(src: str, dst: str):
print(f"copy {src} -> {dst}")
copy.expand_kwargs([{"src": "a.csv", "dst": "bronze/a"}, {"src": "b.csv", "dst": "bronze/b"}])
dag_obj = mapping_basics()
if __name__ == "__main__":
run = dag_obj.test()
print(sorted((ti.task_id, ti.map_index, ti.rendered_map_index) for ti in run.get_task_instances()
if ti.map_index >= 0))
print(run.state)
Common mistakes:
- Passing two lists to
expand()and expecting them to be zipped. You get a cross product. - Listing files at parse time to build tasks, which runs on every parse.
- Mapping over 50,000 tiny items. Batch them into chunks first, because every instance carries scheduling overhead.
In depth: How would you process a variable number of files each day in Airflow?
8. How does Jinja templating work in Airflow, and which macros should you know?
Any operator attribute listed in its template_fields is filled in with Jinja on the worker, just before the task runs. You can use the run’s details: ds, data_interval_start, logical_date, run_id, params, var, conn, macros and more. Templates are how one DAG file can process a different date in every run without any change to the code.
- What is templated: only the fields named in
template_fields, such asbash_commandorsql. A string ending in atemplate_extextension like.sqlis loaded as a template file, searched under the DAG folder andtemplate_searchpath. - When: at task run time on the worker. The DAG file only holds the template string, so
{{ ds }}costs nothing at parse time. - TaskFlow: name context keys as function arguments (
ds=None,data_interval_start=None), or callget_current_context(). You don’t need Jinja inside Python.
Context and macros used most:
| Expression | Value |
|---|---|
{{ ds }} / {{ ds_nodash }} |
Logical date as YYYY-MM-DD / YYYYMMDD |
{{ data_interval_start }}, {{ data_interval_end }} |
Pendulum datetimes for the run’s interval |
{{ data_interval_end | ds }} |
Filters format datetimes (ds, ds_nodash, ts) |
{{ macros.ds_add(ds, -7) }} |
Date arithmetic on ds strings |
{{ macros.ds_format(ds, "%Y-%m-%d", "%d/%m/%Y") }} |
Reformat a date string |
{{ params.region }} |
Run parameters (see How do Params work, and how do you trigger a DAG with validated inputs?) |
{{ var.value.k }}, {{ conn.id.host }} |
Variables and connections (see Connections and Variables: how should DAGs get credentials and configuration?) |
Airflow 3 removed the old keys execution_date, next_ds, prev_ds, yesterday_ds and tomorrow_ds. Use logical_date and the data_interval_* keys, plus macros.ds_add when you need date arithmetic. Templates render to strings by default. Set render_template_as_native_obj=True on the DAG, or on a single operator since 3.2, to get Python lists and dicts back.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime, timezone
from airflow.sdk import dag, task
from airflow.providers.standard.operators.bash import BashOperator
def fiscal_quarter(d) -> str: # a custom macro: plain Python
return f"FY{d.year}Q{(d.month - 1) // 3 + 1}"
@dag(
schedule="0 6 * * *",
start_date=datetime(2026, 1, 1),
catchup=False,
user_defined_macros={"fiscal_quarter": fiscal_quarter},
)
def templating_demo():
BashOperator(
task_id="export",
# Rendered on the worker just before execute(); the DAG file only holds the string.
bash_command=(
"echo ds={{ ds }} "
"start={{ data_interval_start | ds }} "
"week_ago={{ macros.ds_add(ds, -7) }} "
"compact={{ ds_nodash }} "
"fq={{ fiscal_quarter(data_interval_start) }} "
"run={{ run_id }}"
),
)
@task
def show_context(ds=None, data_interval_start=None, data_interval_end=None):
# TaskFlow: name the context keys you need as arguments
print("ds:", ds, "| interval:", data_interval_start, "->", data_interval_end)
@task
def removed_keys(**context):
print("has yesterday_ds:", "yesterday_ds" in context, "| has execution_date:", "execution_date" in context)
show_context() >> removed_keys()
dag_obj = templating_demo()
if __name__ == "__main__":
print(dag_obj.test(logical_date=datetime(2026, 5, 20, 6, tzinfo=timezone.utc)).state)
The interval has zero length because a cron string in Airflow 3 uses CronTriggerTimetable by default (see CronTriggerTimetable vs CronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?).
Common mistakes:
- Using
{{ ds }}in a field that isn’t intemplate_fields, which leaves the literal braces in the output. - Building dates with
datetime.now()in Python instead of using the run’s interval. - Using removed 2.x keys such as
execution_dateoryesterday_dsin Airflow 3.
9. What can you pass to schedule, and what does each option create?
schedule accepts None (only manual or API runs), a cron string or preset such as "@daily", a timedelta, "@once", "@continuous", one or more assets, or a timetable object. Airflow turns each of these into a timetable. In Airflow 3, a cron string runs at the cron time by default (CronTriggerTimetable), instead of waiting until an interval has ended as Airflow 2 did.
| Value | Timetable created (3.3) | Runs |
|---|---|---|
None |
NullTimetable |
Only when triggered |
"0 2 * * *", "@daily", "@hourly", "@weekly", "@monthly", "@quarterly", "@yearly" |
CronTriggerTimetable |
At each cron tick |
timedelta(hours=4) |
DeltaTriggerTimetable |
Every 4 h from start_date |
"@once" |
OnceTimetable |
One run |
"@continuous" |
ContinuousTimetable |
A new run as soon as the last one ends (needs max_active_runs=1) |
[asset], a & b, a | b |
AssetTriggeredTimetable |
When assets update (see How does asset-aware scheduling work, and how do you combine asset conditions?) |
AssetOrTimeSchedule(...) |
Itself | On a timer or on asset updates |
Custom Timetable subclass |
Itself | Your own rules (see CronTriggerTimetable vs CronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?) |
Other settings that shape scheduling:
start_dateis the earliest date that can be scheduled. Use a fixed, timezone-aware date, neverdatetime.now(). Its timezone, or the default timezone (UTC), sets the cron’s timezone, so"0 6 * * *"with aEurope/Londonstart date follows daylight-saving changes.catchupisFalseby default in Airflow 3 ([scheduler] catchup_by_default). WithTrue, Airflow creates every missed run sincestart_date(see Airflow catchup, backfill, start_date and logical date).end_datestops scheduling after a date.max_active_runslimits concurrent runs of the DAG (see How do Airflow’s concurrency limits stack, fromparallelismdown to a single task?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime, timedelta
from airflow.sdk import DAG, Asset
schedules = {
"None (manual/API only)": None,
'"@daily" preset': "@daily",
'"15 2 * * 1-5" cron': "15 2 * * 1-5",
"timedelta(hours=4)": timedelta(hours=4),
'"@once"': "@once",
'"@continuous"': "@continuous",
"[Asset(...)]": [Asset("s3://lake/orders/")],
}
for label, sched in schedules.items():
kwargs = {"max_active_runs": 1} if sched == "@continuous" else {}
d = DAG(f"d{abs(hash(label))}", schedule=sched, start_date=datetime(2026, 1, 1), **kwargs)
print(f"{label:24} -> {type(d.timetable).__name__}")
Common mistakes:
- Using
start_date=datetime.now(). The start date moves on every parse and runs never begin. - Using
schedule_intervalortimetable=, which were removed in Airflow 3. Useschedule. - Expecting
"@daily"in Airflow 3 to run at midnight for “yesterday” with a one-day data interval. That is the oldCronDataIntervalTimetablebehaviour (seeCronTriggerTimetablevsCronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?).
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
10. TriggerDagRunOperator, ExternalTaskSensor or assets: how do you choose for cross-DAG dependencies?
Use assets when “run after that data is updated” is enough; the producer does not need to know who uses the data. Use TriggerDagRunOperator when the producer must start one specific DAG and pass it settings. Use ExternalTaskSensor only when two DAGs keep their own schedules and one must wait for a specific task in the other, and then make sure the schedules line up.
| Need | Best fit | Watch out for |
|---|---|---|
| Many consumers react to one dataset | Assets (see How does asset-aware scheduling work, and how do you combine asset conditions?) | Events mean “task succeeded”, not “data valid” |
| Producer passes run parameters | TriggerDagRunOperator(conf=...) |
Producer and target are tightly coupled; target validates params |
| Wait for the other DAG to finish too | TriggerDagRunOperator(wait_for_completion=True, deferrable=True) |
Without deferrable, it holds a worker slot while it waits |
| Two scheduled DAGs, one task depends on another’s | ExternalTaskSensor |
Logical dates must match; use execution_delta or execution_date_fn |
| Clear downstream when upstream is cleared | ExternalTaskMarker |
Needs a matching ExternalTaskSensor |
ExternalTaskSensor looks for the same logical date in the other DAG unless you shift it. A 03:00 DAG waiting on a 02:00 DAG needs execution_delta=timedelta(hours=1). If you get this wrong, the sensor waits until it times out. Run it with mode="reschedule" or deferrable=True, and always set timeout (see Which sensor settings matter, and how do you write a sensor with @task.sensor?). In Airflow 3, logical dates can be None for manual and asset-triggered runs (see Manual and API-triggered runs in Airflow 3: why can logical_date be None?), which makes date-matching sensors even more fragile. That is one more reason to prefer assets.
In Airflow 3, these operators live in apache-airflow-providers-standard. A run created by TriggerDagRunOperator shows up with its own run type, so you can tell it apart from manual runs.
For a longer walk-through, see the site’s guide on making one Airflow DAG depend on another.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 (apache-airflow-providers-standard)
from datetime import datetime, timedelta
from airflow.sdk import dag, task
from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.providers.standard.sensors.external_task import ExternalTaskSensor
@dag(schedule="0 2 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def load_sales():
@task
def load() -> int:
return 1834
# Push: the producer names its downstream and hands over parameters.
load() >> TriggerDagRunOperator(
task_id="trigger_finance_report",
trigger_dag_id="finance_report",
conf={"source": "load_sales", "rows": "{{ ti.xcom_pull(task_ids='load') }}"},
wait_for_completion=False,
)
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def finance_report():
@task
def build(params=None, dag_run=None):
print("triggered with conf:", dag_run.conf)
build()
# Pull: a DAG on its own schedule waits for a task in another DAG.
@dag(schedule="0 3 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def marketing_mart():
ExternalTaskSensor(
task_id="wait_for_sales_load",
external_dag_id="load_sales",
external_task_id="load",
execution_delta=timedelta(hours=1), # 03:00 run looks for the 02:00 run
mode="reschedule", poke_interval=300, timeout=3 * 3600,
)
producer, consumer, sensor_dag = load_sales(), finance_report(), marketing_mart()
if __name__ == "__main__":
print("producer:", producer.test().state)
from airflow.models.dagrun import DagRun
for dr in DagRun.find(dag_id="finance_report"):
print("finance_report run:", dr.run_type, dr.state, dr.conf)
The triggered run waits in queued because no scheduler is running in this local test. rows arrives as a string because templates render to strings (see How does Jinja templating work in Airflow, and which macros should you know?).
Common mistakes:
- An
ExternalTaskSensorbetween DAGs on different schedules with noexecution_delta. - Chains of
TriggerDagRunOperator(wait_for_completion=True)without deferrable mode, which tie up worker slots. - Building a web of cross-DAG links that should have been one DAG or task groups.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
In depth: How do you make one Airflow DAG depend on another?
11. How do TaskFlow tasks pass values: return values, multiple_outputs and named XComs?
A TaskFlow task’s return value is saved as the return_value XCom, and passing it to another task also creates the dependency. With multiple_outputs=True, or a dictionary return type, each key is also saved as its own XCom, so result["key"] passes just one part. For named values and classic operators, you can still use ti.xcom_push and ti.xcom_pull.
| Need | How |
|---|---|
| Pass the whole result | b(a()) |
| Pass one field of a dict result | meta = a(); b(meta["path"]), with multiple_outputs on |
| A value under a custom key | ti.xcom_push(key="published_path", value=...) |
| Read from a classic operator | op.output, or op.output["key"] |
| Read in Jinja | {{ ti.xcom_pull(task_ids='a', key='rows') }} |
| Read one mapped instance | ti.xcom_pull(task_ids="a", map_indexes=2) |
Things to remember:
multiple_outputsis inferred from adictorTypedDictreturn annotation. Passmultiple_outputs=Falseto stop it.- Values must be serialisable. Primitives, lists, dicts, dataclasses and a few library types work through Airflow’s serde. Pickling is not the default.
- XComs belong to one DAG run and one try. Clearing a task deletes its XComs, so downstream tasks must not expect old values.
- Return pointers (paths, table names, counts, ids), not data (see What are XComs, and what are their limits?, How do custom and object-storage XCom backends work?).
do_xcom_push=Falseon classic operators stops them from pushing anything, for example a huge stdout from a Bash command.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import dag, task
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def passing_data():
@task(multiple_outputs=True) # also inferred from a dict / TypedDict return annotation
def extract() -> dict:
# Return a pointer to the data, not the data itself
return {"path": "s3://lake/raw/orders/2026-05-20.parquet", "rows": 1834}
@task
def validate(path: str, rows: int) -> str:
if rows == 0:
raise ValueError("empty extract")
return path
@task
def publish(path: str, ti=None):
ti.xcom_push(key="published_path", value=path) # an extra, named XCom
print("published", path)
@task
def audit(ti=None):
# Pull by task id and key; TaskFlow wiring would be nicer, this shows the raw API
print("audit saw:", ti.xcom_pull(task_ids="publish", key="published_path"),
"| rows key:", ti.xcom_pull(task_ids="extract", key="rows"))
meta = extract()
publish(validate(meta["path"], meta["rows"])) >> audit() # meta["path"] -> XComArg for one key
dag_obj = passing_data()
if __name__ == "__main__":
print(dag_obj.test().state)
Common mistakes:
xcom_pullwith notask_ids, or a misspelt key, which returnsNonewithout an error.- Expecting XComs to survive a clear, or to be shared between DAG runs.
- Returning a DataFrame “because it worked in dev”.
Learn more: Airflow XCom, Variables, Connections and Secrets
12. What are pools, and how do you use them to protect a shared system?
A pool is a named number of slots shared by every DAG. A task that uses the pool takes one slot (or pool_slots slots) while it runs. When the pool is full, other tasks wait in the scheduled state. Use pools to protect a shared system, for example “never more than 4 warehouse rebuilds at the same time”, no matter which DAG starts them.
- Default. Tasks without a pool use
default_pool, which has 128 slots ([core] default_pool_task_slot_count). - Create pools with
airflow pools set NAME SLOTS "description", the REST API, the UI, or your infrastructure code. Pools are deployment state, not DAG code, so manage them like config. - Weighting.
pool_slots=3lets one heavy query count as three light ones. - Deferred tasks don’t use pool slots unless the pool has
include_deferred=True. - Order in a full pool. Higher
priority_weightgoes first (see How do priority weights andweight_ruledecide what runs first?). - Mapping. Every mapped instance takes slots, so a pool is the natural limit for a large fan-out against one system (see How do you map a whole task group, filter inputs and limit fan-out?).
Pools compared with other limits:
| Limit | Scope |
|---|---|
| Pool | Across all DAGs, per resource |
max_active_tis_per_dag / max_active_tis_per_dagrun |
One task (all of its copies) |
max_active_tasks |
One DAG across its runs |
parallelism |
The whole scheduler |
See How do Airflow’s concurrency limits stack, from parallelism down to a single task? for how they combine.
A task that names a pool which doesn’t exist won’t be scheduled. Create pools before deploying the DAGs that use them, and test that every referenced pool exists in CI (see What does a good CI/CD pipeline for Airflow DAGs look like?).
Example
# Runtime: Apache Airflow 3.3 CLI
airflow pools set warehouse_heavy 4 "Big warehouse queries" --include-deferred
airflow pools list
Common mistakes:
- Using pools as a per-DAG throttle when
max_active_tasksormax_active_runsis meant for that. - Long poke-mode sensors in a small pool, which starve the real work.
- Referencing a pool in code that was never created in production.
13. How do callbacks and notifiers work, and where do they run?
Tasks accept callbacks for when they start, succeed, fail, retry or are skipped. DAGs accept success and failure callbacks. Each callback can be a function, a list of functions, or a notifier: a reusable class with templated fields, such as the Slack, email or PagerDuty notifiers from providers. Task callbacks run where the task ran. DAG callbacks are run by the DAG processor, so look for their errors in its logs.
| Callback | Fires when | Level |
|---|---|---|
on_execute_callback |
Just before the task executes | Task |
on_success_callback |
Task or run succeeded | Task, DAG |
on_failure_callback |
Task failed for good, or run failed | Task, DAG |
on_retry_callback |
Task failed and will retry | Task |
on_skipped_callback |
Task raised AirflowSkipException while running |
Task |
Behaviour to know:
- Callbacks fire only for state changes caused by running tasks. Marking a task failed or successful in the UI or CLI doesn’t trigger them.
- In 3.0+
on_success_callbackno longer fires for tasks that endskipped. - Put task callbacks in
default_argsto cover every task. Put a DAG-levelon_failure_callbackon the DAG for one alert per run instead of one per task. - Notifiers are reusable classes with
template_fieldsandnotify(context). Prefer provider notifiers, such asSlackNotifierorSmtpNotifier, over hand-written HTTP calls. - A callback must be quick and must not fail. An exception in it is only logged, so the alert is lost.
- For “the run didn’t finish by a certain time”, use Deadline Alerts (see SLAs were removed in Airflow 3. How do Deadline Alerts replace them?). For alerting patterns overall, see the site’s guide on failure handling and alerting.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime, timedelta
from airflow.sdk import BaseNotifier, dag, task
class ChatNotifier(BaseNotifier):
"""Reusable alert: template_fields are rendered with the task's context, like an operator."""
template_fields = ("message",)
def __init__(self, message: str, channel: str = "#data-alerts"):
super().__init__()
self.message, self.channel = message, channel
def notify(self, context):
# real version: post to Slack/Teams via a provider hook or notifier
print(f"to {self.channel}: {self.message}")
def log_retry(context): # plain-function callbacks work too
ti = context["ti"]
print(f"retrying {ti.task_id}, try {ti.try_number}")
@dag(
schedule=None, start_date=datetime(2026, 1, 1), catchup=False,
on_failure_callback=ChatNotifier("DAG {{ dag.dag_id }} run {{ run_id }} FAILED"),
default_args={
"retries": 1, "retry_delay": timedelta(seconds=1),
"on_retry_callback": log_retry,
"on_failure_callback": ChatNotifier("task {{ ti.task_id }} failed after {{ ti.try_number }} tries"),
},
)
def alerting_demo():
@task
def load():
raise RuntimeError("warehouse unavailable")
load()
dag_obj = alerting_demo()
if __name__ == "__main__":
print(dag_obj.test().state)
In this local dag.test() run only the task-level callbacks printed. In a deployment, the DAG-level on_failure_callback is run by the DAG processor once the run fails.
Common mistakes:
- Expecting callbacks to fire after marking a task failed in the UI.
- Doing heavy work, such as queries or retries, inside a callback.
- Hard-coding webhook URLs in DAG code instead of keeping them in a connection.
In depth: How do you handle task failures and alerting in Airflow?
14. How do you write DAG integrity tests that catch broken DAGs before merge?
In pytest, load your DAG folder with DagBag and fail the test if there are any import_errors. That catches syntax errors, missing imports, duplicate task ids, cycles and wrong arguments. Then check your team’s rules on each DAG, such as tags, owners, retries and allowed pools, and set a limit on parse time. These tests run in seconds and catch most problems before they appear as errors in production.
What a DagBag load catches, because it runs the same import the DAG processor runs:
- Python errors and missing packages. CI must use the same image or constraints as production.
DuplicateTaskIdFound, cycles, unknown executors (see How do multiple executors work, and how do you route a task to a specific one?), invalidschedulevalues and failed param defaults.- Removed Airflow 2 APIs, such as
airflow.datasetsorschedule_interval(see Walk through migrating a real Airflow 2 deployment to Airflow 3. What breaks first?).
Convention checks worth adding:
| Check | Why |
|---|---|
| Every DAG has an owner or team tag | Routing alerts, ownership |
retries >= 1 on tasks |
No silent single-attempt failures |
catchup set explicitly |
Avoid surprise backfills when defaults change |
| Pools used ∈ an allowed list | Missing pools mean tasks are never scheduled (see What are pools, and how do you use them to protect a shared system?) |
No Variable.get or network at module level |
Parse cost (see Why is DAG parsing slow, and how do you keep parse time low?); enforce with a lint rule or a parse-time budget |
| Parse time below a budget | Catches heavy top-level code early |
Practical notes:
- In 3.3,
DagBag(dag_folder=...)no longer takesinclude_examples. Example DAGs are separate bundles. - Keep test files outside the DAG folder. A file that mentions “airflow” and “dag” inside the folder gets parsed as a DAG file.
- Use
dag.test()for behaviour and plain unit tests for logic (see How do you test task logic and run a DAG end to end withdag.test()?). Integrity tests only prove that a DAG loads.
Example
# Runtime: Python 3.11, Apache Airflow 3.3, pytest — tests/test_dag_integrity.py, run in CI on every PR
import os
import time
import pytest
from airflow.dag_processing.dagbag import DagBag
DAG_FOLDER = os.path.join(os.path.dirname(__file__), "..", "dags")
@pytest.fixture(scope="session")
def dagbag():
start = time.perf_counter()
bag = DagBag(dag_folder=DAG_FOLDER)
bag.parse_seconds = time.perf_counter() - start
return bag
def test_no_import_errors(dagbag):
assert dagbag.import_errors == {}, f"Import errors: {dagbag.import_errors}"
def test_parse_time_budget(dagbag):
assert dagbag.parse_seconds < 5, f"DAG folder took {dagbag.parse_seconds:.1f}s to parse"
@pytest.mark.parametrize("dag_id", sorted(DagBag(dag_folder=DAG_FOLDER).dag_ids))
def test_dag_conventions(dagbag, dag_id):
dag = dagbag.get_dag(dag_id)
assert any(t.startswith("team:") for t in dag.tags), f"{dag_id}: add a team:<name> tag"
for t in dag.tasks:
assert t.retries >= 1, f"{dag_id}.{t.task_id}: set retries (default_args)"
Common mistakes:
- Running CI in an environment that doesn’t match production, so it passes in CI and breaks in prod.
- Treating “it loads” as “it works”. Pair integrity tests with
dag.test()and unit tests. - Calling real APIs or databases at import time, which makes CI depend on the network.
Learn more: Airflow Best Practices: Idempotent Tasks, Testing and CI/CD
In depth: How do you test Airflow DAGs before they reach production?
15. What do the task instance states mean, and which ones signal a problem?
A task usually moves from no state to scheduled (its dependencies are met), queued (sent to the executor), running, then success or failed, with up_for_retry between tries. Other states record decisions: skipped, upstream_failed, up_for_reschedule (a sensor between checks), deferred (waiting in the triggerer), removed, restarting, and awaiting_input for human approval steps. A task stuck in scheduled or queued points to a capacity or executor problem.
| State | Meaning | Worry when… |
|---|---|---|
| (none) | Created, dependencies not yet met | Upstream finished long ago (check the trigger rule) |
scheduled |
Ready; waiting for a slot | It lasts for minutes: pools, max_active_tasks or parallelism are full (see How do Airflow’s concurrency limits stack, from parallelism down to a single task?) |
queued |
Handed to the executor | It lasts for minutes: workers down, broker problems, pods pending. task_queued_timeout (600 s) eventually fails or retries it |
running |
Executing | Its heartbeat stops (see What are zombie tasks (heartbeat timeouts), and how do you debug them?) or it runs past execution_timeout |
deferred |
Waiting in the triggerer | No triggerer is running, or the triggerer is overloaded |
up_for_reschedule |
Sensor between pokes | Its timeout is very long |
up_for_retry |
Failed, waiting retry_delay |
Many tasks at once: a shared dependency is down |
success / failed |
Final | n/a |
skipped |
Branch, short-circuit or skip exception | Unexpected skips: trigger rules (see What are trigger rules, and which ones do you actually use?) |
upstream_failed |
A parent failed | n/a |
removed |
Task no longer in the DAG version | After deploys that rename tasks |
restarting |
Cleared while running | n/a |
awaiting_input |
Human-in-the-loop task waiting for a person (3.1+) | Nobody is assigned to respond |
DAG runs have only queued, running, success and failed. A run’s final state comes from its leaf tasks (teardowns excepted).
Tools for each state: the task-instance details panel in the UI, which lists unmet dependencies; airflow tasks failed-deps; airflow tasks states-for-dag-run; and the scheduler and executor logs for queued problems. For a full triage of slow or stuck tasks, see the site’s guide.
Example
# Runtime: Apache Airflow 3.3 CLI — inspect the run from the trigger-rule example (see Q524)
airflow dags list-runs trigger_rules_demo -o plain
airflow tasks states-for-dag-run trigger_rules_demo "manual__2026-10-17T13:37:18.923999+00:00"
Common mistakes:
- Treating
scheduledandqueuedas the same thing. They point to different bottlenecks. - Clearing tasks over and over without reading the unmet dependencies.
- Not knowing
deferredneeds a running triggerer.
Intermediate Airflow interview questions
16. What are trigger rules, and which ones do you actually use?
A trigger rule decides when a task may run, based on the states of the tasks directly before it. The default is all_success. The ones you use most are all_done for cleanup that must always run, one_failed for alert tasks, and none_failed_min_one_success for a task that joins the paths after a branch. A trigger rule only looks at the direct parents, not the whole DAG.
The rules in Airflow 3.3’s TriggerRule enum:
| Rule | Runs when direct upstreams… | Typical use |
|---|---|---|
all_success (default) |
all succeeded | Normal flow |
all_failed |
all failed or upstream_failed | Fallback path |
all_done |
all finished, in any state | Cleanup, audit row |
all_done_min_one_success |
all finished and at least one succeeded (3.1+) | Partial-tolerance join |
all_done_setup_success |
all done and a setup succeeded | Used by teardowns (see What are setup and teardown tasks, and how are they different from an all_done cleanup?) |
one_success / one_failed / one_done |
as soon as one does so | Race, early alert |
none_failed |
none failed (skips are fine) | Join after optional work |
none_failed_min_one_success |
none failed and at least one succeeded | Join after a branch (see How does branching work in Airflow, and why is the join task often skipped?) |
none_skipped |
none were skipped | Rare |
all_skipped |
all were skipped | “Nothing happened” handling |
always |
no condition | Use with care |
Two behaviours interviewers probe:
- Propagation. Under
all_success, a failure upstream marks the childupstream_failed, and a skip marks itskipped. Each state cascades down until some task’s rule accepts it. - DAG run state comes from the leaf tasks. If the only leaf is an
all_donecleanup task that succeeds, the run can be marked success even though real work failed. Either keep a work task as a leaf or make the cleanup a teardown, because teardowns are ignored when the run’s state is worked out.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import TriggerRule, dag, task
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def trigger_rules_demo():
@task
def load_eu():
return "ok"
@task
def load_us():
raise ValueError("source file missing")
@task # default all_success: will not run because load_us failed
def build_report():
print("report built")
@task(trigger_rule=TriggerRule.ALL_DONE) # runs whatever happened upstream
def cleanup_tmp():
print("temp files removed")
@task(trigger_rule=TriggerRule.ONE_FAILED) # runs as soon as any upstream fails
def page_on_call():
print("paging on-call")
loads = [load_eu(), load_us()]
loads >> build_report()
loads >> cleanup_tmp()
loads >> page_on_call()
dag_obj = trigger_rules_demo()
if __name__ == "__main__":
run = dag_obj.test()
for ti in sorted(run.get_task_instances(), key=lambda t: t.task_id):
print(f"{ti.task_id:14} {ti.state}")
print("dag run:", run.state)
Common mistakes:
- Leaving the join after a branch on the default rule, so it is always skipped.
- Using
alwaysorall_doneon tasks that need correct upstream data. - Assuming a trigger rule can look at tasks that are not direct parents.
17. How does branching work in Airflow, and why is the join task often skipped?
A branch task (@task.branch or BranchPythonOperator) returns the task id, or list of ids, to follow next. Airflow skips its other direct child tasks. That skip then spreads: a join task with the default all_success rule sees a skipped parent and is skipped too. Give the join task the none_failed_min_one_success rule so it runs after whichever branch was taken.
How it works:
- The branch callable runs and returns
"a",["a", "b"], orNone/[]. Returning nothing skips every direct downstream task. - Every task directly downstream of the branch that was not chosen is set to
skipped. - Each later task applies its own trigger rule to its parents’ states (see What are trigger rules, and which ones do you actually use?).
Variants:
| Need | Tool |
|---|---|
| Choose a path in Python | @task.branch |
| Choose by SQL result | BranchSQLOperator (common-sql provider) |
| Choose by time of day or weekday | BranchDateTimeOperator, BranchDayOfWeekOperator |
| Reusable custom logic | Subclass BaseBranchOperator and implement choose_branch |
| Just stop or continue | @task.short_circuit (see Short-circuit, branch or AirflowSkipException: how do you skip work cleanly?) |
Design rules:
- Branch on run metadata, such as
data_interval_start,paramsor upstream XComs, not ondatetime.now(). A rerun next week must take the same path. - Return task_ids that are direct downstream tasks. Inside a task group, use the full id, such as
"group.task". - Keep the branch cheap. A heavy check belongs in an upstream task whose result the branch reads.
- If the branches build the same output in different ways, think about one task with a parameter instead. Branches add a lot of skipped boxes to the grid.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime, timezone
from airflow.sdk import TriggerRule, dag, task
@dag(schedule="@daily", start_date=datetime(2026, 1, 1), catchup=False)
def branch_by_day():
@task.branch
def choose_load(**context) -> str:
# Branch on run metadata, not on wall-clock time, so reruns pick the same path.
is_month_start = context["data_interval_start"].day == 1
return "full_reload" if is_month_start else "incremental_load"
@task
def full_reload():
print("rebuilding whole table")
@task
def incremental_load():
print("merging one day")
# Without this trigger rule the join would be skipped along with the unchosen branch.
@task(trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS)
def refresh_dashboard():
print("dashboard refreshed")
choose_load() >> [full_reload(), incremental_load()] >> refresh_dashboard()
dag_obj = branch_by_day()
if __name__ == "__main__":
for day in (1, 2):
run = dag_obj.test(logical_date=datetime(2026, 3, day, tzinfo=timezone.utc))
states = {ti.task_id: ti.state for ti in run.get_task_instances()}
print(f"2026-03-0{day}:", dict(sorted(states.items())))
Common mistakes:
- Forgetting the join’s trigger rule, then “fixing” it with
all_done, which also runs after a failure. - Branching on
datetime.now()or on a Variable someone edits, which makes reruns take a different path. - Returning a task_id that is not a direct child of the branch task.
18. Short-circuit, branch or AirflowSkipException: how do you skip work cleanly?
@task.short_circuit stops the downstream tasks when its function returns a false value; it is a simple “continue or stop” gate. A branch chooses between several paths. Raising AirflowSkipException inside a task marks only that one task as skipped. Note that a short-circuit skips all downstream tasks by default and ignores their trigger rules; set ignore_downstream_trigger_rules=False to skip only its direct children.
| Tool | Effect | Use when |
|---|---|---|
@task.short_circuit (default) |
Falsy result → every downstream task skipped, trigger rules ignored | “No new data today, stop here” |
@task.short_circuit(ignore_downstream_trigger_rules=False) |
Direct children skipped; tasks further down apply their own rules | An audit or cleanup task must still run |
@task.branch |
Unchosen direct children skipped | Choosing between paths (see How does branching work in Airflow, and why is the join task often skipped?) |
raise AirflowSkipException(...) |
This task becomes skipped; children follow their rules |
Feature flag, an optional export, a tenant opt-out |
raise AirflowFailException(...) |
Fails at once, with no retries | Bad input that retrying won’t fix |
Points to make:
- A skip is not a failure. A DAG run whose leaves are all
successorskippedcounts as successful. Make sure “no data” really is fine; sometimes it should be an alert instead. - A short-circuit that runs before a sensor saves the waiting time as well as the work.
on_skipped_callbackfires only when a task raisesAirflowSkipExceptionwhile running. It does not fire for tasks skipped by a branch or a trigger rule.- In Airflow 3, import task exceptions from
airflow.sdk.exceptions.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import TriggerRule, dag, task
from airflow.sdk.exceptions import AirflowSkipException
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def short_circuit_demo():
@task
def count_new_rows() -> int:
return 0 # nothing arrived today
# False/falsy return -> skip downstream. ignore_downstream_trigger_rules=False
# skips only direct downstream tasks and lets the others apply their own trigger rules.
@task.short_circuit(ignore_downstream_trigger_rules=False)
def has_new_rows(n: int) -> bool:
return n > 0
@task
def transform():
print("transforming")
@task(trigger_rule=TriggerRule.ALL_DONE)
def write_audit_row():
print("audit row written") # still runs: it has its own trigger rule
@task
def optional_export():
if True: # e.g. feature flag off for this tenant
raise AirflowSkipException("export disabled for this tenant")
gate = has_new_rows(count_new_rows())
gate >> transform() >> write_audit_row()
optional_export()
dag_obj = short_circuit_demo()
if __name__ == "__main__":
run = dag_obj.test()
for ti in sorted(run.get_task_instances(), key=lambda t: t.task_id):
print(f"{ti.task_id:16} {ti.state}")
print("dag run:", run.state)
With the default ignore_downstream_trigger_rules=True, the same run also marks write_audit_row as skipped.
Common mistakes:
- Expecting a downstream
all_donetask to run after a default short-circuit. - Using a skip to hide errors. If the data should have arrived, fail or alert.
- Catching every exception and turning it into
AirflowSkipException.
19. What are setup and teardown tasks, and how are they different from an all_done cleanup?
Setup and teardown tasks wrap work that needs a temporary resource, such as a short-lived cluster, a temp schema or a lock. The teardown runs even if the work fails, as long as the setup succeeded. Teardown results are ignored when Airflow decides if the DAG run passed. And clearing a work task also clears its setup and teardown, so a rerun gets a fresh resource.
Mark tasks with @setup / @teardown, or call .as_setup() / .as_teardown(setups=...) on existing operators. The tasks between a pair are in its scope.
Why this beats a plain cleanup task with trigger_rule="all_done":
| Concern | all_done cleanup |
Setup/teardown |
|---|---|---|
| Runs after a work failure | Yes | Yes |
| Runs if the resource was never created | Yes (and may error) | No. The fixed rule all_done_setup_success needs a setup to have succeeded |
| Effect on DAG run state | Can turn a failed run green when it is the leaf | Ignored by default; set on_failure_fail_dagrun=True to count it |
| Clearing one work task | Doesn’t recreate the resource | Clears its setup and teardown as well |
| Graph | Ordinary edge | Dotted setup/teardown edge |
Rules:
- A teardown’s trigger rule cannot be changed.
- Every task in a setup’s scope implicitly needs that setup to succeed.
- Setups and teardowns can be attached to a whole task group, which gives the group a clear lifecycle.
- They are tasks, so they use worker slots and honour retries. Keep teardowns idempotent (“delete if exists”), because they may run twice.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import dag, setup, task, teardown
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def ephemeral_cluster():
@setup
def create_cluster() -> str:
print("cluster created")
return "cluster-42"
@task
def run_job(cluster_id: str):
raise RuntimeError(f"job failed on {cluster_id}")
@task
def publish():
print("published")
@teardown
def delete_cluster(cluster_id: str):
print(f"deleted {cluster_id}") # runs even though run_job failed
cluster = create_cluster()
job = run_job(cluster)
job >> publish()
# as_teardown links the setup to the teardown; the work in between is "in scope"
job >> delete_cluster(cluster).as_teardown(setups=cluster)
dag_obj = ephemeral_cluster()
if __name__ == "__main__":
run = dag_obj.test()
for ti in sorted(run.get_task_instances(), key=lambda t: t.task_id):
print(f"{ti.task_id:15} {ti.state}")
print("dag run:", run.state)
Common mistakes:
- Using
all_donefor cleanup and then wondering why failed runs show green. - Writing a teardown that fails if the resource is already gone.
- Expecting teardown failures to fail the run without
on_failure_fail_dagrun=True.
20. Generating many DAGs from config vs dynamic task mapping: when do you use each?
Generate separate DAGs when each unit needs its own schedule, owner, permissions or history, for example one DAG per customer. Use dynamic task mapping when the number of items changes from run to run inside one pipeline. When you generate DAGs, the config must be fixed and quick to read when the file is parsed. get_parsing_context() lets workers skip building DAGs they do not need.
| Question | Many generated DAGs | One DAG with mapping |
|---|---|---|
| Different schedules or SLAs per unit? | Yes | No |
| Separate pause, permissions or tags? | Yes | No |
| Count changes run to run? | Awkward: the DAG list changes | Natural |
| Parse cost | Grows with the number of DAGs | Constant |
| Where the item list comes from | Parse time: a YAML/JSON file in the bundle | Run time: an upstream task |
Rules for DAG factories:
- The config travels with the code. Use a YAML file in the bundle, not a database query or an API call. Parse-time I/O runs every 30 seconds or so, and if it fails, DAGs disappear.
- Use a plain builder function that takes Python values and returns a
DAG. Arguments of an@dag-decorated function become DAG params, not Python values. Passing a list that way and then calling.expand()on it fails at parse time withexpand() got an unexpected type 'DagParam'. - Keep dag_ids stable. Renaming a generated id orphans its history.
get_parsing_context().dag_idis set when a worker parses the file to run one task. Skipping the other DAGs then speeds up task start. The DAG processor leaves it asNoneand builds all of them.- Libraries such as DAG Factory build DAGs from YAML. They are useful for platform teams, but they still parse as Python.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
# One file -> one DAG per tenant. The config is a static file shipped with the code,
# so parsing stays fast and deterministic (no API or DB calls at top level).
from datetime import datetime
from airflow.sdk import DAG, get_parsing_context, task
TENANTS = { # in practice: yaml.safe_load(open(".../tenants.yaml"))
"acme": {"schedule": "0 2 * * *", "tables": ["orders", "invoices"]},
"globex": {"schedule": "30 3 * * *", "tables": ["orders"]},
}
def build_dag(tenant: str, cfg: dict) -> DAG:
# A plain builder function: arguments of an @dag-decorated function would
# become DAG params instead of Python values.
with DAG(dag_id=f"export_{tenant}", schedule=cfg["schedule"], start_date=datetime(2026, 1, 1),
catchup=False, tags=["export", tenant]) as d:
@task
def export_table(table: str):
print(f"exporting {tenant}.{table}")
export_table.expand(table=cfg["tables"])
return d
# A worker running one task sets the parsing context, so it can skip the other DAGs.
# The DAG processor leaves it unset and builds all of them.
current = get_parsing_context().dag_id
for tenant, cfg in TENANTS.items():
if current is None or current == f"export_{tenant}":
build_dag(tenant, cfg) # a DAG created at module level is registered
Common mistakes:
- Building the DAG list from a database query at parse time.
- Generating thousands of near-identical DAGs where one mapped DAG would do.
- Changing dag_ids on every deploy, for example by including a version or date in them.
21. How do Params work, and how do you trigger a DAG with validated inputs?
params declares inputs for a DAG or task, with types, defaults and JSON Schema validation. A manual trigger, the API or dag_run.conf can override them, and bad values are rejected before the run is even created. Tasks read them as params in the context, or as {{ params.x }} in templates. The trigger form in the UI is built from them automatically.
- Declare:
Param(default, type=..., enum=..., minimum=..., maximum=..., description=...). Types follow JSON Schema:string,integer,number,boolean,array,objectandnull, plus formats such asdate. - Override: the trigger form,
airflow dags trigger --conf '{...}', the REST API orTriggerDagRunOperator(conf=...). With[core] dag_run_conf_overrides_params = True(the default), conf values replace the defaults. - Validate: values are checked against the schema when the run is created. A scheduled run uses the defaults, so every default must be valid.
- Read:
params["region"]in TaskFlow, or{{ params.region }}in templates. Task-level params merge over DAG-level ones.
Params versus other inputs:
| Input | Use for |
|---|---|
| Params | Run-scoped options: reprocess a region, run dry |
| Variables | Environment settings that are the same for every run |
| Connections | Credentials |
| XCom | Values produced during the run |
Good practice: give every param a safe default, so scheduled runs need no conf. Use enum for choices. Document params with description, which appears in the trigger form. Treat conf as untrusted user input: never paste it straight into SQL; bind it as a query parameter or check it against an allow-list.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import Param, dag, task
@dag(
schedule=None,
start_date=datetime(2026, 1, 1),
catchup=False,
params={
"region": Param("eu", type="string", enum=["eu", "us", "apac"]),
"lookback_days": Param(1, type="integer", minimum=1, maximum=31),
"dry_run": Param(False, type="boolean", description="Log the SQL only"),
"tables": Param(["orders"], type="array", items={"type": "string"}),
},
)
def reprocess_region():
@task
def plan(params=None):
print(f"region={params['region']} lookback={params['lookback_days']} "
f"dry_run={params['dry_run']} tables={params['tables']}")
plan()
dag_obj = reprocess_region()
if __name__ == "__main__":
print(dag_obj.test().state) # defaults
print(dag_obj.test(run_conf={"region": "us", "lookback_days": 7,
"tables": ["orders", "refunds"]}).state)
try:
dag_obj.test(run_conf={"lookback_days": 90})
except Exception as e:
print(type(e).__name__, "->", str(e).splitlines()[0])
Common mistakes:
- Reading
dag_run.conf["x"]directly with no default or validation. - Formatting conf values straight into SQL strings.
- Using Variables as run inputs. A Variable is shared by every run.
22. CronTriggerTimetable vs CronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?
CronDataIntervalTimetable, the Airflow 2 behaviour, gives each run a data interval and starts it only after that interval ends. CronTriggerTimetable, the Airflow 3 default for cron strings, simply fires at the cron time, and its data interval has zero length unless you pass interval= for a look-back window. Write a custom timetable only when cron, MultipleCronTriggerTimetable, EventsTimetable or a delta timetable cannot express your calendar.
The first run for "0 6 * * *" with start_date 2026-03-01 (output below):
| Timetable | logical_date | data interval | actually runs at |
|---|---|---|---|
CronTriggerTimetable (3.x default) |
03-01 06:00 | 03-01 06:00 → 03-01 06:00 | 03-01 06:00 |
CronTriggerTimetable(interval=1 day) |
02-28 06:00 | 02-28 06:00 → 03-01 06:00 | 03-01 06:00 |
CronDataIntervalTimetable (2.x default) |
03-01 06:00 | 03-01 06:00 → 03-02 06:00 | 03-02 06:00 |
Why this matters when you migrate: {{ ds }} and data_interval_* move between the two timetables. A task filtering on data_interval_start <= ts < data_interval_end would select nothing under a zero-length interval. Options:
- Set
[scheduler] create_cron_data_intervals = Trueto keep the 2.x semantics for every cron-string DAG. Do it before upgrading. - Pass an explicit
CronDataIntervalTimetable(...)on the DAGs that depend on intervals. - Or use
CronTriggerTimetable(..., interval=timedelta(days=1))and check your templates.
Built-in timetables to know: DeltaTriggerTimetable / DeltaDataIntervalTimetable, MultipleCronTriggerTimetable (several crons, one DAG), EventsTimetable (a fixed list of datetimes), AssetOrTimeSchedule, and the partition timetables from 3.2+ (see What is asset partitioning in Airflow 3.2+, and when would you use it?).
A custom timetable subclasses Timetable and implements next_dagrun_info and infer_manual_data_interval. It is registered through a plugin, because the scheduler must import it to deserialise DAGs. Typical cases are trading-day calendars and “business day N of the month”.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
# Compare how two timetables label and time the first run for "every day at 06:00".
from datetime import datetime, timedelta, timezone
from airflow.timetables.base import TimeRestriction
from airflow.timetables.interval import CronDataIntervalTimetable
from airflow.timetables.trigger import CronTriggerTimetable
start = datetime(2026, 3, 1, tzinfo=timezone.utc)
tables = {
"CronTriggerTimetable (3.x default for cron strings)": CronTriggerTimetable("0 6 * * *", timezone="UTC"),
"CronTriggerTimetable with interval=1 day": CronTriggerTimetable(
"0 6 * * *", timezone="UTC", interval=timedelta(days=1)),
"CronDataIntervalTimetable (2.x behaviour)": CronDataIntervalTimetable("0 6 * * *", timezone="UTC"),
}
for name, tt in tables.items():
info = tt.next_dagrun_info(
last_automated_data_interval=None,
restriction=TimeRestriction(earliest=start, latest=None, catchup=True),
)
print(name)
print(" logical_date:", info.logical_date)
print(" interval: ", info.data_interval.start, "->", info.data_interval.end)
print(" runs at: ", info.run_after)
Common mistakes:
- Saying “a daily DAG always runs for yesterday”. That depends on the timetable.
- Changing
create_cron_data_intervalsafter Airflow 3 runs already exist. Logical dates shift, and runs can be duplicated or skipped. - Writing a custom timetable without registering it in a plugin.
Learn more: Airflow DAG Fundamentals, TaskFlow and Dynamic DAGs
23. How do scheduler-managed backfills work in Airflow 3?
In Airflow 3, a backfill is stored in the database, and the scheduler creates and runs its DAG runs like any others, respecting max_active_runs, pools and the normal executors. You start one from the UI, the REST API or airflow backfill create. You choose the date range and what to rerun: nothing that already ran (none), only failed runs, or completed ones too. You can also run it backwards or as a dry run.
In 2.x, airflow dags backfill ran a loop in your terminal: closing the terminal killed it, and it ignored part of the scheduler’s limits. Airflow 3 moved backfills into the scheduler (AIP-78).
| Option | Meaning |
|---|---|
--from-date / --to-date |
Logical-date window. Both ends are inclusive, but they are datetimes: a --to-date of midnight leaves out a 03:00 run on that day |
--reprocess-behavior none |
Only create runs for dates that have none (the default) |
failed |
Also re-run dates whose latest run failed |
completed |
Re-run every date, including successful ones |
--max-active-runs |
Concurrency for this backfill, applied separately from the DAG’s own max_active_runs |
--run-backwards |
Newest dates first. Not allowed when tasks use depends_on_past |
--dag-run-conf |
Conf/params for every run |
--run-on-latest-version |
Use the latest bundle version instead of each run’s original one (the default for backfills; see What are DAG bundles and DAG versioning in Airflow 3?) |
--dry-run |
List the runs it would create |
Backfill runs have run_type=backfill, appear in the grid, and can be paused or cancelled. A date that is currently running or queued is never duplicated. Backfills need a time-based schedule. For DAGs on partition timetables, the window is read as partition dates.
The DAG still has to be idempotent per interval (see How do you make Airflow tasks idempotent and safe to retry?, How do you design DAGs so any past interval can be reprocessed safely?), because a backfill simply replays history.
Example
# Runtime: Apache Airflow 3.3 CLI; DAG "daily_revenue" has schedule "0 3 * * *"
airflow backfill create --dag-id daily_revenue \
--from-date 2026-03-01 --to-date 2026-03-05 \
--reprocess-behavior failed --max-active-runs 2 --dry-run
The 5 March run is missing because the window ends at 00:00 that day. Use --to-date 2026-03-05T23:59 to include it.
Common mistakes:
- Describing the 2.x
airflow dags backfillCLI loop as current behaviour. - Assuming the default (
none) reprocesses dates that already ran. It only fills gaps. - Backfilling a DAG whose tasks read “latest” data instead of their own interval.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
In depth: What is the difference between catchup and backfill in Airflow 3?
24. Manual and API-triggered runs in Airflow 3: why can logical_date be None?
Airflow 3 separates when a run may start (run_after) from which data it covers (logical_date). Runs started by an asset, or by the API or UI without a date, get logical_date=None and no data interval. That allows many runs to exist at the same time, which suits ad-hoc or ML inference jobs. So any task that can be started in more than one way must handle a missing date.
| Run created by | logical_date |
data interval | run_after |
|---|---|---|---|
| Schedule (cron/timetable) | Set by the timetable | Set by the timetable | When it may start |
| UI/API trigger with a date | That date | Inferred by the timetable | Trigger time |
| UI/API trigger without a date (REST default) | None |
Absent | Trigger time |
| Asset event | None |
Absent | Event time |
| Backfill | Each date in the range | From the timetable | Scheduled by the backfill |
What changed compared with 2.x:
- A logical date was always present and unique per DAG. With
None, multiple runs no longer collide, which is why inference-style DAGs (AIP-83) became possible. - Triggering with a future logical date is no longer allowed. Use
logical_date=Noneinstead. - When the run has no logical date, context keys such as
data_interval_startare missing from the context. The 3.0 release notes say reading them raises aKeyError. - The
confcontext key anddag_run.external_triggerwere removed. Useparamsanddag_run.run_type.
Defensive pattern: read dag_run.logical_date, fall back to dag_run.run_after or a param, and log which one you used. Or make the date a required Param on DAGs that are only triggered manually (see How do Params work, and how do you trigger a DAG with validated inputs?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime, timezone
from airflow.sdk import dag, task
@dag(schedule="0 4 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def run_types_demo():
@task
def which_day(**context) -> str:
dr = context["dag_run"]
# logical_date is None for API/UI triggers without a date and for asset-triggered runs.
# Fall back to run_after, which every run has, and say so in the log.
anchor = dr.logical_date or dr.run_after
print(f"run_type={dr.run_type} logical_date={dr.logical_date} "
f"run_after={dr.run_after:%Y-%m-%d %H:%M} -> processing {anchor:%Y-%m-%d}")
print("has data_interval_start:", "data_interval_start" in context)
return anchor.strftime("%Y-%m-%d")
which_day()
dag_obj = run_types_demo()
if __name__ == "__main__":
dag_obj.test(logical_date=datetime(2026, 4, 2, 4, tzinfo=timezone.utc)) # like a scheduled/dated run
dag_obj.test(logical_date=None, run_after=datetime(2026, 4, 9, 10, 30, tzinfo=timezone.utc))
Common mistakes:
- Assuming every run has
dsand a data interval. - Inventing future logical dates to make runs unique.
- Using
run_afteras the data date for scheduled runs. It is when the run may start, not which data it covers.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
In depth: What are the logical date and data interval in Airflow, and what changed in Airflow 3?
25. How does asset-aware scheduling work, and how do you combine asset conditions?
A task lists an Asset in its outlets. When the task succeeds, Airflow records an asset event. A DAG with schedule=[asset], or a condition such as (a & b) | c, is queued as soon as the events since its last run meet that condition. Events can carry extra metadata, and the consuming DAG reads them through triggering_asset_events.
- Identity. In Airflow 3,
Asset(name=..., uri=...)can be identified by name, URI or both. The URI is normalised, so a trailing/is dropped. Pick one convention and use it everywhere. - Producing. A task with
outlets=[asset]emits an event when it succeeds. Useoutlet_events[asset].extra = {...}to attach row counts, partitions or paths. Events can also come from the REST API, or from other DAGs throughAssetAlias. - Consuming.
schedule=[a, b]means all of them.a & bis all,a | bis any, and the operators nest. Each consumer keeps a queue of the events received since its last run. Two producer events before one consumer run give one run that sees both events. - Mixing with time.
AssetOrTimeSchedule(timetable=..., assets=...)runs on a timer or on updates. - What it doesn’t do. Airflow doesn’t check the data. An event means “the producer task succeeded”, not “the data is valid”. Put quality checks before the outlet task.
| Assets | TriggerDagRunOperator |
ExternalTaskSensor |
|
|---|---|---|---|
| Coupling | Producer doesn’t know its consumers | Producer names the target | Consumer names producer and task |
| Waiting | None; event-driven | None; push | Polls or defers |
| Lineage in the UI | Asset graph | Partial | Partial |
See TriggerDagRunOperator, ExternalTaskSensor or assets: how do you choose for cross-DAG dependencies? for the trade-offs and the site’s guide on cross-DAG dependencies.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import Asset, dag, task
orders = Asset(name="silver_orders", uri="s3://lake/silver/orders/")
customers = Asset(name="silver_customers", uri="s3://lake/silver/customers/")
fx_rates = Asset(name="fx_rates", uri="s3://lake/ref/fx_rates/")
@dag(schedule="@hourly", start_date=datetime(2026, 1, 1), catchup=False)
def load_orders():
@task(outlets=[orders]) # success of this task emits an asset event
def write_orders(*, outlet_events):
outlet_events[orders].extra = {"rows": 1834, "partition": "2026-05-20T10"}
write_orders()
# Runs when orders AND customers have both updated since the last run, OR fx_rates updated.
@dag(schedule=(orders & customers) | fx_rates, start_date=datetime(2026, 1, 1), catchup=False)
def build_revenue_mart():
@task
def build(*, triggering_asset_events):
for asset, events in triggering_asset_events.items():
print(asset.name, [e.extra for e in events])
build()
producer = load_orders()
consumer = build_revenue_mart()
if __name__ == "__main__":
print("consumer timetable:", type(consumer.timetable).__name__)
def show(c): # compact view of the condition tree
return c.name if hasattr(c, "name") else f"{type(c).__name__}({', '.join(show(o) for o in c.objects)})"
print("condition:", show(consumer.timetable.asset_condition))
print("normalised uri:", orders.uri)
print("producer run:", producer.test().state)
from airflow.models.asset import AssetEvent
from airflow.utils.session import create_session
with create_session() as s:
for ev in s.query(AssetEvent).order_by(AssetEvent.id.desc()).limit(1):
print("event:", ev.asset.name, ev.extra, "from", ev.source_dag_id, ev.source_task_id)
The DB query at the end only inspects the result in this local test. Task code in Airflow 3 cannot query the metadata DB (see What are the Task SDK and the Task Execution API, and why do they matter?).
Common mistakes:
- Thinking an asset event proves the data is correct, or that Airflow watches the storage path. It only records that the producer task succeeded.
- Expecting one consumer run per producer event. Events are batched until the consumer runs.
- Using different URIs for the same data in different DAGs, such as with and without a trailing slash, or
s3a://versuss3://.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
26. What do the @asset decorator, Metadata and AssetAlias add on top of plain asset outlets?
@asset is a shortcut for a DAG with one task that produces one asset, all named after the function. If the function has a parameter named after another asset, that asset becomes an input. Yielding Metadata adds extra data to the asset event the task creates. AssetAlias lets a task decide while it runs which real assets it produced, and other DAGs can be scheduled on the alias.
| Feature | Solves | Notes |
|---|---|---|
@asset(uri=..., schedule=...) |
Boilerplate for asset-centric pipelines | Creates an Asset, a DAG and a task, all with the function’s name |
Inlet parameters, e.g. def summary(self, context, raw_orders) |
Reading upstream events | self, context and outlet_events are reserved parameter names |
yield Metadata(asset, {...}) |
Attaching row counts or ranges to the event | Must be JSON-serialisable; it is stored in the DB |
context["inlet_events"][asset][-1] |
Reading past events of an inlet | Lazy; ordered oldest to newest |
@asset.multi(outlets=[a, b]) |
One function producing several assets | |
AssetAlias("name") |
Outputs known only at run time, such as one asset per country | The task adds concrete assets with outlet_events[alias].add(Asset(...), extra=...) |
Asset.ref(name=...) |
Referring to an asset defined in another file | Avoids duplicate definitions |
When to use which:
- Use
@assetwhen the team thinks in data products (“the daily_summary table”) and each product is one step. Use normal DAGs when a pipeline has many steps but publishes one result. - Use
AssetAliaswhen the set of outputs depends on the data. Defining a fixed asset for each possible output would be impractical. - Asset events are lineage records too. The UI’s asset graph shows which DAG produced and consumed what, so use names people recognise.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from airflow.sdk import Asset, AssetAlias, Metadata, asset, dag, task
# @asset = one DAG + one task + one Asset, all named after the function.
@asset(uri="s3://lake/raw/orders", schedule="@daily")
def raw_orders(self):
rows = 4210 # ... write the file ...
yield Metadata(self, {"row_count": rows}) # becomes the asset event's extra
# Naming a parameter after another asset makes it an inlet; schedule on it to run after it.
@asset(uri="s3://lake/gold/daily_summary", schedule=raw_orders)
def daily_summary(self, context, raw_orders):
last = context["inlet_events"][raw_orders][-1] # most recent upstream event
print("upstream rows:", last.extra["row_count"])
# AssetAlias: the concrete asset (here, which country partition) is only known at run time.
@dag(schedule=None)
def export_by_country():
@task(outlets=[AssetAlias("country_exports")])
def export(*, outlet_events):
for country in ("de", "fr"):
outlet_events[AssetAlias("country_exports")].add(
Asset(name=f"export_{country}", uri=f"s3://exports/{country}/"), extra={"country": country})
export()
export_by_country()
@dag(schedule=AssetAlias("country_exports")) # runs when any asset resolved by the alias updates
def notify_partners():
@task
def notify(*, triggering_asset_events):
print(sorted(a.name for a in triggering_asset_events))
notify()
notify_partners()
Common mistakes:
- Defining the same asset with slightly different names or URIs in two files. Use
Asset.refor a shared module. - Putting large payloads in event
extra. Like XCom, it belongs in the metadata DB only when small. - Assuming
@assetworks for multi-step pipelines. It creates exactly one task; use@taskwithoutletsin a normal DAG instead.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
27. Which sensor settings matter, and how do you write a sensor with @task.sensor?
A sensor checks a condition again and again until it is true. The settings that matter are poke_interval (how often to check), timeout, mode (poke or reschedule), soft_fail and exponential_backoff, plus deferrable=True where supported. @task.sensor turns a function into a sensor. Returning PokeReturnValue(is_done=..., xcom_value=...) ends the wait and passes a value to the next task.
This question is about configuring sensors. For poke versus reschedule versus deferrable, see Sensors vs deferrable operators and the site’s guide on how sensors should wait.
| Setting | Meaning | Guidance |
|---|---|---|
poke_interval |
Seconds between checks | Minutes, not seconds, for slow sources; respect API rate limits |
timeout |
Total seconds before the sensor gives up | Always set it. The default is 7 days |
mode="poke" |
Holds a worker slot the whole time | Only for waits of a few minutes |
mode="reschedule" |
Frees the slot between checks; state up_for_reschedule |
For waits of minutes to hours, when no deferrable version exists |
deferrable=True |
Hands the wait to the triggerer | Best for long or numerous waits (see How does the triggerer work, and how would you write a deferrable operator?) |
soft_fail=True |
Timeout gives skipped instead of failed |
When “nothing arrived” is an acceptable result |
exponential_backoff=True |
Interval grows between checks | Flaky or expensive sources |
max_wait |
Caps the backoff interval | Use with backoff |
silent_fail=True |
Errors other than a timeout count as “not yet” | Rarely a good idea |
Things to know:
timeoutcounts total time since the first check, and retries don’t reset it. In reschedule mode,execution_timeoutdoesn’t limit the overall wait either;timeoutdoes.- A sensor that returns a value saves a second lookup. Pass the discovered path forward with
PokeReturnValue. - Sensors fill pools like any other task. Hundreds of
pokesensors can deadlock a pool. - If the producer is inside Airflow, an asset is usually better than any sensor (see How does asset-aware scheduling work, and how do you combine asset conditions?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import PokeReturnValue, dag, task
ATTEMPTS = {"n": 0} # stand-in for "is the partner manifest there yet?"
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def sensor_demo():
@task.sensor(
poke_interval=1, # seconds between checks (use minutes in production)
timeout=30, # total seconds before giving up
mode="poke", # "reschedule" frees the worker slot between pokes
exponential_backoff=False,
soft_fail=False, # True = mark skipped instead of failed on timeout
)
def wait_for_manifest() -> PokeReturnValue:
ATTEMPTS["n"] += 1
found = ATTEMPTS["n"] >= 3
print(f"poke {ATTEMPTS['n']}: found={found}")
# is_done ends the wait; xcom_value is passed downstream like a return value
return PokeReturnValue(is_done=found, xcom_value="s3://partner/2026-05-20/manifest.json" if found else None)
@task
def load(manifest: str):
print("loading from", manifest)
load(wait_for_manifest())
dag_obj = sensor_demo()
if __name__ == "__main__":
print(dag_obj.test().state)
The module-level counter only works because dag.test() runs every poke in one process. A real sensor must check outside state, because in reschedule mode each poke is a new process.
Learn more: Airflow Sensors and Deferrable Operators
28. How do priority weights and weight_rule decide what runs first?
When there are not enough free slots, the scheduler starts the tasks with the highest effective priority weight first. weight_rule decides how that weight is calculated. downstream, the default, adds the weights of every task after this one. upstream adds the weights of every task before it. absolute uses only the task’s own priority_weight.
For a three-task chain extract >> clean >> load where load has priority_weight=10 and the others 1 (output below):
weight_rule |
extract | clean | load | Effect |
|---|---|---|---|---|
downstream (default) |
12 | 11 | 10 | Starts many new pipelines (breadth first) |
upstream |
1 | 2 | 12 | Finishes pipelines that are already running (depth first) |
absolute |
1 | 1 | 10 | Only explicit weights count; cheapest to compute |
Points to make:
- Weights only matter when something is full: a pool,
parallelismor executor slots. With spare capacity, everything ready runs. - Weights are compared across DAGs. Use weights to put the CFO dashboard’s DAG ahead of an exploratory backfill.
upstreamis good for long DAGs, so half-finished runs don’t wait behind brand-new ones. That helps especially during catchup or backfills.absoluteis cheap and predictable on very large DAGs.- A custom
PriorityWeightStrategy, registered through a plugin, can compute weights from task attributes. - Weight doesn’t pre-empt anything. A running low-priority task keeps its slot.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import DAG, WeightRule
from airflow.providers.standard.operators.empty import EmptyOperator
dags = {}
for rule in (WeightRule.DOWNSTREAM, WeightRule.UPSTREAM, WeightRule.ABSOLUTE):
with DAG(f"weights_{rule.value}", schedule=None, start_date=datetime(2026, 1, 1),
default_args={"weight_rule": rule}) as d:
extract = EmptyOperator(task_id="extract")
clean = EmptyOperator(task_id="clean")
load = EmptyOperator(task_id="load", priority_weight=10) # own weight 10, others 1
extract >> clean >> load
dags[rule.value] = d
if __name__ == "__main__":
for name, d in dags.items():
run = d.test()
# the effective weight the scheduler stored on each task instance
print(f"{name:10}", {ti.task_id: ti.priority_weight for ti in
sorted(run.get_task_instances(), key=lambda t: ["extract", "clean", "load"].index(t.task_id))})
Common mistakes:
- Expecting priority to speed things up when there is spare capacity.
- Raising weights everywhere (“everything is priority 100”), which changes nothing.
- Not knowing the default rule adds up downstream weights, so long DAGs win over short ones.
29. How do you configure retries, backoff, timeouts and the 3.3 retry policies?
retries and retry_delay set how many times to retry and how long to wait. retry_exponential_backoff makes the wait grow each time (with a custom multiplier since 3.2), and max_retry_delay caps it. execution_timeout kills a single attempt that hangs. Airflow 3.3 adds retry_policy, which can retry, fail at once or fall back to the defaults depending on the error. Raising AirflowFailException always fails immediately.
| Setting | Scope | Notes |
|---|---|---|
retries |
Task | Default [core] default_task_retries = 0. Set it in default_args |
retry_delay |
Task | Default 300 s |
retry_exponential_backoff |
Task | True or a multiplier such as 2.0 (3.2+); adds jitter |
max_retry_delay |
Task | Cap for the backoff |
execution_timeout |
One try | Kills the try and counts as a failure, which may be retried |
dagrun_timeout |
DAG run | Marks a run that runs too long as failed |
retry_policy (3.3) |
Task | ExceptionRetryPolicy(rules=[RetryRule(...)]), or subclass RetryPolicy |
AirflowFailException |
Raised in code | No retries, ever |
How retry policies work: rules are checked in order against the exception, using isinstance by default, and the first match wins. An action of RETRY can set its own delay but never goes beyond retries. FAIL stops now. DEFAULT falls back to the normal settings, and so does an exception no rule matches. The policy runs in the worker, and its decision is written to the task log. A subclass can inspect HTTP status codes, Retry-After headers or dag_run.run_type.
Rules of thumb:
- Retry transient errors such as timeouts, 429s, 5xx responses and lost connections. Fail fast on bad credentials, 4xx responses, schema errors and bad input.
- Retries are only safe if the task is idempotent (see How do you make Airflow tasks idempotent and safe to retry? and the site’s guide on retries and idempotency).
- Always set
execution_timeouton tasks that call networks. A hung socket otherwise holds a slot until the heartbeat timeout fires (see What are zombie tasks (heartbeat timeouts), and how do you debug them?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3 (retry policies are new in 3.3)
from datetime import datetime, timedelta
from airflow.sdk import ExceptionRetryPolicy, RetryAction, RetryRule, dag, task
CALLS = {"flaky": 0}
# First matching rule wins; anything unmatched falls back to retries/retry_delay.
API_POLICY = ExceptionRetryPolicy(rules=[
RetryRule(exception=PermissionError, action=RetryAction.FAIL, reason="bad credentials, retrying won't help"),
RetryRule(exception=ConnectionError, action=RetryAction.RETRY, retry_delay=timedelta(seconds=1)),
])
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False,
default_args={
"retries": 3,
"retry_delay": timedelta(seconds=1),
"retry_exponential_backoff": 2.0, # numeric multiplier since 3.2 (True = 2)
"max_retry_delay": timedelta(minutes=30),
"execution_timeout": timedelta(minutes=10), # per try; kills a hung call
"retry_policy": API_POLICY,
})
def retry_demo():
@task
def flaky_api():
CALLS["flaky"] += 1
if CALLS["flaky"] < 3:
raise ConnectionError(f"timeout on attempt {CALLS['flaky']}")
print("succeeded on attempt", CALLS["flaky"])
@task
def bad_credentials():
raise PermissionError("token rejected")
flaky_api()
bad_credentials()
dag_obj = retry_demo()
if __name__ == "__main__":
run = dag_obj.test()
for ti in sorted(run.get_task_instances(), key=lambda t: t.task_id):
print(f"{ti.task_id:16} state={ti.state} try_number={ti.try_number} max_tries={ti.max_tries}")
bad_credentials had 3 retries available but failed on its first try, because of the policy’s FAIL rule.
Common mistakes:
- Treating
execution_timeoutas a whole-run timeout. It applies to each try, including time spent deferred. - Retrying non-idempotent appends, which duplicates data on every retry.
- Very many retries with no backoff against a struggling dependency.
In depth: How should Airflow retries and idempotency work together?
30. SLAs were removed in Airflow 3. How do Deadline Alerts replace them?
The old sla and sla_miss_callback were removed in Airflow 3.0; using them now only gives a warning. Since 3.1, a DAG can declare deadline=DeadlineAlert(reference=..., interval=..., callback=...). If a run has not finished by the reference time plus the interval, the callback runs. Callbacks are either AsyncCallback, run in the triggerer, or SyncCallback, run by the executor (since 3.2). The feature is still marked experimental.
Why SLAs went away: they were measured from odd anchors, they were evaluated by the DAG processor, and they misfired around catchup. Deadlines are explicit.
References (the point the clock starts from):
| Reference | Deadline = |
|---|---|
DAGRUN_LOGICAL_DATE |
Scheduled time + interval. “Done by 04:00 for the 01:00 run”, even if the run never started |
DAGRUN_QUEUED_AT |
Queue time + interval. Catches capacity problems |
FIXED_DATETIME(dt) |
A wall-clock time; a negative interval alerts before it |
AVERAGE_RUNTIME(max_runs, min_runs) |
Now + historical average + interval. No deadline is set if there aren’t enough runs |
| Custom reference | Any function that returns a timestamp |
Callbacks:
AsyncCallback(callable_or_notifier, kwargs=...)runs in the triggerer. The callable must be importable there, for example from the plugins folder, and the triggerer needs a restart after you change it.SyncCallback(...)(3.2+) is sent to the executor and runs as a top-priority task.- Templated kwargs such as
{{ dag_run.dag_id }}and{{ deadline.deadline_time }}work with notifiers, and acontextkwarg is passed in. - Airflow 3.3 adds a Deadlines page under Browse.
How to migrate: map each old sla=timedelta(...) to a DAGRUN_LOGICAL_DATE deadline at the DAG level, and send it to the same channel. Remember that the old SLAs were per task, while deadlines are per DAG run. Product behaviour changes; checked October 2026.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — plugins/deadline_callbacks.py
def page_finance_oncall(**kwargs):
context = kwargs.get("context", {})
dag_id = context.get("dag_run", {}).get("dag_id")
print(f"[{kwargs['severity']}] {dag_id} missed its deadline")
Common mistakes:
- Saying “set
sla=on the task” for Airflow 3. - Defining an
AsyncCallbackthat the triggerer can’t import. - Using only
AVERAGE_RUNTIMEon a new DAG, which sets no deadline until enough runs exist.
31. How do multiple executors work, and how do you route a task to a specific one?
Since Airflow 2.10 you can list several executors, for example CeleryExecutor,KubernetesExecutor. The first one is the default. A task can choose another with executor="KubernetesExecutor" or an alias, and a whole DAG can do it through default_args. Airflow 3 removed the old hybrid executors, CeleryKubernetes and LocalKubernetes, because this does the same job more simply.
Q42 compares the executors themselves. This question is about running more than one.
Configuration:
executor = LocalExecutor,CeleryExecutor, or with aliases:executor = fast:CeleryExecutor,isolated:KubernetesExecutor.- Every component (schedulers, API server, workers, DAG processor) must have the same list. A task that names an executor not in the list makes the DAG fail to parse (output below).
- One class can’t be listed twice, except across teams in multi-team mode (3.2+).
Routing:
| Scope | How |
|---|---|
| One task | @task(executor="KubernetesExecutor") or Operator(executor=...) |
| Whole DAG | default_args={"executor": "..."} |
| Per-executor settings | executor_config={"pod_override": k8s.V1Pod(...)} for Kubernetes; queue= for Celery |
Typical layouts:
- Celery default + Kubernetes for the heavy work: low latency for thousands of light tasks, isolation for big ones.
- Local default + an ECS, Batch or Kubernetes executor: a small single-machine deployment that can burst.
- Celery + EdgeExecutor: run some tasks on remote sites or in other networks (see What is the Edge Executor, and when would you use it?).
Each executor reports its own metrics, such as executor.open_slots.<executor class name>. Watch each one separately. An idle Kubernetes executor doesn’t help when the Celery queue is full.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
# airflow.cfg (every component must have the same list):
# [core] executor = CeleryExecutor,KubernetesExecutor # first = default
from datetime import datetime
from airflow.sdk import dag, task
@dag(schedule="0 2 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def mixed_executors():
@task # default executor (first in the list)
def trigger_warehouse_job():
print("submitting SQL")
@task(executor="KubernetesExecutor", # own pod, own resources
executor_config={"pod_override": None}) # e.g. a k8s V1Pod with 16Gi memory
def train_model():
print("training")
trigger_warehouse_job() >> train_model()
mixed_executors()
Common mistakes:
- Configuring the second executor on the scheduler but not on other components, which leads to parse errors in some places.
- Proposing CeleryKubernetesExecutor for Airflow 3.
- Confusing
executor=withqueue=. A queue routes between Celery worker groups within the Celery executor.
Learn more: Airflow Executors, Pools and Scaling
In depth: How do you choose an Airflow executor: Local, Celery, Kubernetes or several?
32. KubernetesPodOperator vs KubernetesExecutor vs virtualenv tasks: how do you isolate dependencies?
KubernetesPodOperator runs any container image as one task, from any executor; the Airflow task just starts the pod and watches it. KubernetesExecutor runs the Airflow task itself in a new pod. @task.virtualenv and @task.external_python give a task its own Python packages on the worker, without building an image. @task.docker and @task.kubernetes run a Python function inside a container.
| Option | What is isolated | Startup cost | Best for |
|---|---|---|---|
@task.virtualenv(requirements=[...]) |
Python packages; venv built per run (cacheable) | Seconds to minutes | Occasional conflicting libraries |
@task.external_python(python="/opt/venvs/x/bin/python") |
A venv that already exists | Low | Stable, heavy dependencies baked into the worker image |
@task.docker / DockerOperator |
Container on a Docker host | Medium | Docker-based setups |
@task.kubernetes |
A Python function in a pod with a chosen image | Pod start | Python code with its own image |
KubernetesPodOperator |
Any image, any language, own CPU/RAM/GPU | Pod start | Spark-submit, dbt, ML, non-Python tools |
KubernetesExecutor (executor= routing) |
The whole Airflow task process | Pod start | Per-task resources while keeping normal operators |
KubernetesPodOperator settings that matter:
imagewith a pinned tag,cmds/arguments(templated), andcontainer_resourcesrequests and limits.namespace,service_account_namefor cloud IAM through workload identity, andnode_selector/tolerations.on_finish_action="delete_succeeded_pod"keeps failed pods around for debugging.get_logs=Truestreams logs.do_xcom_push=Truereads/airflow/xcom/return.jsonfrom a sidecar.deferrable=Truewaits in the triggerer instead of keeping a worker busy while the pod runs (see How does the triggerer work, and how would you write a deferrable operator?).reattach_on_restart=True, the default, avoids launching a second pod after a worker restart.
The usual mistake is mixing up KPO and KubernetesExecutor (see Airflow executors: Local vs Celery vs Kubernetes). KPO works fine on Celery.
Example
# Runtime: Python 3.11, Apache Airflow 3.3, apache-airflow-providers-cncf-kubernetes 10.x
from datetime import datetime
from kubernetes.client import models as k8s
from airflow.sdk import dag, task
from airflow.providers.cncf.kubernetes.operators.pod import KubernetesPodOperator
@dag(schedule="0 3 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def isolated_tasks():
# 1) Any container image, any language, own CPU/memory; works with ANY executor.
score = KubernetesPodOperator(
task_id="score_customers",
name="score-customers",
namespace="data-jobs",
image="registry.internal/ml/scorer:2026.05.1", # pinned tag, not :latest
cmds=["python", "-m", "scorer"],
arguments=["--date", "{{ ds }}"], # templated
container_resources=k8s.V1ResourceRequirements(
requests={"cpu": "2", "memory": "8Gi"}, limits={"memory": "8Gi"}),
env_vars={"OUTPUT": "s3://lake/gold/scores/{{ ds }}/"},
on_finish_action="delete_succeeded_pod", # keep failed pods for debugging
get_logs=True,
deferrable=True, # wait in the triggerer, not a worker
)
# 2) Python with conflicting libraries, no image build: a throwaway virtualenv on the worker.
@task.virtualenv(requirements=["pandas==2.2.3"], system_site_packages=False)
def legacy_report():
import pandas as pd
return pd.__version__
score >> legacy_report()
isolated_tasks()
Common mistakes:
- Using the
:latesttag, which makes reruns not reproducible. - No resource requests or limits, so pods get evicted or starve their neighbours.
@task.virtualenvwith a large requirements list on every run, without caching (venv_cache_path).
Learn more: Airflow Executors, Pools and Scaling
33. What are DAG bundles and DAG versioning in Airflow 3?
A DAG bundle is where DAG code comes from: a local folder, a Git repository, or a folder in S3 or GCS. Airflow saves a new DAG version whenever a DAG’s structure changes after it has run. Versioned bundles, today GitDagBundle, also tie each run to the Git commit it started with. So a run keeps using the same code even if main changes during the run, and the UI shows each run’s own graph.
| Bundle | Versioned? | Notes |
|---|---|---|
LocalDagBundle (default dags-folder) |
No | Same behaviour as Airflow 2’s DAGs folder; always the latest code |
GitDagBundle (git provider) |
Yes | tracking_ref (branch, tag or SHA), git_conn_id or repo_url, subdir, sparse_dirs |
S3DagBundle / GCSDagBundle |
No | Bucket and prefix; latest code |
Configure bundles with [dag_processor] dag_bundle_config_list, a JSON list of {name, classpath, kwargs}. You can mix bundle types and have several repositories, for example one per team.
DAG versioning behaviour:
- The DAG processor serialises each DAG. If the result differs and the current version already has task instances, a new version number is created. Otherwise the current version is updated in place.
- Each run records
created_dag_version. The grid and graph views show history as it was, so removed tasks no longer vanish from the history. - Rerun and clear (3.3).
rerun_with_latest_version(DAG argument,[core]setting, or a per-request flag) chooses between the original bundle version and the latest one. The default is the original version for clear and rerun, and the latest version for backfills. disable_bundle_versioning=Trueon a DAG opts it out of versioning.
Why interviewers care: Airflow 2 always reran with the latest code. A fix deployed in the middle of a run could leave half a run on old code and half on new. Versioned bundles make reruns reproducible and deploys safer.
Example
# Runtime: Apache Airflow 3.3 + apache-airflow-providers-git — airflow.cfg
[dag_processor]
dag_bundle_config_list = [
{"name": "analytics-dags",
"classpath": "airflow.providers.git.bundles.git.GitDagBundle",
"kwargs": {"git_conn_id": "github_analytics", "tracking_ref": "main", "subdir": "dags"}},
{"name": "dags-folder",
"classpath": "airflow.dag_processing.bundles.local.LocalDagBundle",
"kwargs": {}}
]
[core]
rerun_with_latest_version = False
Common mistakes:
- Assuming versioning pins code when you use the local DAGs folder. Only versioned bundles pin code. The local folder still records DAG structure versions.
- Expecting a clear to use new code by default in 3.3. Clears default to the original version; use “run on latest version” when you are deploying a fix.
- Not giving the DAG processor and the workers Git credentials and network access.
Learn more: Airflow DAG Fundamentals, TaskFlow and Dynamic DAGs
34. How do secrets backends work in Airflow 3, and what is the lookup order?
A secrets backend fetches Connections and Variables, and sensitive settings, from Vault, AWS Secrets Manager, GCP Secret Manager or Azure Key Vault when they are needed. Airflow always looks in the configured backend first, then environment variables, then the metadata database, and you cannot change that order. Airflow 3 also lets workers use their own secrets backend ([workers] secrets_backend), which they check before the general one.
Configuration:
[secrets]
backend = airflow.providers.amazon.aws.secrets.secrets_manager.SecretsManagerBackend
backend_kwargs = {"connections_prefix": "airflow/connections", "variables_prefix": "airflow/variables"}
use_cache = False # True caches lookups for cache_ttl_seconds (900)
[workers]
secrets_backend = # optional worker-only backend, checked first on workers
Each kwarg can also be set on its own as AIRFLOW__SECRETS__BACKEND_KWARG__<KEY>, which is handy for Kubernetes secrets.
How it behaves:
- Search path: custom backend →
AIRFLOW_CONN_*/AIRFLOW_VAR_*→ metadata DB. The first match wins, so a key that exists in two places can hide another. - Writes from the UI, CLI or
Variable.setalways go to the metadata DB. A value stored in the backend keeps winning on reads, which confuses people. - The UI shows only DB-stored values. Check backend-provided values in the backend itself.
- Cost and latency: every
Variable.getis an API call to the backend. Top-level lookups multiply that by the parse rate (see Why is DAG parsing slow, and how do you keep parse time low?). Turn onuse_cacheor read only inside tasks. - Prefixes and lookup patterns (
connections_lookup_pattern,variables_lookup_patternon several providers) limit which keys are sent to the backend, which saves calls for DB-stored keys. - Masking: values from backends are masked in logs like any connection password.
A custom backend subclasses BaseSecretsBackend and implements get_conn_value (returning a URI or JSON) and get_variable. Returning None means “not here”, and the next source is tried.
Example
The backend’s s3://exports-prod beat the environment variable, as the lookup order says it should.
Common mistakes:
- Editing a Variable in the UI and expecting it to override the backend’s value.
- Top-level
Variable.getwith a paid secrets API behind it, which turns into thousands of calls an hour. - Giving workers access to all secrets instead of a prefix.
Learn more: Airflow XCom, Variables, Connections and Secrets
35. How do you test task logic and run a DAG end to end with dag.test()?
Keep the business logic in plain Python functions and unit-test them without Airflow; that is fast and gives the same result every time. Test TaskFlow tasks through their underlying function (.function on the decorated task). Use dag.test() to run a whole DAG in one process, with no scheduler, executor or triggerer. Its arguments, such as run_conf, logical_date and files for connections and variables, make that run repeatable.
A testing pyramid for Airflow:
| Layer | What | Speed |
|---|---|---|
| Unit | Pure functions such as transforms, SQL builders and file parsers | Milliseconds |
| Task | .function(...) or operator.execute(context) with a fake or minimal context |
Milliseconds |
| Integrity | DagBag loads, conventions (see How do you write DAG integrity tests that catch broken DAGs before merge?) | Seconds |
| DAG | dag.test(): real dependencies, XCom, trigger rules, branching, deferral (triggers run in-process) |
Seconds |
| Integration | Against real services in a staging environment, possibly with use_executor=True |
Minutes |
dag.test() in 3.3:
logical_date=...(timezone-aware) orlogical_date=None, plusrun_after=to simulate a run without a date (see Manual and API-triggered runs in Airflow 3: why canlogical_datebeNone?).run_conf={...}validates against params (see How do Params work, and how do you trigger a DAG with validated inputs?).conn_file_path/variable_file_pathload test Connections and Variables from a file.mark_success_pattern="publish|notify"marks tasks whose ids match the regex as successful without running them, which skips side effects.- It needs a metadata DB. A local SQLite DB, created with
airflow db migrate, is fine. It also syncs the DAG’s bundle first, so keep the test harness outside the DAG folder. - It returns the DagRun, so you can assert on
run.stateand on each task instance’s state.
Mocking: patch hooks at their import path (unittest.mock.patch("my_dag.S3Hook")), or inject clients so tests can pass fakes. Avoid mocking Airflow internals.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — dags/fx_pipeline.py
from datetime import datetime
from airflow.sdk import dag, task
def to_eur(rows: list[dict], rates: dict) -> list[dict]:
"""Pure business logic: no Airflow imports needed to test it."""
out = []
for r in rows:
if r["currency"] not in rates:
raise ValueError(f"no rate for {r['currency']}")
out.append({**r, "amount_eur": round(r["amount"] * rates[r["currency"]], 2)})
return out
@dag(schedule="0 6 * * *", start_date=datetime(2026, 1, 1), catchup=False)
def fx_pipeline():
@task
def extract() -> list[dict]:
return [{"id": 1, "amount": 100.0, "currency": "USD"}, {"id": 2, "amount": 50.0, "currency": "GBP"}]
@task
def convert(rows: list[dict]) -> list[dict]:
return to_eur(rows, {"USD": 0.92, "GBP": 1.17})
@task
def publish(rows: list[dict]) -> int:
print("publishing", rows)
return len(rows)
publish(convert(extract()))
fx_pipeline()
Common mistakes:
- Testing only through the Airflow UI.
- Calling real external systems from
dag.test()in CI. - Treating
dag.test()as proof of production isolation. It runs in one process with DB access (see What are the Task SDK and the Task Execution API, and why do they matter?).
36. What does a good CI/CD pipeline for Airflow DAGs look like?
On every pull request: lint with ruff and its AIR rules, run unit tests, load a DagBag in the production image, and optionally run dag.test() on the DAGs that changed. On merge, deploy the DAG code by moving a Git bundle’s tracking_ref or syncing files, and build a new image only when dependencies change. Promote through staging before production, with the same code and different connections.
Split the two kinds of change:
| Artifact | Changes how often | Deploy by |
|---|---|---|
| DAG code (Python, SQL, YAML) | Many times a day | GitDagBundle (versioned, see What are DAG bundles and DAG versioning in Airflow 3?), git-sync, or object-storage sync |
| Runtime image (Airflow, providers, libraries) | Weekly or monthly | Image build with constraints, then a rolling restart of the components |
Pipeline stages:
- Static:
ruff check --select AIRand general lint, plussqlflufffor SQL files and type checks. - Unit: pure-function tests (see How do you test task logic and run a DAG end to end with
dag.test()?). - Integrity: DagBag with zero import errors, conventions, and a parse-time budget, all inside the production image (see How do you write DAG integrity tests that catch broken DAGs before merge?).
- Behaviour:
dag.test()for DAGs whose files changed, with side effects masked. - Deploy to staging: move the bundle ref, then smoke-test with
airflow dags list-import-errorsand one triggered run. - Promote to prod: the same commit with prod connections from the secrets backend.
Things worth calling out:
- Constraints files. Install Airflow with the official
constraints-<version>/constraints-<python>.txt, so providers and libraries don’t change silently. - Pools, Variables and connections as code. Set them with Terraform, the REST API or
airflow pools importin the pipeline, not by hand. - Version pinning. Because a
GitDagBundlepins each run to a commit, a deploy in the middle of a run is safe. A local-folder sync is not. - Rollback means reverting the commit or moving the ref back. Running DAGs keep their versions.
- Managed platforms have their own deploy tools, such as
astro deploy, Composer’s bucket sync and MWAA’s S3 sync (see MWAA, Cloud Composer or Astronomer: what are the trade-offs of managed Airflow?).
Example
# Runtime: GitHub Actions; Apache Airflow 3.3 image used for test steps
name: dags-ci
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
container: registry.internal/data/airflow:3.3.2-2026.10 # same image as production
env:
AIRFLOW__CORE__LOAD_EXAMPLES: "False"
steps:
- uses: actions/checkout@v4
- run: ruff check --select AIR3 dags/ plugins/
- run: airflow db migrate # throwaway SQLite DB for DagBag and dag.test()
- run: pytest -q tests/unit tests/test_dag_integrity.py
- run: pytest -q tests/dag_runs -k "$(git diff --name-only origin/main -- dags | xargs -n1 basename | sed 's/.py$//' | paste -sd' or ' -)"
The -k expression in the last workflow step assumes one test module per DAG file. Adapt it to your own layout.
Common mistakes:
- Rebuilding and redeploying the whole image for every SQL change.
- CI that tests in a different Python, Airflow or provider version than production.
- Hand-editing pools and connections in prod, so environments drift apart.
Learn more: Airflow Best Practices: Idempotent Tasks, Testing and CI/CD
37. MWAA, Cloud Composer or Astronomer: what are the trade-offs of managed Airflow?
All three run the scheduler, database, API server and workers for you. Amazon MWAA fits deeply into AWS (IAM, S3 for DAGs, VPC). Google Cloud Composer does the same for GCP, on GKE and GCS. Astronomer (Astro) is a platform focused only on Airflow, on several clouds, with its own CLI and image-based deploys, and it usually offers new Airflow versions first. The trade-off is control versus convenience: version delays, limits on settings and plugins, scaling options and the pricing model.
| Dimension | MWAA (AWS) | Cloud Composer (GCP) | Astronomer Astro | Self-managed (Helm/K8s) |
|---|---|---|---|---|
| DAG deploy | S3 bucket sync | GCS bucket sync | astro deploy (image or DAG-only) |
Your choice: Git bundle, git-sync, image |
| Dependencies | requirements.txt and plugins zip, startup script |
PyPI packages in the environment config | Your Dockerfile | Your image |
| Scaling | Environment class plus min/max workers | Environment size, worker autoscaling | Worker queues, autoscaling | Anything you build |
| Identity | IAM execution role | Service accounts | Cloud identities per deployment | You wire it up |
| Config access | Allow-listed overrides | Most overrides | Wide (env vars, image) | Full |
| New Airflow versions | Usually lag upstream | Usually lag upstream | Typically fastest | Immediate |
| Best when | All-AWS shop, small platform team | All-GCP shop, BigQuery-heavy | Many teams, multi-cloud, want Airflow expertise as a service | Strict control or cost needs, strong K8s team |
How to evaluate one:
- Version support. Which Airflow 3.x minor versions, and how quickly they arrive. Features from 3.2/3.3 such as asset partitioning, retry policies and deadline callbacks depend on it. Product behaviour changes; checked October 2026. Confirm on each provider’s supported-versions page before deciding.
- Executor choice. Some services fix the executor (for example Celery on MWAA). KubernetesPodOperator or the services’ own container operators give isolation.
- Networking. Private IPs, VPC peering, and the path to on-premises sources.
- Cost model. Always-on environment fees versus usage-based pricing, plus the worker minimums when idle.
- Escape hatch. Keep DAGs portable: standard providers, no service-only imports, config from env vars and secrets backends. Then moving between services is mostly redeploying.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — run inside each environment (local, MWAA/Composer/Astro
# image) and diff the output before moving DAGs between them.
import sys
import airflow
from airflow.configuration import conf
from airflow.providers_manager import ProvidersManager
print("airflow", airflow.__version__, "| python", sys.version.split()[0])
print("executor:", conf.get("core", "executor"))
for name, info in sorted(ProvidersManager().providers.items()):
print(f" {name}=={info.version}")
38. Why is DAG parsing slow, and how do you keep parse time low?
The DAG processor re-imports every DAG file about every 30 seconds, and workers import it again whenever a task starts. Anything at the top level of the file runs every time: API calls, database queries, Variable.get and heavy imports such as pandas or ML libraries. Move that work inside tasks, import heavy libraries inside the task that needs them, measure with airflow dags report, and use .airflowignore so non-DAG files are not parsed.
Why it matters:
- Slow files delay new DAGs and changes from appearing, and files over
dagbag_import_timeout(30 s) become import errors, so DAGs “flicker” in and out of the UI. - With versioned bundles, every task start parses the file again, so parse time adds to task latency.
- Parse-time calls multiply quickly: 200 files × 2 lookups each × 2 parses a minute is 800 secrets-backend calls a minute.
Fixes, roughly in order of impact:
| Fix | How |
|---|---|
| No I/O at top level | Move the work into a task. Use dynamic task mapping for lists only known at run time (see How do partial() and expand() work in dynamic task mapping, and what is a map index?) |
| Lazy heavy imports | import pandas inside the task function |
| Templates instead of Python lookups | {{ var.value.x }}, {{ conn.x.host }} render at run time |
| Static config for factories | YAML in the bundle, yaml.safe_load once (see Generating many DAGs from config vs dynamic task mapping: when do you use each?) |
get_parsing_context() |
Workers build only the DAG they need |
.airflowignore |
Skip sql/, tests/ and helper packages (glob syntax by default in 3.x) |
| Processor tuning | parsing_processes, min_file_process_interval, refresh_interval, more DAG processor replicas or separate bundles |
parsing_pre_import_modules = True (default) |
Imports airflow modules once in the parent process |
Measure before tuning. airflow dags report lists the parse duration per file. The dag_processing.last_duration metric, tagged by file, shows trends. A CI parse-time budget stops regressions (see How do you write DAG integrity tests that catch broken DAGs before merge?). The official best-practices guide says the same: top-level code is the most common cause of slow schedulers.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — dags/slow_top_level.py
# BAD: work at import time runs on every parse (every ~30 s per file, on every DAG processor)
import time
from datetime import datetime
from airflow.sdk import dag, task
def fetch_tables_from_api():
time.sleep(1.5) # stands in for an HTTP call / DB query
return ["orders", "customers", "invoices"]
TABLES = fetch_tables_from_api() # runs at parse time!
@dag(schedule="@daily", start_date=datetime(2026, 1, 1), catchup=False)
def slow_top_level():
for t in TABLES:
@task(task_id=f"load_{t}")
def load(table=t):
print(table)
load()
slow_top_level()
The same work costs 1.5 s on every parse in the first file, and only once per run, inside a task, in the second.
Common mistakes:
- Raising
dagbag_import_timeoutinstead of removing top-level I/O. - Assuming the scheduler parses files in Airflow 3. The DAG processor does (see How does a Python file become a DAG in Airflow 3? Explain parsing and the DAG processor).
datetime.now()in DAG arguments, which also changes the serialised DAG on every parse and creates needless versions.
Learn more: Airflow DAG Fundamentals, TaskFlow and Dynamic DAGs
In depth: Airflow is slow and tasks sit in scheduled or queued. How do you find the bottleneck?
Advanced Airflow interview questions (experienced)
39. How do you map a whole task group, filter inputs and limit fan-out?
Call .expand() on a @task_group function, and Airflow creates a copy of the whole sub-pipeline for each input. Copies run depth-first, so each item’s second step can start as soon as its own first step is done. Shape the inputs with a filter task, XComArg.map() or .zip(). Use max_active_tis_per_dagrun and pools, so a fan-out of a thousand items does not take every worker slot.
Mapped task groups. process.expand(file=files) maps every task in the group with the same index. process.validate[2] therefore belongs to process.parse[2]. A downstream task that depends on the group’s return value receives every copy’s result.
Shaping the input.
| Tool | Runs as | Use for |
|---|---|---|
| Filter task returning a shorter list | A real task | Dropping items based on data |
A mapped task returning None for an element |
A real task | That element is left out of the next expansion |
xcom_arg.map(fn) |
Pre-processing inside the downstream task, not a separate task | Reshaping each element, such as building kwargs. fn must be a plain function; raise AirflowSkipException in it to skip one element, because returning None does not work |
a.zip(b) / a.concat(b) |
Pre-processing | Pairing or joining lists |
Limits and back-pressure.
[core] max_map_length(1024 by default) is a hard ceiling. If an upstream task returns a longer list, that upstream task fails when it pushes the XCom, and the mapped task becomesupstream_failed. Chunk the input upstream.max_active_tis_per_dagrunlimits running copies within one run.max_active_tis_per_daglimits them across all runs.- A pool (see What are pools, and how do you use them to protect a shared system?) protects a shared external system across DAGs.
- Each instance is a full task: it is scheduled, logged and has its own XCom. Ten thousand instances can slow the scheduler and the UI. Batching 100 items per instance is often better.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import dag, task, task_group
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def mapped_groups():
@task
def list_files() -> list[str]:
return ["orders_1.csv", "orders_2.csv", "README.txt", "orders_3.csv"]
# .map() transforms each element lazily without an extra task; returning None is not
# allowed, so filtering is done in a real task instead.
@task
def only_csv(files: list[str]) -> list[str]:
return [f for f in files if f.endswith(".csv")]
@task_group
def process(file: str):
@task(max_active_tis_per_dagrun=2) # at most 2 copies of this task at once
def parse(file: str) -> dict:
return {"file": file, "rows": len(file) * 10}
@task
def validate(stats: dict) -> dict:
if stats["rows"] <= 0:
raise ValueError(f"empty file {stats['file']}")
return stats
return validate(parse(file))
@task
def summarise(results) -> None:
results = list(results) # materialise the lazy sequence once
print(f"{len(results)} files, {sum(r['rows'] for r in results)} rows")
csv_files = only_csv(list_files())
upper = csv_files.map(lambda f: f.upper()) # map() on an XComArg: no new task
summarise(process.expand(file=upper))
dag_obj = mapped_groups()
if __name__ == "__main__":
run = dag_obj.test()
mapped = sorted({(ti.task_id, ti.map_index) for ti in run.get_task_instances() if ti.map_index >= 0})
print(mapped)
print(run.state)
Common mistakes:
- Passing an Airflow task to
.map(). It must be a plain function. - Assuming Airflow truncates a list longer than
max_map_length. It fails the task that produced the list. - Calling
list()on the lazy sequence many times inside a loop, which pulls every XCom each time.
40. How do AssetWatcher and event-driven scheduling work?
An AssetWatcher attaches a trigger to an asset. The trigger runs in the triggerer and listens to an outside source, such as SQS, Kafka, Redis or a custom poller. Each time it fires, Airflow records an asset event, and any DAG scheduled on that asset runs. Only triggers based on BaseEventTrigger are allowed, and their message reaches tasks through triggering_asset_events.
How the pieces fit together (added in 3.0):
- Define
Asset(name=..., watchers=[AssetWatcher(name=..., trigger=SomeEventTrigger(...))]). - The DAG processor registers the watcher, and a triggerer starts running the trigger’s async
run(). - When the trigger yields a
TriggerEvent, the triggerer creates an asset event whoseextracontains the event payload. For the messaging triggers that means the message, underpayload. - The trigger is then started again to wait for the next event, and every DAG scheduled on the asset is queued.
Ready-made: MessageQueueTrigger(scheme="sqs" | "kafka" | "redis+pubsub", ...) from the common.messaging provider, backed by the AWS, Kafka and Redis providers.
Rules for a custom event trigger:
- Subclass
BaseEventTrigger. Ordinary deferral triggers are not accepted, because many of them fire again immediately when restarted, which would trigger endless runs. - It must be idempotent across restarts. Consume, acknowledge or move what it saw, as the example does by moving each file. Otherwise the same file fires again after the restart.
- It must be fully async. A blocking call stalls every trigger on that triggerer (see How does the triggerer work, and how would you write a deferrable operator?).
serialize()returns an importable classpath, and the module must be on the triggerer’s path. Changing it needs a triggerer restart.- Since 3.3, siblings that poll the same source can share one poll loop via
shared_stream_key().
Delivery is about as reliable as the source and the trigger make it. Keep consumers idempotent, and use the payload, such as a message id or file name, as the deduplication key.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — plugins/inbox_trigger.py (must be importable by the triggerer)
import asyncio
import os
from airflow.triggers.base import BaseEventTrigger, TriggerEvent
class InboxFileTrigger(BaseEventTrigger):
"""Fires once per file dropped into an inbox directory, then moves the file away
so the same file can never fire twice (the trigger is restarted after each event)."""
def __init__(self, inbox: str, done_dir: str, poll_seconds: float = 5.0):
super().__init__()
self.inbox, self.done_dir, self.poll_seconds = inbox, done_dir, poll_seconds
def serialize(self):
return ("inbox_trigger.InboxFileTrigger",
{"inbox": self.inbox, "done_dir": self.done_dir, "poll_seconds": self.poll_seconds})
async def run(self):
while True:
for name in sorted(os.listdir(self.inbox)):
os.makedirs(self.done_dir, exist_ok=True)
os.replace(os.path.join(self.inbox, name), os.path.join(self.done_dir, name))
yield TriggerEvent({"file": name})
return
await asyncio.sleep(self.poll_seconds)
os.listdir is a quick local call. On a network filesystem, use an async client or run it in a thread with asyncio.to_thread.
Common mistakes:
- Using a normal
BaseTrigger(for example a file sensor’s trigger) in a watcher. - A trigger that doesn’t consume or acknowledge what it saw, so it fires again forever.
- Treating event-driven runs as exactly-once.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
41. What is asset partitioning in Airflow 3.2+, and when would you use it?
Asset partitioning (Airflow 3.2 and later) gives each asset event a partition_key, such as an hour, a day or a region. Then each downstream run gets exactly the partitions it needs. A producer uses CronPartitionTimetable, or sets keys while it runs with PartitionedAtRuntime. A consumer uses PartitionedAssetTimetable with partition mappers. Since 3.3, RollupMapper can hold a daily run until all its hourly partitions have arrived.
Plain asset scheduling only knows that something was updated. Partitioning adds which slice was updated.
| Piece | Role |
|---|---|
CronPartitionTimetable("0 * * * *") |
Producer: each scheduled run gets a key for its tick, and its events carry it |
PartitionedAtRuntime() (3.3) |
Producer: the task calls outlet_events[asset].add_partitions([...]) once it knows the keys |
PartitionedAssetTimetable(assets=..., default_partition_mapper=...) |
Consumer: one run per downstream key |
IdentityMapper, StartOfHourMapper, StartOfDayMapper, …, ProductMapper, AllowedKeyMapper |
Translate upstream keys into downstream keys |
RollupMapper(upstream_mapper, window=DayWindow(), wait_policy=...) (3.3) |
Many to one: wait for every hour in a day |
WaitForAll() / MinimumCount(n) |
Release a rollup when all keys, or at least n, have arrived |
FanOutMapper, SegmentWindow + FixedKeyMapper (3.3) |
One to many, and categorical rollups such as all regions |
Inside the run, read dag_run.partition_key. When the mapper is temporal, dag_run.partition_date is set too. Backfills of partitioned DAGs read --from-date/--to-date as a partition-date range (see How do scheduler-managed backfills work in Airflow 3?). Partitioned events don’t trigger DAGs that aren’t partition-aware, and a consumer on PartitionedAssetTimetable ignores events with no key.
Points to raise in an interview:
- It is new and still changing quickly between minor versions. Pin the version and read the release notes before relying on mappers. Product behaviour changes; checked October 2026.
- A
DayWindowassumes 24 hourly steps. Use UTC keys for rollups that cross a daylight-saving change, otherwise a day can wait forever for an hour that never exists. [scheduler] partition_mapper_max_downstream_keysbounds how far one event can fan out.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 (asset partitioning: 3.2+, rollups: 3.3+)
from airflow.sdk import (DAG, Asset, CronPartitionTimetable, DayWindow, MinimumCount,
PartitionedAssetTimetable, RollupMapper, StartOfHourMapper, task)
hourly_clicks = Asset(name="hourly_clicks", uri="s3://lake/bronze/clicks")
# Producer: each run carries a partition key for its hour and stamps it on the asset event.
with DAG("ingest_hourly_clicks",
schedule=CronPartitionTimetable("0 * * * *", timezone="UTC"), catchup=False) as producer:
@task(outlets=[hourly_clicks])
def ingest(dag_run=None):
print("ingesting partition", dag_run.partition_key)
ingest()
# Consumer: one run per UTC day, released when at least 23 of the 24 hours have landed.
with DAG("daily_click_summary",
schedule=PartitionedAssetTimetable(
assets=hourly_clicks,
default_partition_mapper=RollupMapper(
upstream_mapper=StartOfHourMapper(),
window=DayWindow(),
wait_policy=MinimumCount(23), # tolerate one late hour
),
),
catchup=False) as consumer:
@task
def summarise(dag_run=None):
print("summarising day", dag_run.partition_key) # e.g. "2026-05-20"
summarise()
if __name__ == "__main__":
print("consumer timetable:", type(consumer.timetable).__name__)
# How the scheduler computes the producer's next run (core-side class, used here only to show it):
import pendulum
from airflow.timetables.base import TimeRestriction
from airflow.timetables.trigger import CronPartitionTimetable as CoreCronPartition
info = CoreCronPartition("0 * * * *", timezone="UTC").next_dagrun_info_v2(
last_dagrun_info=None,
restriction=TimeRestriction(earliest=pendulum.datetime(2026, 5, 20, 9, 30, tz="UTC"),
latest=None, catchup=True))
print("next producer run:", info.run_after, "| partition_key:", info.partition_key)
Common mistakes:
- Calling this “Airflow 3.0 functionality”. Partitioning arrived in 3.2, and rollups and runtime partitions in 3.3.
- Expecting a partitioned producer to trigger an ordinary asset-scheduled DAG.
- Building hourly-to-daily rollups on local-time keys across daylight-saving changes.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
42. How does the triggerer work, and how would you write a deferrable operator?
A deferrable operator starts the outside work, then calls self.defer(trigger=..., method_name=...). The task moves to the deferred state and frees its worker slot. The triggerer is a separate async process that runs thousands of triggers in one event loop. When a trigger fires, the task is scheduled again and continues in method_name, with the trigger’s message as input. Waiting then costs almost nothing.
Lifecycle:
execute()runs on a worker and submits the job, which is quick.self.defer(...)raises a special exception. The trigger is serialised (classpath and kwargs) and stored, and the task becomesdeferred. It holds no worker slot, and by default no pool slot either.- A triggerer picks the trigger up and runs
async def run(). Each triggerer handles up to[triggerer] capacitytriggers, 1000 by default. Run two or more triggerers for high availability; they split the triggers between them. - The trigger yields a
TriggerEvent(payload). The task goes back toscheduled, a worker starts it again, and it callsexecute_complete(context, event). That method is a fresh call, so any state must come from the event or fromkwargspassed todefer.
Design rules:
- Never block in
run(). Use async clients,asyncio.sleepandasyncio.to_threadfor unavoidable sync calls. One blocking call stalls every trigger in that process. SetPYTHONASYNCIODEBUG=1to find them. - Triggers must be importable by the triggerer and must not depend on worker-only state.
- Timeouts.
defer(timeout=...)bounds the wait.execution_timeoutcovers the whole task, including the deferred time. start_from_trigger=Truelets suitable operators go straight to the triggerer without starting on a worker at all.- Many provider operators support
deferrable=True.[operators] default_deferrable = Trueturns it on everywhere it is supported.
Compared with sensors in reschedule mode (see Sensors vs deferrable operators, Which sensor settings matter, and how do you write a sensor with @task.sensor?): reschedule releases the slot between pokes, but every poke is still a full task start. Deferral is cheaper when there are many long waits.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — job_trigger.py, importable by workers and the triggerer
import asyncio
from airflow.triggers.base import BaseTrigger, TriggerEvent
class JobDoneTrigger(BaseTrigger):
"""Polls an external job asynchronously inside the triggerer's event loop."""
def __init__(self, job_id: str, poll_seconds: float = 30.0):
super().__init__()
self.job_id, self.poll_seconds = job_id, poll_seconds
def serialize(self):
# classpath + kwargs: stored in the DB so any triggerer can rebuild this object
return ("job_trigger.JobDoneTrigger", {"job_id": self.job_id, "poll_seconds": self.poll_seconds})
async def run(self):
polls = 0
while True:
polls += 1
status = "SUCCEEDED" if polls >= 3 else "RUNNING" # stand-in for an async API call
if status in ("SUCCEEDED", "FAILED"):
yield TriggerEvent({"job_id": self.job_id, "status": status, "polls": polls})
return
await asyncio.sleep(self.poll_seconds) # never time.sleep() here
dag.test() runs the trigger in-process, so you can test deferral without a triggerer.
Common mistakes:
time.sleep()or a synchronous HTTP client insiderun().- Keeping state on
selfbetweenexecuteandexecute_complete. It is a new process. - Not running a triggerer at all, so deferred tasks wait forever.
Learn more: Airflow Sensors and Deferrable Operators
In depth: Poke, reschedule or deferrable: how should an Airflow sensor wait?
43. How do custom and object-storage XCom backends work?
An XCom backend controls how XCom values are stored. The common.io provider includes XComObjectStorageBackend: values bigger than a size limit go to S3, GCS, Azure or a file path, and the database keeps only a reference. Reading follows the reference automatically, so DAG code does not change. A custom backend extends BaseXCom and overrides serialize_value, deserialize_value and purge.
Q43 explains why the default backend should only hold small values. A backend changes that without touching DAG code.
Configuration for the built-in object-storage backend:
| Setting | Example |
|---|---|
[core] xcom_backend |
airflow.providers.common.io.xcom.backend.XComObjectStorageBackend |
[common.io] xcom_objectstorage_path |
s3://aws_default@my-bucket/xcom |
[common.io] xcom_objectstorage_threshold |
Bytes. -1 = always DB (the default), 0 = always object storage |
[common.io] xcom_objectstorage_compression |
gzip, bz2, zip, lzma, snappy |
The environment-variable form replaces the section’s dot with an underscore: AIRFLOW__COMMON_IO__XCOM_OBJECTSTORAGE_PATH.
Things to design for:
- Where it runs. In Airflow 3 serialisation happens in the worker’s Task SDK. Workers need credentials for the bucket, and so does the API server if the UI is to show values.
- Lifecycle. Objects outlive their DB rows unless
purgeruns, for example when task instances are cleared. Add a bucket lifecycle rule as a safety net. - Security. Bucket permissions now control who can read task outputs.
- What it doesn’t fix. Moving 2 GB between tasks is still slow. For real data, pass paths to tables or files you write yourself (see the site’s guide on XCom vs external storage).
- A custom backend fits special encodings, such as storing DataFrames as Parquet, or an internal blob store. Keep
serialize_valuedeterministic and its errors clear, because every task depends on it.
Example
# Runtime: Python 3.11, Apache Airflow 3.3, apache-airflow-providers-common-io
# Config (env vars here; airflow.cfg or Helm values in production):
# AIRFLOW__CORE__XCOM_BACKEND=airflow.providers.common.io.xcom.backend.XComObjectStorageBackend
# AIRFLOW__COMMON_IO__XCOM_OBJECTSTORAGE_PATH=file:///srv/xcom (s3://aws_conn@bucket/xcom in prod)
# AIRFLOW__COMMON_IO__XCOM_OBJECTSTORAGE_THRESHOLD=1024 (bytes; smaller values stay in the DB)
# AIRFLOW__COMMON_IO__XCOM_OBJECTSTORAGE_COMPRESSION=gzip
from datetime import datetime
from airflow.sdk import dag, task
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def xcom_backend_demo():
@task
def small() -> int:
return 42 # under threshold -> metadata DB
@task
def big() -> list[dict]:
return [{"id": i, "sku": f"SKU-{i:05d}"} for i in range(2000)] # over threshold -> object storage
@task
def use(n: int, rows: list[dict]):
print("small:", n, "| big rows:", len(rows), rows[-1]) # transparently read back
use(small(), big())
dag_obj = xcom_backend_demo()
if __name__ == "__main__":
print(dag_obj.test().state)
Common mistakes:
- Treating an object-storage backend as permission to pass big datasets through XCom.
- Forgetting worker credentials for the bucket. The tasks then fail when they push, not at parse time.
- Writing
AIRFLOW__COMMON.IO__...as an environment variable. Shells won’t export the dot, and Airflow readsCOMMON_IO.
Learn more: Airflow XCom, Variables, Connections and Secrets
In depth: When should Airflow tasks pass data through XCom, and when through external storage?
44. How do Airflow’s concurrency limits stack, from parallelism down to a single task?
A task only starts when every limit that applies to it has room. The limits are: [core] parallelism per scheduler, the executor’s or worker’s slots, the pool, the DAG’s max_active_tasks and max_active_runs, and the task’s max_active_tis_per_dag and max_active_tis_per_dagrun. The tightest one wins. So “tasks stuck in scheduled” usually means one of these limits is full.
| Level | Setting | Default (3.3) | Limits |
|---|---|---|---|
| Scheduler | [core] parallelism |
32 | Running + queued task instances per scheduler |
| Executor | Celery worker_concurrency, K8s quotas, Local process count |
Celery 16 per worker | Physical slots |
| Pool | slots per pool |
default_pool 128 |
One resource, across all DAGs |
| DAG | max_active_tasks |
[core] max_active_tasks_per_dag = 16 |
Running tasks of one DAG across all its runs |
| DAG | max_active_runs |
[core] max_active_runs_per_dag = 16 |
Concurrent runs (catchup, backfill) |
| Task | max_active_tis_per_dag |
None | Copies of one task across runs |
| Task | max_active_tis_per_dagrun |
None | Copies of one task within a run (mapping) |
| Backfill | --max-active-runs |
n/a | That backfill only (see How do scheduler-managed backfills work in Airflow 3?) |
Related settings:
max_consecutive_failed_dag_runspauses a DAG automatically after N failed runs in a row.[scheduler] max_tis_per_querycontrols how many task instances the scheduler examines per loop. It is a throughput knob, not a limit.- With two or more schedulers,
parallelismapplies per scheduler, so the total capacity multiplies (see How do you scale and make the scheduler highly available?).
How to diagnose: open a task stuck in scheduled. The UI’s task-instance details, or airflow tasks failed-deps <dag_id> <task_id> <run_id>, list the unmet dependency, such as “pool full” or “max_active_tasks reached”. Then raise the limit that is actually the bottleneck. Raising parallelism does nothing when the pool is full. See the site’s guide on finding why tasks sit in scheduled or queued.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.configuration import conf
from airflow.sdk import dag, task
@dag(
schedule="@hourly", start_date=datetime(2026, 1, 1), catchup=True,
max_active_runs=3, # at most 3 runs of this DAG at once (catchup can't flood)
max_active_tasks=8, # at most 8 running task instances across those runs
max_consecutive_failed_dag_runs=5, # auto-pause after 5 failed runs in a row
)
def throttled_ingest():
@task(max_active_tis_per_dagrun=2, # per run: 2 copies of this task at once
max_active_tis_per_dag=4, # across all runs: 4 copies at once
pool="partner_api") # across ALL DAGs: pool slots
def fetch_page(page: int):
print("page", page)
fetch_page.expand(page=list(range(20)))
d = throttled_ingest()
if __name__ == "__main__":
t = d.get_task("fetch_page")
print("[core] parallelism:", conf.getint("core", "parallelism"),
"| max_active_tasks_per_dag default:", conf.getint("core", "max_active_tasks_per_dag"),
"| max_active_runs_per_dag default:", conf.getint("core", "max_active_runs_per_dag"))
print("DAG:", {"max_active_runs": d.max_active_runs, "max_active_tasks": d.max_active_tasks,
"max_consecutive_failed_dag_runs": d.max_consecutive_failed_dag_runs})
print("task:", {"per_dagrun": t.max_active_tis_per_dagrun, "per_dag": t.max_active_tis_per_dag, "pool": t.pool})
For this DAG, at most 4 fetch_page copies run at once, and only if the partner_api pool and the scheduler’s parallelism both have room.
Common mistakes:
- Turning on
catchup=Truefor an hourly DAG with a year-oldstart_dateand the defaultmax_active_runsof 16. - Using one huge pool as the only control and ignoring the DAG-level limits.
- Not knowing that
parallelismis per scheduler.
45. What is the Edge Executor, and when would you use it?
The EdgeExecutor, from the apache-airflow-providers-edge3 package, sends tasks to small edge workers that can run anywhere with outbound HTTPS to the API server: a factory, a branch office, another cloud or an on-premises data centre. Workers pull their jobs over HTTP, so you need no inbound firewall rules, no message broker and no database access. It usually runs next to Celery or Kubernetes as one of several executors.
How it works:
- The central scheduler queues jobs for the
EdgeExecutor. The API server exposes the edge API ([edge] api_enabled = True,[edge] api_url). - An edge worker started with
airflow edge worker -q <queues>polls for jobs, runs them with the Task SDK, and sends back heartbeats and logs over HTTPS. It authenticates with the shared[api_auth] jwt_secret. - Tasks are routed with
executor="EdgeExecutor"plus aqueuethat only the right site’s workers listen on. If the Edge Executor isn’t the default, both are needed. - On Airflow 3.2+, the provider registers its own database tables automatically. Older versions need
[database] external_db_managers. - From 3.2, multi-team mode can give each team its own Edge Executor and workers.
Requirements and limits:
- Each worker needs Airflow, the Task SDK, the edge3 provider and the libraries its tasks use. DAG files must be synced to it, for example by Git sync, because the worker parses them.
- Configuration must match the central site.
- Throughput and latency depend on HTTP polling. It suits tens to hundreds of remote tasks, not tens of thousands of short tasks a minute.
| Use Edge when | Use something else when |
|---|---|
| Data can’t leave a site, or the network only allows outbound connections | Everything runs in one cloud network (use Celery or Kubernetes) |
| You need hardware on site (OT systems, GPUs on premises) | You only need a different image (KubernetesPodOperator) |
| A few hybrid tasks in an otherwise central platform | The remote site runs its own full Airflow anyway |
Example
# Runtime: Apache Airflow 3.3 + apache-airflow-providers-edge3 — airflow.cfg on central site AND workers
[core]
executor = CeleryExecutor,airflow.providers.edge3.executors.EdgeExecutor
[api_auth]
jwt_secret = <same random secret everywhere>
[edge]
api_enabled = True
api_url = https://airflow.example.internal/edge_worker/v1/rpcapi
Common mistakes:
- Expecting edge workers to work without the DAG files or the tasks’ libraries.
- Setting
queue="site_a"but notexecutor="EdgeExecutor"when Edge isn’t the default executor. - Treating it as a way around security reviews. The worker still runs arbitrary DAG code inside that network.
Learn more: Airflow Executors, Pools and Scaling
46. How do you scale and make the scheduler highly available?
Run two or more schedulers against a Postgres or MySQL 8+ metadata database. They coordinate through row locks (SELECT … FOR UPDATE SKIP LOCKED), so they are all active at once, and if one dies the others carry on. Scale the DAG processor and the triggerer separately. Tune the scheduler loop with max_dagruns_per_loop_to_schedule, max_tis_per_query and parallelism, and check the database first when things get slow.
In Airflow 3 there are several components to scale, not one:
| Component | Scales by | Bottleneck symptoms |
|---|---|---|
| Scheduler | More replicas (active-active) | Runs late to start, tasks slow to queue |
| DAG processor | parsing_processes, more replicas, separate bundles |
DAGs update slowly, parse timeouts (see Why is DAG parsing slow, and how do you keep parse time low?) |
| Triggerer | Replicas × [triggerer] capacity (1000) |
Deferred tasks resume late |
| API server | Replicas, workers | Slow UI, slow Execution API calls from tasks |
| Executor/workers | Celery workers, K8s nodes | Tasks sit in queued |
| Metadata DB | Instance size, connection pooling (PgBouncer), cleanup | Everything is slow |
Scheduler essentials:
- HA needs
[scheduler] use_row_level_locking = True(the default) and a database withSKIP LOCKED. SQLite supports neither, so it is for local development only. parallelismis per scheduler. Three schedulers with 32 each can have 96 task instances running or queued.- Loop tuning:
max_dagruns_to_create_per_loop(10),max_dagruns_per_loop_to_schedule(20) andmax_tis_per_query(16). Raise them carefully; larger batches mean longer locks. - Database hygiene:
airflow db clean --clean-before-timestamp ...trims old runs, task instances, XComs and logs metadata. Large tables slow every query the scheduler makes. - Health checks:
airflow jobs check --job-type SchedulerJob --allow-multiple, which can serve as a liveness probe, plusscheduler_heartbeatmetrics.
Before adding schedulers, check whether the problem is parsing (top-level code), the database, or concurrency limits (see How do Airflow’s concurrency limits stack, from parallelism down to a single task?). A second scheduler fixes none of those.
Example
# Runtime: Apache Airflow 3.3 CLI (run on any host with the deployment's config)
airflow jobs check --job-type SchedulerJob --allow-multiple --limit 5 # exits 0 if a scheduler is alive
airflow jobs check --job-type TriggererJob --allow-multiple
airflow jobs check --job-type DagProcessorJob --allow-multiple
airflow db clean --clean-before-timestamp "$(date -u -d '-90 days' +%Y-%m-%dT%H:%M:%S)" --yes
Common mistakes:
- Thinking only one scheduler can be active, an active-passive model. Since 2.0, all schedulers are active.
- Running HA schedulers on SQLite, or on MySQL 5.x without
SKIP LOCKED. - Scaling schedulers to fix slow parsing, which is the DAG processor’s job in Airflow 3.
Learn more: Airflow Scheduling: Intervals, Logical Dates, Catchup, Timetables and Assets
47. What are the Task SDK and the Task Execution API, and why do they matter?
In Airflow 3, task code talks to Airflow only through the Task SDK (airflow.sdk). A supervisor process on the worker sends those calls over HTTP to the API server’s Task Execution API, using a short-lived token for that one task. So workers no longer need database passwords. This improves security, lets the SDK be upgraded separately, enables remote workers (Edge), and opens the door to task SDKs in other languages (Java and Go, experimental in 3.3).
Airflow 2: every worker had the DB connection string. Any task could open an ORM session and read or change anything in the database.
Airflow 3:
- The executor starts the supervisor on the worker. The supervisor starts the task process and relays its requests: Variables, Connections, XCom, state changes, heartbeats and logs.
- The supervisor calls the Execution API (
/execution/...on the API server) with a token scoped to that task instance. - The task process sees a stable interface:
airflow.sdkclasses,get_current_context(),Variable,Connection, XCom andoutlet_events.
What this means for DAG authors:
| Old pattern | Airflow 3 replacement |
|---|---|
from airflow.settings import Session in task code |
Not supported. Use the SDK, or the REST API / Python client for admin operations |
DagRun.find(...) or TaskInstance queries in a task |
The context (dag_run, ti), or the REST API |
from airflow.models import Variable |
from airflow.sdk import Variable |
Raising airflow.exceptions.AirflowSkipException |
airflow.sdk.exceptions |
Operational effects: API-server capacity now affects running tasks. Network rules must allow workers to reach the API server. [core] execution_api_server_url must be correct on the workers. The Task SDK can be upgraded on a different cadence from airflow-core (since 3.1). Note that the DAG processor and the triggerer still run user code with DB access, so that boundary is not complete.
The 3.3 Coordinator layer (AIP-108) lets @task.stub(queue=...) tasks run in Java or Go runtimes that use the same Execution API. Product behaviour changes; checked October 2026.
Example
# Runtime: Python 3.11, Apache Airflow 3.3
from datetime import datetime
from airflow.sdk import Variable, dag, get_current_context, task
@dag(schedule=None, start_date=datetime(2026, 1, 1), catchup=False)
def sdk_boundary():
@task
def produce(dag_run=None) -> dict:
# Each call below is a Task SDK call that the worker's supervisor sends to the
# Execution API (HTTP + a short-lived JWT for this task instance) - no DB session.
Variable.set("last_seen_run", dag_run.run_id)
return {"rows": 10}
@task
def consume(payload: dict):
ctx = get_current_context()
prev = ctx["ti"].xcom_pull(task_ids="produce")
print("variable ok:", Variable.get("last_seen_run") == ctx["dag_run"].run_id,
"| xcom:", prev, "| arg:", payload, "| try:", ctx["ti"].try_number)
consume(produce())
dag_obj = sdk_boundary()
if __name__ == "__main__":
print(dag_obj.test().state)
dag.test() runs in one process that has the database configured. An ORM query inside a task would therefore “work” locally but fail on real workers, which get no DB credentials. Catch it in code review, and with ruff --select AIR in CI (see Walk through migrating a real Airflow 2 deployment to Airflow 3. What breaks first?), not with dag.test().
48. How do you design DAGs so any past interval can be reprocessed safely?
Make every run depend only on its own interval. Read only data inside [data_interval_start, data_interval_end), and replace that interval’s output in one transaction: partition overwrite, delete then insert, or MERGE. Never use now(), “latest” reads or shared state that changes. Then clears, retries, catchup and backfills give the same result whenever they run. How do you make Airflow tasks idempotent and safe to retry? covers the single task; this is the same idea for a whole DAG.
A checklist for a design review:
| Rule | Breaks when ignored |
|---|---|
Time comes from the run (data_interval_*, logical_date, or a partition key), never from now() |
A backfill processes today’s data 90 times |
Half-open intervals >= start AND < end |
Boundary rows are counted twice or missed |
Output is keyed by the interval: .../dt=2026-03-01/, WHERE day = ... |
Reruns append duplicates |
Replace atomically: partition overwrite, DELETE+INSERT in one transaction, MERGE, INSERT OVERWRITE |
A half-written partition is visible |
| Inputs are frozen or versioned: snapshot tables, time travel, immutable raw zone | Reprocessing gives different numbers from the original run |
| Reference data “as of” the interval: SCD2, effective dates | Old days are re-priced with today’s FX rates |
Side effects (emails, API posts) deduplicated by run_id or interval |
Customers get duplicate notifications |
Writes per interval don’t conflict; max_active_runs set |
Parallel backfill runs fight over the same table |
Choose the timetable on purpose (see CronTriggerTimetable vs CronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?) |
Zero-length intervals select nothing |
Late data has two remedies. Re-run a trailing window (lookback days, MERGE by key), or schedule on assets so runs start when data lands. See How does asset-aware scheduling work, and how do you combine asset conditions? and What is asset partitioning in Airflow 3.2+, and when would you use it?. For non-time-based runs (logical_date=None), make the unit of work explicit with a param or partition key (see Manual and API-triggered runs in Airflow 3: why can logical_date be None?).
Example
# Runtime: Python 3.11, Apache Airflow 3.3 (sqlite3 stands in for the warehouse)
import os
import sqlite3
import tempfile
from datetime import datetime, timezone
from airflow.sdk import dag, task
from airflow.timetables.interval import CronDataIntervalTimetable
WAREHOUSE = os.path.join(tempfile.gettempdir(), "af_reprocess_demo.db")
@dag(schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"), # explicit interval semantics
start_date=datetime(2026, 1, 1), catchup=False, max_active_runs=1)
def daily_revenue_rebuild():
@task
def rebuild_partition(data_interval_start=None, data_interval_end=None):
day = data_interval_start.strftime("%Y-%m-%d") # derived from the run, never from now()
con = sqlite3.connect(WAREHOUSE)
with con: # one transaction: delete + insert
con.execute("CREATE TABLE IF NOT EXISTS orders (id INT, ts TEXT, amount REAL)")
con.execute("CREATE TABLE IF NOT EXISTS revenue_daily (day TEXT, revenue REAL)")
if con.execute("SELECT COUNT(*) FROM orders").fetchone()[0] == 0:
con.executemany("INSERT INTO orders VALUES (?,?,?)", [
(1, "2026-03-01T10:00:00", 40.0), (2, "2026-03-01T23:59:59", 60.0),
(3, "2026-03-02T00:00:00", 99.0)]) # belongs to the NEXT day
con.execute("DELETE FROM revenue_daily WHERE day = ?", (day,)) # replace, never append
con.execute("""INSERT INTO revenue_daily
SELECT ?, COALESCE(SUM(amount), 0) FROM orders
WHERE ts >= ? AND ts < ?""", # half-open interval [start, end)
(day, data_interval_start.strftime("%Y-%m-%dT%H:%M:%S"),
data_interval_end.strftime("%Y-%m-%dT%H:%M:%S")))
rows = con.execute("SELECT * FROM revenue_daily ORDER BY day").fetchall()
con.close()
print("interval:", data_interval_start, "->", data_interval_end, "| revenue_daily:", rows)
rebuild_partition()
dag_obj = daily_revenue_rebuild()
if __name__ == "__main__":
if os.path.exists(WAREHOUSE):
os.remove(WAREHOUSE)
# A manual run's interval is inferred by the timetable: for CronDataIntervalTimetable a run
# triggered "at" 2026-03-02 00:00 covers the interval that just ended, i.e. 1 March.
for _ in range(2): # run the same interval twice: same end state
dag_obj.test(logical_date=datetime(2026, 3, 2, tzinfo=timezone.utc))
The second run gives identical output, and the order at exactly midnight on 2 March is left for the next interval. The inferred interval shows why Q537 warns against assuming a manual run’s interval equals its logical date.
Common mistakes:
INSERT INTO ... SELECTwith no delete or overwrite step.- Joining to “current” dimension tables when reprocessing history.
- Reading “the latest file” in the landing bucket instead of the file for the run’s interval.
49. Walk through migrating a real Airflow 2 deployment to Airflow 3. What breaks first?
Upgrade to the latest 2.x first, then clean and back up the metadata database. Fix DAG code with ruff check --select AIR3 (AIR301/302 for breaking changes, AIR311/312 for recommended ones). Install the standard provider and remove any direct database access from tasks. Run airflow config update --fix and airflow db migrate, then start the new components, including a separate DAG processor. What breaks first: removed imports, removed context keys and changed scheduling defaults.
Q47 lists what changed, and the site has a migration guide. This question is the runbook, with the traps that show up in practice:
| Step | Detail |
|---|---|
| 1. Prerequisites | On 2.7+ (latest 2.x recommended). Supported Python. No SubDAGs, SLAs or SequentialExecutor |
| 2. DB | airflow db clean to shrink the history (migrations on large tables are slow). Back up. airflow dags reserialize must show no errors |
| 3. Code | ruff check dags/ --select AIR3 --fix (--unsafe-fixes for import moves, plus F401 to drop dead imports) |
| 4. Providers | Install apache-airflow-providers-standard (Bash, Python and Empty operators, sensors) |
| 5. DB access | Rewrite tasks that use Session, DagRun.find or TaskInstance queries to use the context or the REST API (see What are the Task SDK and the Task Execution API, and why do they matter?) |
| 6. Config | airflow config update, then --fix. webserver settings move to api / apiServer in the Helm chart |
| 7. Components | airflow api-server, airflow dag-processor (now required), scheduler, triggerer |
| 8. Plugins | Flask-AppBuilder views need the FAB provider or a rewrite as FastAPI/React plugins |
Behaviour changes that pass CI but break at run time:
- Removed context keys.
execution_date,next_ds,prev_ds,yesterday_ds,confand others are gone. A callable that takesexecution_datefails withTypeErrorwhen it runs (output below). catchup_by_default=False, and cron strings useCronTriggerTimetable. Decidecreate_cron_data_intervalsbefore upgrading (seeCronTriggerTimetablevsCronDataIntervalTimetable: what changed in Airflow 3, and when do you write a custom timetable?).- Manual and asset runs can have
logical_date=None(see Manual and API-triggered runs in Airflow 3: why canlogical_datebeNone?). airflow.datasetscan no longer be imported in 3.3, even though ruff labels the move AIR311 (“still works”).- SLAs are replaced by Deadline Alerts (see SLAs were removed in Airflow 3. How do Deadline Alerts replace them?). CeleryKubernetesExecutor is replaced by multiple executors (see How do multiple executors work, and how do you route a task to a specific one?).
Example
# Runtime: Airflow 2-style DAG file, before migration (legacy/old_style.py)
from datetime import datetime
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.datasets import Dataset
from airflow.models import Variable
orders = Dataset("s3://lake/orders")
def _load(execution_date, **context):
bucket = Variable.get("bucket")
print(execution_date, bucket)
with DAG("old_style", schedule_interval="@daily", start_date=datetime(2024, 1, 1)) as dag:
PythonOperator(task_id="load", python_callable=_load, outlets=[orders])
After ruff, the imports read from airflow.sdk import Asset, DAG, Variable and from airflow.providers.standard.operators.python import PythonOperator. Changing execution_date to logical_date, or to data_interval_start, completes the fix. That last step is why dag.test() belongs in the migration CI as well as linting.
In depth: What changed in Airflow 3, and how would you migrate Airflow 2 DAGs?
50. What are zombie tasks (heartbeat timeouts), and how do you debug them?
A zombie, now called a task heartbeat timeout, is a task the database shows as running while its process is actually dead, for example after an out-of-memory kill, an evicted pod or a failed machine. The scheduler notices that the heartbeats stopped for longer than task_instance_heartbeat_timeout (300 seconds), then fails or retries the task. The real fix is to find out why the process died, usually memory, and to make the task safe to rerun.
How detection works in Airflow 3: the worker’s supervisor sends heartbeats through the Execution API. If they stop, the scheduler, checking every task_instance_heartbeat_timeout_detection_interval (10 s), marks the task failed, or up_for_retry if it has retries left, and records the reason.
Common causes and evidence:
| Cause | Evidence |
|---|---|
| OOM kill | Pod OOMKilled in kubectl describe; dmesg on VMs; the log stops suddenly mid-task |
| Pod eviction or node scale-down | Kubernetes events; often during cluster-autoscaler downsizing |
| Worker restart during a deploy | It happens at deploy times; check the Celery warm-shutdown settings |
| Liveness probe killed the worker | Probe failures in the events |
| Supervisor can’t reach the API server | API server overloaded or network policy; heartbeat errors in the worker logs |
Related timeouts, which people often mix up:
| Setting | Fires when |
|---|---|
task_instance_heartbeat_timeout (300 s) |
A running task’s heartbeat stops |
[scheduler] task_queued_timeout (600 s) |
A task stays queued too long |
execution_timeout (task) |
One try runs too long, even with a healthy heartbeat |
dagrun_timeout (DAG) |
The whole run is too long |
[dag_processor] dag_file_processor_timeout (50 s) |
Parsing one file takes too long |
Prevention: give tasks resource requests and limits, stream data instead of loading it all into memory, use KubernetesPodOperator for heavy work, and make tasks idempotent so an automatic retry is harmless (see How do you make Airflow tasks idempotent and safe to retry?). The docs give a recipe for reproducing heartbeat timeouts locally: set a long heartbeat interval and a very short timeout.
Example
# Runtime: Python 3.11, Apache Airflow 3.3 — print the timeouts that decide when a task is declared dead/stuck
from airflow.configuration import conf
for section, key in [("scheduler", "task_instance_heartbeat_timeout"),
("scheduler", "task_instance_heartbeat_timeout_detection_interval"),
("scheduler", "task_queued_timeout"),
("dag_processor", "dag_file_processor_timeout"),
("sensors", "default_timeout")]:
print(f"[{section}] {key} = {conf.get(section, key)}")
Common mistakes:
- Raising
task_instance_heartbeat_timeoutto “fix” zombies. That only hides dead tasks for longer. - Confusing
execution_timeoutwith the heartbeat timeout. - Retrying a non-idempotent task that was killed halfway through its writes.
Progress is saved in this browser only. No account needed.

