How a Python file becomes a scheduled run
Apache Airflow is not a workflow engine that stores jobs in a web console. It is a scheduler that reads Python files, turns them into directed graphs, and then continuously decides which nodes are allowed to move. The loop has four stages: parse, schedule, queue, execute. The scheduler re-parses every DAG file on a short interval, writes task instances into a metadata database, marks the ones whose upstream dependencies are satisfied as ready, and hands them to a worker pool.
That design has one immediate consequence for authors: module-level code runs on every parse cycle, dozens of times an hour, for every DAG in the folder. If your file opens a warehouse connection, downloads a model, or queries an API at import time, you have just made the scheduler slower for every other pipeline sharing that process. Treat the DAG file as a declarative manifest. Cheap imports, heavy work inside the callable.
After this lesson you should be able to read any DAG file and predict its run history without opening the UI, choose between a sensor and a short sleep, and recognise the configuration mistakes that turn a quiet pipeline into a pager incident.
The execution date trap
Every confusion about Airflow schedules starts here: the execution date is the beginning of the period a run covers, not the wall-clock moment the run starts. A @daily DAG that fires at 00:05 on 16 January carries execution date 15 January, because that run is responsible for the data between midnight and midnight on the 15th. The logical date is therefore always one interval behind, and macros such as {{ ds }} and {{ ds_nodash }} refer to that logical date, which is exactly what you want when you filter source tables by day.
The companion setting is catchup. When a DAG is first enabled after three weeks of inactivity, catchup mode queues every missed interval back to start_date, which is a legitimate backfill when intentional and an outage when it is not. Production pipelines almost always set catchup=False and let a manual backfill clear historical dates when the business asks for one.
| Setting | What it controls | Default | Production choice |
|---|---|---|---|
schedule | Interval or timetable driving runs | None | @daily or a cron expression |
start_date | First logical date eligible to run | Required | A fixed past timestamp, never datetime.now() |
catchup | Whether historical intervals queue up | True | False for serving pipelines |
max_active_runs | Concurrent DAG runs | Unlimited | 1 when writing to shared tables |
depends_on_past | Whether a run waits for the previous one | False | Only for strictly sequential loads |
misfire_grace_time | How late a run may still start | Platform | Set above your typical scheduler lag |
A fixed start_date deserves emphasis. Beginners set it to datetime.now() so the DAG starts "today", but that value is baked into the parsed file and shifts every parse cycle, so the schedule anchor moves and the scheduler can never settle. Pick a date in the past and let catchup be the thing that decides what runs.
Choosing the operator that fits the job
Operators are the atomic units of work, and picking the wrong one is the most common source of brittle DAGs. The rule of thumb is that each task should do one thing that a human could describe in a sentence and that could be re-run alone without corrupting anything.
| Operator | Best for | Failure isolation | Notes |
|---|---|---|---|
PythonOperator | In-process transformations | Per task | Keep functions importable and side-effect aware |
BashOperator | Shell commands, CLI tools | Per task | Quote arguments, avoid heredocs you cannot debug |
PostgresOperator / SQL operators | Set-based warehouse work | Per statement | Prefer this over shipping rows through Python |
SparkSubmitOperator | Cluster jobs | Per submission | Pass only small parameters, not data |
KubernetesPodOperator | Isolated, dependency-heavy steps | Per pod | Best isolation, slowest startup |
BranchPythonOperator | Conditional routing | Per decision | Follow with a join task using trigger rules |
S3KeySensor / HttpSensor | Waiting on external events | Polling | Use reschedule mode so slots free up |
DummyOperator | Structural placeholders | None | Useful for branch joins and visual grouping |
Notice what the table implies: a task that runs SQL inside the warehouse moves compute to where the data already lives, while a task that pulls ten million rows into a Python function moves ten million rows through the metadata database if you push them into XCom. Small scalars belong in XComs; large frames belong in files or tables referenced by path.
Writing a DAG you can re-run safely
The pipeline below extracts one day of orders, validates the batch, loads it, and notifies the owning team. It is deliberately small, but it carries the five habits that separate demo DAGs from ones that survive on-call: explicit timeouts, bounded retries with delay, a failure callback, idempotent task bodies, and catchup=False.
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.operators.bash import BashOperator
from airflow.utils.trigger_rule import TriggerRule
default_args = {
"owner": "analytics-eng",
"retries": 3,
"retry_delay": timedelta(minutes=10),
"retry_exponential_backoff": True,
"execution_timeout": timedelta(hours=1),
"email_on_failure": True,
"email": ["analytics-eng@example.com"],
}
def extract_day(**context):
"""Pull exactly one logical day of orders and record the row count."""
import sqlite3
day = context["logical_date"].date().isoformat()
conn = sqlite3.connect("warehouse.db")
rows = conn.execute(
"SELECT order_id, customer_id, amount, status FROM orders "
"WHERE order_date = ?",
(day,),
).fetchall()
conn.close()
context["ti"].xcom_push(key="row_count", value=len(rows))
return rows
def validate_batch(**context):
"""Fail fast on empty or negative-amount batches."""
rows = context["ti"].xcom_pull(task_ids="extract_day")
if not rows:
raise ValueError("No rows extracted; check upstream load")
bad = [r for r in rows if r[2] is None or r[2] < 0]
if bad:
raise ValueError(f"{len(bad)} rows failed the amount check")
def load_day(**context):
"""Append the batch keyed on order_id so re-runs do not duplicate rows."""
import sqlite3
rows = context["ti"].xcom_pull(task_ids="extract_day")
conn = sqlite3.connect("warehouse.db")
conn.executemany(
"INSERT OR REPLACE INTO orders_fact VALUES (?, ?, ?, ?)", rows
)
conn.commit()
conn.close()
with DAG(
dag_id="daily_order_load",
default_args=default_args,
schedule="0 2 * * *",
start_date=datetime(2025, 1, 1),
catchup=False,
max_active_runs=1,
tags=["orders", "core"],
) as dag:
extract = PythonOperator(task_id="extract_day", python_callable=extract_day)
validate = PythonOperator(
task_id="validate_batch", python_callable=validate_batch
)
load = PythonOperator(task_id="load_day", python_callable=load_day)
freshen = BashOperator(
task_id="refresh_metrics",
bash_command="echo refreshing metrics for {{ ds }}",
trigger_rule=TriggerRule.ALL_DONE,
)
extract >> validate >> load >> freshen
Two details matter more than they look. First, INSERT OR REPLACE makes the load idempotent, so a manual re-run of a past date produces the same table instead of doubling revenue. Second, the validation task sits between extract and load so a bad batch fails while it is still cheap to fix, rather than after it has polluted a fact table.
Sensors, branches, and waiting without wasting slots
Real pipelines wait: for a file to land, for an API to answer, for another team's load to finish. A sensor is the sanctioned way to wait, and the mode you pick decides whether your cluster idles. In poke mode a sensor holds a worker slot for the entire wait, polling on an interval. In reschedule mode the task releases its slot, records the poke time, and is re-queued later. Waiting an hour for a drop file should almost always be reschedule.
from airflow.sensors.filesystem import FileSensor
from airflow.operators.python import BranchPythonOperator
wait_for_drop = FileSensor(
task_id="wait_for_drop_file",
filepath="/incoming/orders/{{ ds }}.csv",
poke_interval=300,
timeout=3600,
mode="reschedule",
task_owner="analytics-eng",
)
def route_by_volume(**context):
"""Small days go to the fast path, big days to the Spark job."""
rows = context["ti"].xcom_pull(task_ids="extract_day") or []
return "load_day" if len(rows) < 500_000 else "spark_load"
route = BranchPythonOperator(task_id="route", python_callable=route_by_volume)
Branching needs a join. Downstream tasks that must run regardless of which branch was taken declare trigger_rule="none_failed_min_one_success"; otherwise the skipped branch silently skips everything after it, which is the single most common "why did my pipeline stop" ticket in Airflow support channels.
Concurrency, pools, and the limits you actually have
Four numbers govern throughput, and they nest. parallelism caps tasks running across the whole deployment, max_active_tasks_per_dag caps one run, a pool caps a named resource, and execution_timeout caps a single task. A Spark job competing with twelve other teams for four cluster slots should live in a pool with four slots; otherwise the first heavy day queue-spikes into hours of silent waiting that no dashboard shows.
Set execution_timeout everywhere. Without it, a task that hangs on a dead network connection holds a slot until a human notices. With it, the task fails, releases the slot, retries under policy, and surfaces in the same failure path as every other error.
Failures that explain themselves
When a run fails at 03:00, the value of your setup is measured by what the alert says. A on_failure_callback that logs the task id, run id, and a deep link to the grid view turns a two-minute triage into a thirty-second one. Pair it with on_retry_callback so transient errors are visible before they become incidents, and keep the failure message specific enough that the responder knows whether to rerun, roll back, or wake someone else.
â ī¸Reruns are not replays
Re-running a task only fixes things if the task body is idempotent. Anything that appends, increments, or sends external messages will produce a second effect on the second run. Make writes keyed and deduplicated, and move notifications into a task with trigger_rule that fires once per successful DAG run.
Common Mistakes
Setting start_date to datetime.now(), which shifts the schedule anchor on every parse
Fix: Use a fixed past date and control what runs with catchup and manual triggers
Shipping large result sets through XCom, which serialises them into the metadata database
Fix: Write frames to object storage and pass the path; keep XComs to counts, ids, and paths
Leaving sensors in poke mode so they hold worker slots for hours
Fix: Use mode="reschedule" with a sensible timeout so slots are released between pokes
Forgetting a join after a BranchPythonOperator, so one path silently stops the DAG
Fix: Declare trigger_rule="none_failed_min_one_success" on tasks that must run either way
Best Practices
- Keep every DAG to one logical workflow and group steps with TaskGroup instead of nested SubDAGs
- Configure retries, retry delay, execution_timeout, and a failure callback in default_args so nothing ships bare
- Set catchup=False and max_active_runs=1 for pipelines that write to shared tables
- Test locally with airflow dags test before you rely on the scheduler, then deploy through version control
- Log the inputs a task used â logical date, row counts, source path â so audits do not require archaeology
Interview Questions
Q1: What does the execution date mean for a daily DAG run?
It is the start of the period the run covers, so a run firing just after midnight on the 16th carries execution date the 15th and processes that day's data.
Q2: Difference between poke and reschedule sensor mode?
Poke keeps a worker slot for the whole wait and polls in place; reschedule releases the slot between pokes and is re-queued, which is far cheaper for long waits.
Q3: How do you prevent duplicate rows when a load is re-run?
Make the write idempotent â key on the business identifier and use insert-or-replace or merge semantics so a second run converges to the same state.
Q4: Why might a downstream task never run after a branch?
The unselected branch leaves its children in a skipped state, and a default trigger rule of all_success treats skipped upstream as not satisfied.
Key Takeaways
- Airflow parses DAG files continuously, so import-time work must stay cheap
- The execution date leads wall-clock time by one interval, and catchup decides whether missed intervals queue
- Prefer SQL and cluster operators over moving large data through Python and XCom
- Idempotent task bodies make manual reruns safe, and timeouts stop hung tasks from holding slots
- Branching requires an explicit join task, sensors should reschedule rather than poke, and failure callbacks should carry enough context to act on