Özer Cem KELAHMETKELAHMET
Articles · Batch processing

Idempotent batch jobs: partition overwrites, data intervals and safe backfills

A batch job is only safe when running it twice gives the same table as running it once. This guide tests Spark's partition overwrite modes, shows why appends double data on retry, and plans backfills with the Airflow 3.4 backfill command.

Download Markdown
At a glance
Reading time
14 min
Sections
8
Code examples
4
Tables
5
Sources
8
Published
23 Nov 2026
In 30 seconds
What changed
Apache Airflow 3.4.0 is released
Why it matters
Idempotency is a property of the whole run, not a single setting.
What to do
Search for append writes in batch jobs

Every batch pipeline eventually reruns. A task fails halfway and the scheduler retries it. A bug in yesterday's logic is fixed and last month has to be rebuilt. A source system resends a day of data. If the job appends rows, each rerun adds another copy. If it overwrites the wrong thing, a rerun of one day deletes the rest of the table.

The property that makes reruns safe is idempotency: running a job for a given input slice once, twice or ten times leaves the same result. Think of a light switch labelled "on" and "off" rather than a toggle button. Pressing "on" three times still leaves the light on; pressing a toggle three times depends on where you started.

This article builds an idempotent daily job in PySpark 4.3.0, tests the two partition overwrite modes that decide whether a rerun is safe or destructive, and then plans a backfill with the backfill command in Apache Airflow 3.4.0. Every Spark result below comes from running the code locally.

What happened

Apache Airflow 3.4.0 is released (6 November 2026)

Airflow 3.4.0 was published to PyPI on 6 November 2026. The project's release post is titled "Task Loops, Dags in Any Language, and AI Agents". For batch processing the relevant part is unchanged in spirit since Airflow 3.0: backfills are created as their own objects and run by the scheduler, instead of by a long-running local CLI process. In the 3.4.0 source, airflow backfill create takes --dag-id, --from-date, --to-date (both inclusive), --max-active-runs, --run-backwards, --reprocess-behavior and --dry-run, and its help text notes that for partitioned Dags the range is read as a partition-date range.

Apache Spark 4.3.0 is released (30 October 2026)

PySpark 4.3.0 was published on 30 October 2026, with release notes on the Spark site. The batch features used here, partitioned Parquet writes and the spark.sql.sources.partitionOverwriteMode setting, behave as they have in earlier releases. A fresh 4.3.0 session still reports the default overwrite mode as STATIC, which is the main trap this article is about.

Three ways to load a day of data

A daily job reads one day of source data, transforms it and writes it to a table partitioned by date. There are three common write patterns.

Table 1. Three ways to load a day of data
Pattern Rerun the same day Rerun after a fix Risk
Append Duplicates the day Duplicates the day Double counting on every retry
Overwrite whole table, static mode Deletes every other day Deletes every other day Data loss
Overwrite only the day's partition Same result Day is replaced with corrected data Must compute exactly one slice per run

Only the third pattern is idempotent. It needs two things: the job must compute a well-defined slice (one day, one hour, one source file batch), and the write must replace exactly that slice in the target.

Testing Spark's partition overwrite modes

I wrote a small table with three days, 20 to 22 November, three orders per day, amount 10 each. Then I reprocessed only 21 November with corrected data: four orders of amount 20.

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[2]")
         .config("spark.sql.session.timeZone", "UTC").getOrCreate())

def daily(day, n, amount):
    return spark.createDataFrame([(i, day, amount) for i in range(n)],
                                 "order_id INT, order_date STRING, amount INT")

initial = daily("2026-11-20", 3, 10).union(daily("2026-11-21", 3, 10)) \
                                    .union(daily("2026-11-22", 3, 10))
initial.write.mode("overwrite").partitionBy("order_date").parquet("orders")

spark.conf.set("spark.sql.sources.partitionOverwriteMode", "static")  # or "dynamic"
daily("2026-11-21", 4, 20).write.mode("overwrite") \
    .partitionBy("order_date").parquet("orders")

The results after the reprocessing write, as (date, rows, total amount):

Table 2. Testing Spark's partition overwrite modes
Mode Table afterwards
static (the default) Only 2026-11-21: 4 rows, 80
dynamic 2026-11-20: 3 rows, 30; 2026-11-21: 4 rows, 80; 2026-11-22: 3 rows, 30

In static mode, mode("overwrite") on a partitioned path replaces the whole table with whatever the DataFrame contains, so the two untouched days vanished. In dynamic mode, Spark replaces only the partitions present in the DataFrame, so 21 November was corrected and the other days stayed. That one setting is the difference between a safe rerun and a deleted table.

Retries: append versus dynamic overwrite

Next I simulated a retry: the job for 23 November ran twice, as it would if the scheduler retried after a timeout that happened after the write had already finished.

Table 3. Retries: append versus dynamic overwrite
Write pattern, run twice Rows for 2026-11-23 Total amount
mode("append") 6 60
mode("overwrite") with dynamic mode 3 30

Append doubled the day. Dynamic overwrite gave the same answer both times. This is the most common silent bug in batch pipelines: the retry succeeds, the dashboard shows twice the revenue for one day, and nobody notices until month end.

Table formats offer the same idea, more safely

Plain Parquet directories have no transactions, so a crash in the middle of an overwrite can leave a partition half-written. Open table formats make the replace atomic. Spark's own DataFrameWriterV2 has overwritePartitions(), which dynamically replaces the partitions present in the DataFrame for tables in a catalog. Delta Lake offers a replaceWhere option that replaces exactly the rows matching a predicate, such as order_date = '2026-11-21', and fails if the new data falls outside it. Apache Iceberg supports dynamic partition overwrite through the same overwritePartitions() API. The transaction logs behind these guarantees are explained in the Delta Lake transaction log article and the Iceberg metadata article.

Deciding what slice a run owns

An overwrite is only idempotent if the slice it computes is fixed. There are two ways to define it.

Option 1: a high-water mark

The job stores the largest updated_at it has processed and, next time, reads rows above it. This is simple and adapts to irregular arrival, but the slice depends on when the job runs. A retry after new data arrives reads a different set of rows than the original attempt. It also cannot express "rebuild 3 November" without editing the stored mark. It suits append-only feeds where reruns are rare; incremental models in dbt hit the same problem, skipping late rows unless you add a lookback.

Option 2: a data interval passed by the scheduler

The scheduler tells each run which interval it owns, for example 2026-11-21 00:00 to 2026-11-22 00:00, and the job reads and writes only that interval. In Airflow the interval is available to tasks as data_interval_start and data_interval_end. A retry receives the same interval, and a backfill is simply many runs with older intervals.

# job.py, called as: spark-submit job.py 2026-11-21 2026-11-22
import sys
from pyspark.sql import SparkSession, functions as F

start, end = sys.argv[1], sys.argv[2]
spark = (SparkSession.builder
         .config("spark.sql.sources.partitionOverwriteMode", "dynamic")
         .config("spark.sql.session.timeZone", "UTC")
         .getOrCreate())

orders = (spark.read.parquet("s3://lake/bronze/orders")
          .where((F.col("event_ts") >= start) & (F.col("event_ts") < end)))

daily = (orders.groupBy(F.to_date("event_ts").alias("order_date"), "store_id")
               .agg(F.count("*").alias("orders"), F.sum("amount").alias("revenue")))

daily.write.mode("overwrite").partitionBy("order_date").parquet("s3://lake/silver/daily_store_sales")

Two details make this safe. The filter is half-open (>= start, < end), so adjacent runs never share rows. The output partition is derived from the same interval, so the run replaces exactly the partition it computed. If a run's input interval could produce rows for more than one output partition, for example because of time zones, either align the interval to the partition boundaries or filter the output to the expected partitions before writing.

Table 4. Option 2: a data interval passed by the scheduler
Approach Retry gives same result Backfill a past range Handles late data Best for
High-water mark Not guaranteed Needs manual reset Only with a lookback Append-only feeds, CDC tails
Data interval Yes Yes, natively Rerun the affected intervals Daily and hourly aggregates, facts

Planning a backfill with Airflow 3.4

A backfill reruns a DAG for a range of past intervals. With the data-interval job above, it is safe by construction. The Airflow 3.4.0 command looks like this:

airflow backfill create \
  --dag-id daily_store_sales \
  --from-date 2026-01-01 \
  --to-date 2026-10-31 \
  --max-active-runs 4 \
  --reprocess-behavior completed \
  --dry-run

What the options do, according to the 3.4.0 CLI definitions:

Table 5. Planning a backfill with Airflow 3.4
Option Meaning
--from-date, --to-date Backfill window, both ends inclusive
--reprocess-behavior none Create runs only for missing intervals (the default)
--reprocess-behavior failed Missing and failed runs
--reprocess-behavior completed All runs, including ones that succeeded
--max-active-runs Upper limit on concurrent runs for this backfill
--run-backwards Start from the most recent date; not supported if tasks use depends_on_past
--dry-run Show what would be created without creating it

Use completed when the logic changed and every day must be rebuilt, and none when you only need to fill gaps.

Sizing the backfill

A worked example. The range 1 January to 31 October 2026 is 304 daily runs. Each run takes about 6 minutes on its cluster.

  • With --max-active-runs 1: 304 × 6 = 1,824 minutes, about 30.4 hours.
  • With --max-active-runs 4: 304 ÷ 4 = 76 waves, × 6 = 456 minutes, about 7.6 hours, if the cluster and the source can sustain four runs at once.
  • With --max-active-runs 8: 38 waves, about 3.8 hours, but now eight jobs compete for the same source database, object store prefixes and warehouse slots.

Concurrency is limited by the weakest shared resource, not by Airflow. If the source is a production database, a fast backfill can become an outage. Start with a short range, watch source load and job duration, then widen it.

Alternatives to one run per day

For large historical rebuilds, one run per day is not always the cheapest shape. A single Spark job can read a whole month and write 30 partitions in one dynamic overwrite, which spends less time on cluster start-up and file listing. The trade-off is blast radius: if the month job fails at the end, you redo the month. A practical rule is to backfill in chunks that take minutes to an hour each, small enough to retry cheaply and large enough to amortise start-up. Managed services such as Amazon EMR and AWS Glue run the same Spark code; Glue also offers job bookmarks, a managed form of high-water mark that tracks which input has been processed.

What it means in practice

Idempotency is a property of the whole run, not a single setting. The input slice must be fixed, the transformation must be deterministic for that slice, and the write must replace exactly that slice. Break any one and retries or backfills drift from the truth.

The Spark default is the sharpest edge. Because partitionOverwriteMode is STATIC unless you change it, a correct-looking mode("overwrite").partitionBy(...) can wipe a table. Set it to dynamic in cluster or session config for every batch job that writes partitioned output, or use a table format API with explicit partition or predicate replacement.

Scheduler-owned intervals make the rest routine. With Apache Airflow passing data_interval_start and data_interval_end, retries recompute the same slice, and a backfill is just a date range on the command line. For the engine side of large rebuilds, the Spark adaptive query execution article covers shuffle and skew tuning, and the PySpark tool page has the basics.

What to do now

  1. Search for append writes in batch jobs. Any job that appends and can be retried is a duplicate risk; switch it to a partition or predicate replace.
  2. Set dynamic overwrite explicitly. Add spark.sql.sources.partitionOverwriteMode=dynamic to the job or cluster config, and test it with a one-partition rewrite.
  3. Pass intervals into jobs. Make every scheduled job accept a start and end argument instead of computing "yesterday" from the wall clock.
  4. Use half-open filters. Filter with >= start and < end so adjacent intervals never overlap or leave gaps.
  5. Prefer transactional replaces. On Delta or Iceberg tables, use replaceWhere or overwritePartitions() so a failed write never leaves a half-written partition.
  6. Retry test every job. Run the same interval twice in a test environment and compare row counts and sums.
  7. Dry-run backfills. Use airflow backfill create --dry-run to see which runs would be created before starting a large range.
  8. Cap backfill concurrency. Start with a low --max-active-runs, measure load on sources and targets, then raise it.
  9. Record what was rebuilt. Log the range, code version and reprocess behaviour of each backfill so downstream users know which history changed.

Risks and open questions

Static overwrite deletes data. The default mode replaces the whole table on a partitioned overwrite; one missed setting can erase history.

Non-deterministic logic breaks idempotency. Functions like current_timestamp(), random sampling or reading "the latest" dimension snapshot give different results on rerun. Derive such values from the interval instead.

Backfills can overload sources. Many concurrent runs against an operational database or a rate-limited API can cause incidents; schedule large backfills off-peak.

Code version matters. A backfill may run with current code or the code active when the original run happened. The Airflow 3.4 CLI marks --run-on-latest-version as experimental and documents its default fallback; check which behaviour you get.

Plain Parquet is not atomic. A crash during an overwrite on a bare directory can leave partial files; readers may see incomplete partitions until the rerun finishes.

Watch next: how partition-aware scheduling in Airflow's partitioned Dags develops, and whether table formats make predicate-based replaces the default write path for batch jobs.

Frequently asked questions

What does idempotent mean for a batch job?

It means running the job for the same input slice any number of times leaves the target in the same state as running it once. Retries and backfills are then safe. Appending rows is not idempotent; replacing the slice is.

What is the difference between static and dynamic partition overwrite?

In static mode, an overwrite of a partitioned table replaces all partitions, so partitions missing from the new data are deleted. In dynamic mode, Spark replaces only the partitions that appear in the new data. In the test above, static mode left one day out of three, while dynamic mode corrected the day and kept the others.

Should I use a high-water mark or a data interval?

Use a data interval for scheduled aggregates and fact loads, because retries and backfills then recompute exactly the same slice. A high-water mark suits append-only feeds where you simply want everything new, but it needs a lookback for late data and a manual reset to rebuild history.

What does --reprocess-behavior do in Airflow backfills?

It decides which runs the backfill creates in the range: none creates only missing runs (the default), failed adds runs that failed, and completed reruns everything, including successful runs. Use completed after a logic change that affects all history.

How do I make a backfill finish faster?

Raise --max-active-runs within what your cluster and sources can sustain, or process larger chunks, such as a month per Spark job with dynamic overwrite. Measure source load first, because the bottleneck is usually the database or storage, not the scheduler.

Summary

Batch jobs rerun all the time, so they must be idempotent: each run owns a fixed slice and replaces exactly that slice. Tests on PySpark 4.3.0 show why the details matter. Spark's default static overwrite wiped two of three days during a one-day fix, dynamic overwrite replaced only the day, and an appended retry doubled a day's revenue while a dynamic overwrite did not. Passing scheduler-defined data intervals into jobs, using half-open filters and transactional replaces, and planning backfills with Airflow 3.4's backfill create options turns reruns from a risk into a routine.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 23). Idempotent batch jobs: partition overwrites, data intervals and safe backfills. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/idempotent-batch-jobs-partition-overwrite-backfills

BibTeX
@online{kelahmet2026idempotent,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Idempotent batch jobs: partition overwrites, data intervals and safe backfills}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/idempotent-batch-jobs-partition-overwrite-backfills}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 23, 2026
Type to search.
    ↑↓ navigate↵ open