Idempotent pipelines with Spark and Delta
Airflow will run your tasks again: on retries, reruns and backfills. A pipeline is only correct if running a day twice gives the same result as running it once. This lesson shows the patterns that make that true.
Pipelines in production · Airflow · Gold · Data-aware pipelines, lesson 2 of 2
On this page
Read first: Templates and idempotent reruns · MERGE INTO and upserts (skip if you know them)
In plain words first
Pressing a lift button twice does not call two lifts. Pressing it is idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more →: doing it again changes nothing. Adding money to an account is not: doing it twice pays twice.
Every Airflow 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 → should behave like the lift button, because Airflow will press it again.
The contract
Airflow will run your task again: on a retry, when someone clears a run, during a backfillbackfill: Running a DAG for past dates on purpose, to fill in or redo history. Learn more →. The pipeline is correct only if running a task for a given day twice leaves the same data as running it once. The Airflow side is small (pass the run's dates in); the real work is in how the job writes.
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator daily_plays = SparkSubmitOperator( task_id="daily_plays", application="jobs/daily_plays.py", application_args=["--day", "{{ ds }}"], # the run's day, never "today" conn_id="spark_default", )
Three idempotent ways to write
| Pattern | Spark / Delta | Use when |
|---|---|---|
| Overwrite the run's slice | .mode("overwrite").option("replaceWhere", f"dt = '{day}'") on Delta; dynamic partition overwrite on ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → | Each run owns one partition or date range |
| MERGE on a key | MERGE INTO ... ON t.id = s.id WHEN MATCHED AND s.seq > t.seq ... | Upserting entities that change over time |
| Write-audit-publish | Write to a staging table or branch, run checks, then swap or fast-forward | Consumers must never see a half-checked day |
# jobs/daily_plays.py, started by the DAG as: daily_plays.py --day {{ ds }} import argparse parser = argparse.ArgumentParser() parser.add_argument("--day", required=True) day = parser.parse_args().day plays = spark.read.table("bronze.plays").where(F.col("dt") == day) daily = plays.groupBy("dt", "track_id").agg(F.count("*").alias("plays")) (daily.write.format("delta") .mode("overwrite") .option("replaceWhere", f"dt = '{day}'") # replace this day only .saveAsTable("silver.daily_plays"))
append is the most common way to lose idempotency: every retry adds the day again. A dynamic partition overwrite without a filter on the input is the second: a rerun of one day can rewrite partitions it did not mean to touch.When each day builds on the last
A running total, a snapshot, an SCD table: day N is computed from day N-1's output. Then order matters, and a failed day must stop the days after it. depends_on_past=True does that, per task:
import pendulum from airflow.sdk import DAG from airflow.providers.standard.operators.bash import BashOperator with DAG( dag_id="listener_totals", schedule="@daily", start_date=pendulum.datetime(2026, 3, 1, tz="UTC"), catchup=True, ): stage = BashOperator(task_id="stage", bash_command="stage_listeners --day {{ ds }}") total = BashOperator(task_id="running_total", depends_on_past=True, bash_command="add_to_total --day {{ ds }}") stage >> total
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 Mar 4, 09:00 UTC · grid as of Mar 4, 11:00 UTC · failing: running_total in the 2026-03-02 run · @daily (CronTriggerTimetable)
| task \ run | Mar 1 00:00 | Mar 2 00:00 | Mar 3 00:00 | Mar 4 00:00 |
|---|---|---|---|---|
| stage | ||||
| running_total |
successfailed· the bar on top is the run's state; a number is how many tries
running_total fails for 2 March. For 3 and 4 March it has no status: it waits for the previous day's instance to succeed, and the runs stay running instead of building totals on a gap. stage has no such dependency and ran every day. Fix the cause, clear the failed task, and the waiting days continue in order.
Side effects
Emails, payments, API posts and messages are not idempotent by themselves. Put them in their own task at the end, make them idempotent with a key the receiver checks (the run id and task id make a good one), or record that they happened and skip when the record exists. Then a rerun of the data steps does not pay the artists twice.
Common mistakes
- mode("append") in a daily job — Every retry and rerun adds the day again.
- Computing the day inside the Spark job from the clock — Backfills write today's data into every partition.
- Running totals without depends_on_past — A failed day is skipped over and every later total is wrong.
- Sending emails in the same task as the load — A retry of the load sends them again.
Key takeaways
- Idempotent = the run's dates in, the run's slice replaced out.
- replaceWhere / partition overwrite for daily slices, MERGE for entities, WAP for audited publishing.
- depends_on_past keeps chained days in order and stops at a failure.
- Isolate side effects and give them idempotency keys.
Interview prep
THE QUESTION
"How do you make a daily Spark job orchestrated by Airflow safe to rerun and backfill?"
Avoid: "Airflow retries make the pipeline reliable". Retries make it run again; only idempotent writes make running again safe.
Follow-ups · answer out loud, then open
Follow-up"What can go wrong with a dynamic partition overwrite in a rerun?"
Scenario"A daily snapshot table must never show a partially loaded day to analysts. How do you publish?"
Trap"depends_on_past makes the next run wait if this run is still going."
Check yourself
3 questionsWhich Delta write replaces only the run's day?
Show the answer
mode("overwrite") with replaceWhere on the date. replaceWhere limits the overwrite to the matching rows.
With depends_on_past, the 2 March instance failed. What happens to 3 March?
Show the answer
It waits with no status. It waits until the previous day's instance succeeds.
Where should "email the artists" go?
Show the answer
In its own task at the end, guarded by an idempotency key. So reruns of the data steps do not repeat it.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Running Airflow in production · 5 min readPools, concurrency and priority
Every limit on how many tasks run at once, pools for shared systems, and who goes first.
Related lessons
Templates and idempotent rerunsData lake & lakehouse · 7 min read
Branches, tags and write-audit-publishData lake & lakehouse · 7 min read
MERGE INTO and upserts
Previous: Assets: scheduling on data
Primary sources: Best practices · Delta: selectively overwrite data