Skip to content
Apache AirflowData EngineeringBigQuery

Designing Idempotent Airflow DAGs That Survive Retries and Backfills

Learn to design idempotent Apache Airflow DAGs with data intervals, partition overwrites, MERGE upserts and quality gates so retries and backfills stay safe.

By 6 min read

Every Airflow pipeline will eventually run more than once for the same period. A task times out and retries, an upstream fix forces you to reprocess last week, or a new table needs two years of history. If your DAGs are idempotent, these re-runs are routine; if not, they create duplicates, gaps and late-night debugging.

What idempotency means for a pipeline

An operation is idempotent when running it once or many times produces the same result. For a data pipeline, it means a run for a given period always leaves the target in the same state, whether it is the first attempt, the third retry or a backfill six months later.

Idempotency rests on two properties:

  • Deterministic inputs: a run always reads the same slice of source data.
  • Replace-style outputs: a run overwrites its own slice of the target instead of adding to it.

Get those two right and most retry and backfill problems disappear.

Use the data interval, never now()

Airflow gives every scheduled DAG run a data interval. data_interval_start and data_interval_end mark the period of data the run is responsible for, and logical_date identifies the run. A daily run for 17 April covers that day from midnight to midnight, even if it executes on 18 April or in a backfill next year.

The most common idempotency bug is calling datetime.now() in Python or CURRENT_DATE() in SQL inside a task. A retry an hour later, or a backfill, then reads a different window and produces different output. Derive every filter, file path and partition key from the data interval instead.

import pendulum
from datetime import timedelta
from airflow.sdk import dag, task  # Airflow 2.x: from airflow.decorators import dag, task

@dag(
    schedule="@daily",
    start_date=pendulum.datetime(2026, 1, 1, tz="UTC"),
    catchup=False,
    max_active_runs=1,
    default_args={"retries": 3, "retry_delay": timedelta(minutes=5)},
)
def daily_orders():
    @task
    def extract(data_interval_start=None, data_interval_end=None) -> str:
        day = data_interval_start.strftime("%Y-%m-%d")
        path = f"gs://raw-bucket/orders/dt={day}/orders.parquet"
        export_orders(data_interval_start, data_interval_end, path)  # overwrites the file
        return day

    @task
    def load(day: str):
        merge_orders_partition(run_date=day)  # runs the MERGE shown below
    load(extract())

daily_orders()

Here export_orders and merge_orders_partition stand in for your own helper functions. The important part is that the TaskFlow API injects the data interval as keyword arguments, and everything downstream is keyed on it.

Overwrite, don't append

Appending is the enemy of idempotency, because every retry adds the same rows again. Design each write so that re-running it replaces the previous result.

Overwrite the partition

If the target is partitioned by date, each run can replace exactly one partition. In BigQuery, load with WRITE_TRUNCATE into a partition decorator such as orders$20260417. In Spark, set spark.sql.sources.partitionOverwriteMode to dynamic so only the partitions present in the DataFrame are replaced. In Redshift, delete the day's rows and insert the new ones inside a single transaction.

MERGE for upserts

When source records change over time, such as orders moving from pending to shipped, use a MERGE statement, often called an upsert. It updates rows that already exist and inserts new ones, so running it twice gives the same result.

MERGE analytics.orders AS t
USING (
  SELECT * EXCEPT (rn) FROM (
    SELECT *, ROW_NUMBER() OVER (
      PARTITION BY order_id ORDER BY updated_at DESC) AS rn
    FROM staging.orders
    WHERE order_date = @run_date
  )
  WHERE rn = 1
) AS s
ON t.order_id = s.order_id AND t.order_date = @run_date
WHEN MATCHED AND s.updated_at > t.updated_at THEN
  UPDATE SET status = s.status, amount = s.amount, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT (order_id, order_date, status, amount, updated_at)
  VALUES (s.order_id, s.order_date, s.status, s.amount, s.updated_at);

Three details make this robust. The ROW_NUMBER subquery removes duplicate source rows, which would otherwise make the statement fail because one target row matches several source rows. The t.order_date = @run_date condition limits the target scan to a single partition. And @run_date is a query parameter passed in from the data interval, not computed inside the SQL.

Atomic writes through staging tables

A task that fails halfway can leave a target half-written. The fix is to write into a staging table first, validate it, and then publish in one atomic step: a single MERGE, a CREATE OR REPLACE TABLE ... AS SELECT, or a delete-and-insert inside one transaction. Downstream consumers then see either the old data or the new data, never a partial load.

Design small, retryable tasks

Retries only help when retrying a task is cheap and safe. A few patterns make that true:

  • One responsibility per task: extract, load, transform and validate as separate steps, so a failed load retries without re-extracting.
  • Pass references, not data: return file paths or table names through XCom, Airflow's mechanism for passing small values between tasks, rather than whole datasets.
  • Retry with backoff: a few retries with a delay, optionally with retry_exponential_backoff=True, absorb transient API and network errors.
  • Set timeouts: execution_timeout stops a hung task from blocking the pipeline indefinitely.

Sensors vs deferrable operators

Sensors wait for a condition, such as a file landing in a bucket. In the default poke mode, a sensor holds a worker slot for the entire wait. reschedule mode releases the slot between checks, and deferrable operators go further: they hand the wait to the triggerer, a lightweight asynchronous Airflow process, and free the worker completely. Many built-in sensors accept deferrable=True, and for long waits it is the better default.

Catchup and backfills

With catchup=True, the scheduler creates a run for every interval between start_date and now that has not run yet. That is useful for building history, but it can launch hundreds of runs at once, so pair it with max_active_runs. Use depends_on_past=True only when each day genuinely depends on the previous day's result.

For one-off reprocessing, trigger a backfill over a date range:

# Airflow 3.x
airflow backfill create --dag-id daily_orders \
  --from-date 2026-03-01 --to-date 2026-03-31

# Airflow 2.x
airflow dags backfill -s 2026-03-01 -e 2026-03-31 daily_orders

In Airflow 3, check the --reprocess-behavior option if you need to re-run intervals that already have runs. Because every run uses its own data interval and overwrites its own partition, a backfill is just a set of ordinary runs, with no special code path to test.

Quality gates and alerting

Idempotency protects you from duplicates, not from bad source data. Add a validation task between loading and publishing that fails the run when something looks wrong:

  • Row counts fall within an expected range compared with recent days.
  • Key columns contain no nulls and primary keys are unique.
  • The latest record timestamp falls inside the data interval.

The SQL check operators in Airflow's common SQL provider, dbt tests, or tools such as Great Expectations and Soda all work. What matters is that a failed check stops downstream tasks, so bad data never reaches dashboards.

Finally, make failures visible. Use on_failure_callback to notify Slack, Teams or a paging tool, and include the DAG, task, data interval and log link in the message. Alert on stale data as well as failed tasks, because a pipeline that silently stops running is worse than one that fails loudly.

Key takeaways

  • An idempotent run produces the same result no matter how many times it executes for the same interval.
  • Derive every filter, path and partition key from the data interval, never from the current time.
  • Overwrite partitions or MERGE instead of appending, and publish through staging tables for atomic writes.
  • Keep tasks small with retries and timeouts, and prefer deferrable operators for long waits.
  • Gate publishing on data-quality checks, and alert on both failures and stale data.
Portrait of Nandha Kumar

Written by

Nandha Kumar

Data Engineer & Full-Stack Developer in Chennai, building data platforms on AWS and Google Cloud.