Rewrite an Airflow task that picks its day with datetime.now() so retries and backfills are safe
A daily task on Airflow 3 loads yesterday's sales. Today it computes day = datetime.now().date() - timedelta(days=1) and runs INSERT INTO sales_daily SELECT * FROM raw_sales WHERE order_ts::date = day. After a retry past midnight and a 7-day backfill, some days hold today's rows and others are doubled.
Constraints: take the slice from Airflow's run context, not the clock; do not use execution_date; a rerun of the same run must leave sales_daily unchanged; run_sql(sql, params) runs its statements in one transaction. The DAG declares an interval timetable on purpose.
import pendulum
from airflow.sdk import CronDataIntervalTimetable, dag, task
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=pendulum.datetime(2026, 1, 1, tz="UTC"),
catchup=False,
)
def sales_daily():
@task(retries=3)
def load_sales():
# your code here
...
load_sales()
sales_daily()Write the implementation.
datetime.now() ties the slice to the clock, so a retry after midnight or a backfill loads another day under an old run and appends it again. Read data_interval_start/data_interval_end from the context (not execution_date, gone in Airflow 3) and overwrite that range.
- Fixing the date source but keeping an append, so a retry of the same run still doubles the interval
- Reaching for
execution_date, which Airflow 3 removed from the task context - Filtering on the interval under Airflow 3's default cron timetable, where start equals end and the filter is empty
- How would the same task pass the interval to a SQL operator through Jinja templates instead?
- What changes if the target table is partitioned by day and supports partition overwrite?
The slice comes from the run context: TaskFlow passes in the context keys that match the function's parameter names. The interval is half-open, [start, end), and the write replaces it whole in one transaction, so a retry, a backfill or a clear gives the same result:
@task(retries=3)
def load_sales(data_interval_start=None, data_interval_end=None):
params = {"start": data_interval_start, "end": data_interval_end}
run_sql(
"""
DELETE FROM sales_daily
WHERE order_ts >= %(start)s AND order_ts < %(end)s;
INSERT INTO sales_daily
SELECT * FROM raw_sales
WHERE order_ts >= %(start)s AND order_ts < %(end)s;
""",
params,
)The interval timetable on the DAG is required here. In Airflow 3 a bare cron string such as "0 0 * * *" resolves to CronTriggerTimetable, where data_interval_start == data_interval_end, and this filter would select no rows. Airflow 3 removed execution_date from the context; logical_date labels the run, but the slice boundaries are the data_interval_* values.