Skip to content
Bronze 5 min read · Templates 1 practice problem ↓

Templates and idempotent reruns

A nightly pipeline must process a different day each night, without editing the code. Templates fill in values such as the run's date when the task runs. This lesson shows which arguments are templated, the variables you can use, and the traps.

Pipelines in production · Airflow · Bronze · Tasks, lesson 2 of 2

Read first: Schedules and logical dates (skip if you know it)

In plain words first

A form letter says "Dear ____, your order of ____ has shipped". The blanks are filled in when each letter is sent. A template field in Airflow is that blank, and {{ ds }} is filled in with the run's date when the tasktask: One step of a DAG, such as running a query or calling an API. Each run of a task for one date is a task instance. Learn more → starts.

Templates are rendered when the task runs

Some operatoroperator: A ready-made kind of task: BashOperator runs a command, PythonOperator a function. You make a task by giving an operator its arguments. Learn more → arguments are template fields: bash_command, the arguments of a TaskFlowTaskFlow: Airflow's decorator style: @task turns a Python function into a task, and return values pass between tasks automatically. Learn more → call, op_args and op_kwargs of a PythonOperator, the SQL of SQL operators. Airflow renders them with Jinja just before the task runs, with that run's context. Arguments that are not template fields are passed as written, braces and all.

Python · dags/plays_partition.py · one partition per run, named from the run
import pendulum
from airflow.sdk import DAG
from airflow.providers.standard.operators.bash import BashOperator

with DAG(
    dag_id="plays_partition",
    schedule="0 3 * * *",
    start_date=pendulum.datetime(2026, 2, 27, tz="UTC"),
    catchup=True,
):
    BashOperator(
        task_id="load",
        bash_command=(
            "load_plays --partition dt={{ ds_nodash }}"
            " --from {{ data_interval_start | ds }}"
            " --report-month {{ logical_date.strftime('%Y-%m') }}"
            " --week-ago {{ macros.ds_add(ds, -7) }}"
        ),
    )

What the schedulerscheduler: The Airflow process that reads DAG files, creates runs when they are due, and queues the tasks whose upstream tasks are done. Learn more → does · deployed Feb 27, 00:00 UTC · grid as of Mar 1, 04:00 UTC · 0 3 * * * (CronTriggerTimetable)

task \ runFeb 27
03:00
Feb 28
03:00
Mar 1
03:00
load

success· the bar on top is the run's state; a number is how many tries

Command of load, run by run

Feb 27, 03:00  load_plays --partition dt=20260227 --from 2026-02-27 --report-month 2026-02 --week-ago 2026-02-20
Feb 28, 03:00  load_plays --partition dt=20260228 --from 2026-02-28 --report-month 2026-02 --week-ago 2026-02-21
Mar 1, 03:00  load_plays --partition dt=20260301 --from 2026-03-01 --report-month 2026-03 --week-ago 2026-02-22

What the context holds

VariableValue for the run on 1 March at 03:00 (default timetable)
ds, ds_nodash2026-03-01, 20260301
logical_dateA datetime: 2026-03-01 03:00 UTC (use .strftime(...), | ds)
data_interval_start, data_interval_endBoth 2026-03-01 03:00 with the default timetable
ts, ts_nodash2026-03-01T03:00:00+00:00, 20260301T030000
paramsThe DAGDAG: A pipeline in Airflow: a set of tasks and the order they run in, defined in a Python file and run on a schedule. Learn more →'s params, overridable when triggering a run
ti, dag_run, run_idThe task instancetask instance: One run of one task for one DAG run, with its own state (queued, running, success, failed) and its own log. Learn more → and the run
macrosds_add, ds_format, datetime, timedelta
var.value.NAME, conn.NAMEAn Airflow Variable, a connection
Watch out: Airflow 3 removed the old shortcuts: execution_date, prev_ds, next_ds, yesterday_ds, tomorrow_ds and their _nodash forms. A template that still uses one fails with UndefinedError when the task runs. Use logical_date, macros.ds_add(ds, -1) and the data interval instead.

Idempotent reruns

A task is idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more → when running it again for the same run gives the same result. That is what makes retries, reruns from the UI and backfillsbackfill: Running a DAG for past dates on purpose, to fill in or redo history. Learn more → safe. Two rules get you most of the way:

  1. 1
    Take every date from the run, never from the clock. {{ ds }} on a rerun of 1 March is still 2026-03-01; datetime.now() inside the task is whatever day you rerun it.
  2. 2
    Replace, do not append. Write the run's partition with an overwrite (INSERT OVERWRITE ... PARTITION (dt=...), a Delta replaceWhere, delete-then-insert in one transaction). An append on a rerun doubles the day.

With both, "rerun last Tuesday" is a button in the UI instead of an incident.

Common mistakes

  • A template in an argument that is not a template field — The braces reach the command unrendered.
  • {{ prev_ds }} or {{ execution_date }} in Airflow 3 — Removed: the task fails with UndefinedError.
  • datetime.now() inside a task to pick the day — A rerun or backfill processes the wrong day.
  • Appending a day's rows on every run — A retry or rerun duplicates the day.

Key takeaways

  • Template fields are rendered just before the task runs, with that run's context.
  • Use ds, logical_date, the data interval and macros; Airflow 3 removed prev_ds and friends.
  • Idempotent = dates from the run + overwrite instead of append.
  • Idempotent tasks make retries, reruns and backfills safe.

Interview prep

THE QUESTION

"What makes an Airflow task safe to rerun?"

It derives everything it touches from the run, not the clock: the dates come from ds, logical_date or the data interval, so a rerun of a past day processes that day. And it replaces its output instead of appending: overwrite the run's partition, or delete and insert in one transaction, or MERGE on a key. Then retries, UI reruns and backfills give the same result as the first run. I would also mention keeping side effects such as emails or API posts in separate tasks, guarded so a rerun does not repeat them blindly.

Avoid: "use datetime.today() to get the date to process". A rerun or backfill then processes the wrong day.

Follow-ups · answer out loud, then open

Follow-up"How do you get last month's first day in a template?"
From the run's logical date, never the clock: {{ logical_date.subtract(months=1).start_of('month') | ds }} with pendulum, or a user-defined macro that encodes the rule once for all DAGs.
Scenario"A task appends a day's rows to a table. It was retried after a timeout and the day doubled. How do you fix it for good?"
Make the write idempotent: overwrite the run's partition (INSERT OVERWRITE, a Delta replaceWhere), or delete that day and insert in one transaction, or MERGE on a key. Then a retry, rerun or backfill always leaves exactly one copy.
Trap"{{ ds }} inside a Python function's body is rendered."
Templates are rendered only in template fields, before the task runs. In Python code, take ds or logical_date as a parameter instead.

Check yourself

3 questions

When is {{ ds }} in bash_command rendered?

Show the answer

Just before the task runs. Templates are rendered with the run's context at run time.

A template uses {{ yesterday_ds }} in Airflow 3. What happens?

Show the answer

The task fails with UndefinedError. The variable was removed in Airflow 3.

Which write makes a daily task idempotent?

Show the answer

Overwrite the day's partition. Overwriting the run's partition gives the same result on every rerun.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Failures · 5 min read
Retries, timeouts and callbacks
Which failures to retry, how retry_delay and backoff space them, timeouts, and failing fast.

Related lessons

Previous: Operators and TaskFlow

Primary sources: Templates reference · Best practices