Logical Dates, Partitions and Backfills
Backfill two weeks of history with Airflow 3. See a loader that reads the wall clock turn three green runs into one partition, backfill the interval-driven DAG from the first lab, rerun part of the range with each reprocess behaviour and prove every day exists exactly once. Then compare catch-up with backfills and see why a manual run is the wrong way to rerun a past day.
Contentsand lesson path
On this page
- The problem
- Step 1: Know which date a run is for
- Step 2: Backfill a loader that reads the clock
- Step 3: Backfill the interval-driven DAG
- Step 4: Rerun part of the range
- Step 5: Catch-up instead of a backfill
- Step 6: Why a manual run is not a rerun of a day
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Pipeline Orchestration
- What an Orchestrator Should and Should Not Do Concept · 20 min
- Lab: A First Airflow 3 DAG with the TaskFlow API Lab · 30 min
- Logical Dates, Partitions and Backfills Worked example · 25 min
- Lab: Retries, Sensors, Assets and Alerts Lab · 25 min
- The Asset-Centric Alternative: Dagster Worked example · 20 min
- Check: Orchestration Failure Scenarios Knowledge check · 8 questions
What you will learn
- Write tasks parameterized by logical date or partition so they are idempotent, and run catch-up and backfills over a past date range.
Prerequisites: ETL/ELT Pipeline Design
01. The problem
Finance wants region revenue for every day from 1 to 14 November. The orders_daily DAG from the first Airflow lab has so far only run for single days. A colleague has also written orders_wallclock, a loader that "loads yesterday". You need to fill the fourteen days, be able to rerun any of them safely, and prove that each day is in the table exactly once.
You work in the lab folder from that lesson, with airflow standalone running in terminal 2 and source env.sh done in terminal 1. Two words matter throughout. A partition is the slice of a table that one interval owns, here all rows with one day. A backfill creates runs for a range of past intervals, one run per interval, and lets the scheduler execute them like ordinary runs.
02. Step 1: Know which date a run is for
Every Airflow run carries several timestamps, and confusing them causes most date bugs.
data_interval_startanddata_interval_end: the window of data the run is responsible for. WithCronDataIntervalTimetable("0 0 * * *")a run covers one day, midnight to midnight.logical_date: the label of the run. For scheduled and backfill runs it equalsdata_interval_start. The template variable{{ ds }}is its date part.run_after: the earliest moment the run may start, here the end of the interval. Scheduled and backfill run IDs embed it, which is why the run for 1 November is calledbackfill__2026-11-02T00:00:00+00:00.
A task is idempotent when running it once or many times for the same interval leaves the target in the same state. The load task of orders_daily is: it deletes the partition for data_interval_start and inserts it again, in one transaction. That property is what makes the rest of this lesson safe. (Airflow 3.4 can also schedule by named partitions, with timetables such as CronPartitionTimetable, and its backfills then take partition dates; this lesson keeps to data intervals.)
03. Step 2: Backfill a loader that reads the clock
Here is the colleague's loader. It works every night in production, because at 00:05 on 3 November "yesterday" really is 2 November. Save it as airflow/dags/orders_wallclock.py.
"""A buggy loader: it asks the wall clock which day to load."""
import pendulum
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.sdk import CronDataIntervalTimetable, dag, task
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=pendulum.datetime(2026, 11, 1, tz="UTC"),
catchup=False,
)
def orders_wallclock():
@task
def load_yesterday(*, run_id):
day = pendulum.now("UTC").subtract(days=1).date() # BUG: today minus one
hook = PostgresHook(postgres_conn_id="warehouse")
with hook.get_conn() as conn, conn.cursor() as cur:
cur.execute("CREATE TABLE IF NOT EXISTS wallclock_loads "
"(day date PRIMARY KEY, loaded_by text)")
cur.execute("INSERT INTO wallclock_loads VALUES (%s, %s) ON CONFLICT (day) "
"DO UPDATE SET loaded_by = EXCLUDED.loaded_by", (day, run_id))
print(f"loaded {day} for run {run_id}")
load_yesterday()
orders_wallclock()airflow dags reserialize parses the DAG files now and stores them in the metadata database, instead of waiting for the DAG processor's next scan. Then unpause the DAG and backfill 1 to 3 November. airflow backfill create only creates the runs; the scheduler executes them, so it must be running. --max-active-runs 1 runs them one at a time.
airflow dags reserialize > /dev/null 2>&1
airflow dags list -o plain | awk '{print $1, $4}'
airflow dags unpause orders_wallclock > /dev/null
airflow backfill create --dag-id orders_wallclock \
--from-date 2026-11-01 --to-date 2026-11-03 --max-active-runs 1 > /dev/null 2>&1
./wait_for_runs.sh orders_wallclock backfill__ 3dag_id is_paused
orders_daily False
orders_wallclock True
orders_wallclock: 3 finished run(s) whose id starts with backfill__airflow dags list-runs orders_wallclock -o plain | awk '/backfill__/ {print $2, $3, $5}'
docker exec orch-pg psql -U lab -d warehouse -c "SELECT count(*) AS rows,
bool_and(day = current_date - 1) AS all_yesterday FROM wallclock_loads"backfill__2026-11-04T00:00:00+00:00 success 2026-11-03T00:00:00+00:00
backfill__2026-11-03T00:00:00+00:00 success 2026-11-02T00:00:00+00:00
backfill__2026-11-02T00:00:00+00:00 success 2026-11-01T00:00:00+00:00
rows | all_yesterday
------+---------------
1 | t
(1 row)Three green runs, each correctly labelled 1, 2 or 3 November, and one row (unpausing also created one scheduled run, for yesterday's interval, hidden by the filter): every run loaded the day before today. Nothing failed, so no alert would fire. This is the wall-clock bug: a task that takes its date from now() or date.today() gives the right answer only when it runs on schedule. Retries the next morning, reruns after a fix and backfills all process the wrong day. The fix is to read the date from the run, as orders_daily does with data_interval_start.
04. Step 3: Backfill the interval-driven DAG
First ask Airflow which runs a backfill of 1 to 14 November would consider. --dry-run prints them without creating anything; both dates are inclusive and are logical dates.
airflow backfill create --dag-id orders_daily \
--from-date 2026-11-01 --to-date 2026-11-14 --dry-run > dry-run.txt 2>&1
grep -oE '^\| 2026-[0-9-]+' dry-run.txt | cut -c3- | sed -n '1p;$p'
grep -c '^| 2026' dry-run.txt2026-11-01
2026-11-14
14Now create the backfill with at most three runs active at a time. The limit protects the source and the warehouse, and it leaves scheduler capacity for regular runs; a backfill's --max-active-runs applies independently of the DAG's own max_active_runs. Save the query below as check.sql. It reduces the fourteen days to one line, including a fingerprint: the start of an MD5 hash over every row in a fixed order, which changes if any row is missing, repeated or different.
-- One line that changes if any row for 1-14 November is missing, repeated or different
SELECT count(*) AS rows, count(DISTINCT day) AS days, sum(revenue) AS revenue,
left(md5(string_agg(day || region || orders || revenue, ','
ORDER BY day, region)), 12) AS fingerprint
FROM region_revenue
WHERE day BETWEEN '2026-11-01' AND '2026-11-14';airflow backfill create --dag-id orders_daily \
--from-date 2026-11-01 --to-date 2026-11-14 --max-active-runs 3 > backfill.log 2>&1
./wait_for_runs.sh orders_daily backfill__ 14
docker exec -i orch-pg psql -U lab -d warehouse < check.sqlorders_daily: 14 finished run(s) whose id starts with backfill__
rows | days | revenue | fingerprint
------+------+----------+--------------
42 | 14 | 78193.33 | 7b0b3f2ea93d
(1 row)Fourteen days, three regions each, forty-two rows. Each run processed exactly its own interval because every task reads data_interval_start, and the runs did not interfere with each other because each one writes only its own partition.
05. Step 4: Rerun part of the range
Suppose the revenue rule changed for 5 to 7 November. What if you create the same backfill again? The reprocess behaviour decides. The default, none, creates runs only for dates that have no run yet, whatever the state of an existing one; failed also reruns dates whose run failed; completed reruns every date. A date whose run is still queued or running is never duplicated.
First, a DAG can have only one unfinished backfill, and the scheduler marks a backfill finished on a 30-second timer after its last run ends; a backfill create in between fails with AlreadyRunningBackfill. The 3.4 CLI cannot list backfills, so save this helper as wait_for_backfill.sh. It reads Airflow's internal tables, which may change between versions; real scripts should call GET /api/v2/backfills.
#!/usr/bin/env bash
# Waits until Airflow's metadata database has no unfinished backfill.
sql='select count(*) from backfill where completed_at is null'
for attempt in $(seq 1 60); do # at most five minutes
[ "$(docker exec orch-pg psql -U lab -d airflow -Atc "$sql")" = 0 ] && exit 0
sleep 5
done
echo "a backfill is still unfinished after five minutes" >&2
exit 1chmod +x wait_for_backfill.sh && ./wait_for_backfill.sh
airflow backfill create --dag-id orders_daily \
--from-date 2026-11-05 --to-date 2026-11-07 > backfill-2.log 2>&1
docker exec orch-pg psql -U lab -d airflow -Atc "select logical_date::date,
exception_reason from backfill_dag_run where backfill_id =
(select max(id) from backfill) order by 1"
airflow dags list-runs orders_daily -o plain | grep -c ' backfill__'
LOGS=airflow/logs/dag_id=orders_daily/run_id=backfill__2026-11-06T00:00:00+00:00
ls "$LOGS/task_id=load"2026-11-05|already exists
2026-11-06|already exists
2026-11-07|already exists
14
attempt=1.logStill fourteen backfill runs and a single attempt for 5 November's load: every date already had a run, so nothing ran again. backfill-2.log says Created backfill Dag run for each date, but the backfill's records show each one skipped as already exists. With completed, Airflow clears the existing runs for those dates and the scheduler runs them again as new attempts.
./wait_for_backfill.sh
airflow backfill create --dag-id orders_daily --from-date 2026-11-05 \
--to-date 2026-11-07 --reprocess-behavior completed > backfill-3.log 2>&1
./wait_for_runs.sh orders_daily backfill__ 14
LOGS=airflow/logs/dag_id=orders_daily/run_id=backfill__2026-11-06T00:00:00+00:00
ls "$LOGS/task_id=load"
docker exec -i orch-pg psql -U lab -d warehouse < check.sqlorders_daily: 14 finished run(s) whose id starts with backfill__
attempt=1.log
attempt=2.log
rows | days | revenue | fingerprint
------+------+----------+--------------
42 | 14 | 78193.33 | 7b0b3f2ea93d
(1 row)attempt=2.log shows the second attempt, and the fingerprint is identical to step 3: three days were rewritten and the table ended in exactly the same state. If load appended instead of replacing its partition, these three days would now be doubled.
06. Step 5: Catch-up instead of a backfill
A backfill is something you ask for. Catch-up is the scheduler doing it on its own: with catchup=True, it creates a run for every interval between start_date (or the last run) and now that has not run yet, in date order, limited by max_active_runs. It also happens when a paused DAG is unpaused. Airflow 3 defaults to catchup=False, because a new DAG with an old start_date and catch-up on can start hundreds of runs. Save this small DAG as airflow/dags/catchup_demo.py; its end_date keeps the demo to a closed range.
"""catchup=True: the scheduler creates one run per missed interval."""
import pendulum
from airflow.sdk import CronDataIntervalTimetable, dag, task
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=pendulum.datetime(2026, 11, 1, tz="UTC"),
end_date=pendulum.datetime(2026, 11, 4, tz="UTC"), # a closed range for the demo
catchup=True,
max_active_runs=2,
)
def catchup_demo():
@task
def show(*, data_interval_start, data_interval_end):
print(f"interval {data_interval_start} to {data_interval_end}")
show()
catchup_demo()airflow dags reserialize > /dev/null 2>&1
airflow dags unpause catchup_demo > /dev/null
./wait_for_runs.sh catchup_demo scheduled__ 4
airflow dags list-runs catchup_demo -o plain | awk 'NR > 1 {print $2, $3, $5}' | sort
grep -ho 'interval [^"]*' airflow/logs/dag_id=catchup_demo/*/task_id=show/*.log | sortcatchup_demo: 4 finished run(s) whose id starts with scheduled__
scheduled__2026-11-02T00:00:00+00:00 success 2026-11-01T00:00:00+00:00
scheduled__2026-11-03T00:00:00+00:00 success 2026-11-02T00:00:00+00:00
scheduled__2026-11-04T00:00:00+00:00 success 2026-11-03T00:00:00+00:00
scheduled__2026-11-05T00:00:00+00:00 success 2026-11-04T00:00:00+00:00
interval 2026-11-01 00:00:00+00:00 to 2026-11-02 00:00:00+00:00
interval 2026-11-02 00:00:00+00:00 to 2026-11-03 00:00:00+00:00
interval 2026-11-03 00:00:00+00:00 to 2026-11-04 00:00:00+00:00
interval 2026-11-04 00:00:00+00:00 to 2026-11-05 00:00:00+00:00Unpausing alone created four runs. The last one has logical date 4 November, the end_date: the bound applies to the start of each interval. Catch-up suits a DAG designed to rebuild its history; for one-off history, a backfill with an explicit range and limit is easier to control.
07. Step 6: Why a manual run is not a rerun of a day
It is tempting to rerun a day by clicking Trigger or running airflow dags trigger. In Airflow 3 a manual run started without a logical date has none, and for this timetable no data interval either, so the tasks that ask for one cannot start.
airflow dags trigger orders_daily > /dev/null 2>&1
./wait_for_runs.sh orders_daily manual__ 2
RUN=$(airflow dags list-runs orders_daily -o plain | awk '/ manual__/ {print $2; exit}')
LOG=airflow/logs/dag_id=orders_daily/run_id=$RUN/task_id=extract/map_index=0
grep -ho '"exc_value":"[^"]*"' "$LOG/attempt=1.log" | fold -w 80orders_daily: 2 finished run(s) whose id starts with manual__
"exc_value":"orders_daily.<locals>.extract() missing 2 required keyword-only arg
uments: 'data_interval_start' and 'data_interval_end'"Naming the date does not help either. A DAG can have only one run per logical date, so a manual run for a day that already ran is refused.
airflow dags trigger orders_daily --logical-date 2026-11-09T00:00:00+00:00 \
> trigger.log 2>&1; echo "exit code $?"
grep -m 2 -oE '(UniqueViolation|DETAIL):.*' trigger.log | fold -w 80exit code 1
UniqueViolation: duplicate key value violates unique constraint "dag_run_dag_id_
logical_date_key"
DETAIL: Key (dag_id, logical_date)=(orders_daily, 2026-11-09 00:00:00+00) alrea
dy exists.And for a date with no run yet, the documentation warns that a manual run's data interval depends on how it was started and may differ from its logical date: in our tests, a run triggered with --logical-date 2026-11-04 was given 15 to 16 November, the last complete day, as its interval. To rerun past days, create a backfill for exactly those dates, with --reprocess-behavior completed if they already ran. If a task must also work in manual runs, read logical_date explicitly and fail with a clear message when it is None.
08. Check your understanding
09. Apply it
For the skill practice, run the 14-day backfill on your own pipeline and keep the evidence: the dry run, the check.sql line before and after a rerun with completed, and the run list. Then make the failure path visible: make one day fail on purpose, rerun it with --reprocess-behavior failed, and confirm the fingerprint matches a clean run. Idempotent Writes and a Safe Backfill shows the same checks without an orchestrator.
10. Review prompt
Without looking back, explain: the difference between logical_date, data_interval_start and run_after for a backfill run; why the wall-clock loader produced three successful runs and one row; what the three reprocess behaviours do; how catch-up differs from a backfill; and why a manual run is a poor way to reload a past day.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.