Home / Data Platform / Databricks & Spark

Data PlatformTroubleshootingAdvanced

Spark Structured Streaming foreachBatch writes duplicates after a restart: idempotent Delta writes with txnAppId and txnVersion

Why foreachBatch replays a micro-batch after a failure, how that duplicates appends and multi-table writes, and how txnAppId/txnVersion and deterministic MERGE make reruns safe.

Deepak Bhardwaj7 min read

Applies toApache Spark 3.x-4.x Structured Streaming with Delta Lake 2.x-4.x; Databricks Runtime and Azure Databricks

Symptom

A streaming job that writes to Delta through foreachBatch failed, or the cluster was restarted. After it recovered, the target tables have duplicate rows for one micro-batch. Sometimes only one of two target tables is duplicated. The source and the checkpoint look healthy, and the job reports no errors.

This is expected behaviour, not a bug. Structured Streaming guarantees that foreachBatch runs at least once for each batch. If the query fails after your function has written data but before the batch is committed to the checkpoint, the same batchId runs again on restart. Delta only skips the second write if you tell it which writes belong to which batch.

Confirm it was a replay

Look at the Delta history of the target. A replay shows two commits with the same operation and very similar numOutputRows close together around the restart time:

DESCRIBE HISTORY bronze.events LIMIT 20;
from pyspark.sql import functions as F

(spark.sql("DESCRIBE HISTORY bronze.events")
   .select("version", "timestamp", "operation",
           F.col("operationMetrics.numOutputRows").alias("rows"))
   .orderBy(F.col("version").desc())
   .show(20, truncate=False))

Then check the checkpoint. The offsets folder contains a file for every batch that started, and the commits folder contains a file for every batch that finished. If the highest number in offsets is greater than the highest number in commits, that batch was in flight when the job died, and it will run again:

# Databricks CLI, Unity Catalog volume checkpoint
databricks fs ls dbfs:/Volumes/ops/chk/events_ingest/offsets
databricks fs ls dbfs:/Volumes/ops/chk/events_ingest/commits

In a notebook, dbutils.fs.ls() lists the same folders.

Count the duplicates by business key before you change anything:

SELECT event_id, count(*) AS copies
FROM bronze.events
GROUP BY event_id
HAVING count(*) > 1
ORDER BY copies DESC
LIMIT 50;

Causes

Pattern in foreachBatch What happens on replay Fix
A single append to Delta with no transaction options The batch is appended twice Add txnAppId and txnVersion
Appends to two or more tables Tables that were already written get the batch again Add the same txnAppId/txnVersion pair to every write
MERGE upsert by key Usually safe: the second run updates the same rows to the same values Make the source deterministic and deduplicate it by key
MERGE whose updates use current_timestamp(), counters or amount = amount + s.amount Values are applied twice or change Take values from the source only, or track processed batches
Writes to a JDBC database, REST API or a non-Delta sink Duplicates on that sink Use upserts on the sink side, or keep a batch-id table
A try/except that catches the error and writes again Partial batches and double writes Let the batch fail and let the job retry it

Fix 1: idempotent appends with txnAppId and txnVersion

Delta writers accept two options. txnAppId is a stable string that identifies the writer. txnVersion is a number that must increase. Delta stores the highest version it committed for each app id in the transaction log, and skips any write whose txnVersion is not higher than that. Bind txnVersion to batchId:

APP_ID = "events_ingest_v1"   # stable, unique per stream and per checkpoint

def write_batch(batch_df, batch_id):
    batch_df.persist()
    (batch_df.write.format("delta")
        .option("txnAppId", APP_ID)
        .option("txnVersion", batch_id)
        .mode("append")
        .save("abfss://lake@stdata.dfs.core.windows.net/bronze/events"))
    (batch_df.filter("severity = 'ERROR'").write.format("delta")
        .option("txnAppId", APP_ID)
        .option("txnVersion", batch_id)
        .mode("append")
        .save("abfss://lake@stdata.dfs.core.windows.net/bronze/event_errors"))
    batch_df.unpersist()

(spark.readStream.table("raw.events")
    .writeStream
    .foreachBatch(write_batch)
    .option("checkpointLocation", "/Volumes/ops/chk/events_ingest")
    .start())

If the job dies after the first write, the replay skips bronze/events because that table already has this app id and batch, and writes only bronze/event_errors.

persist() stops Spark from reading the source twice for the two writes. If the source is not deterministic, the two writes can also see different rows.

Warning

Use a fixed string for txnAppId, not a random UUID or the run id. The query id that query.id returns is stable for the life of a checkpoint and can be used. A value that changes on every restart turns off the protection.

Fix 2: make MERGE replay-safe

MERGE does not need the transaction options if running the same batch twice gives the same result. Two things break that:

  • Several source rows per key in one batch. The second run can choose a different "winner", or the MERGE fails with "multiple source rows matched".
  • Update expressions that depend on the current target value or on the clock.
from delta.tables import DeltaTable
from pyspark.sql import Window, functions as F

def upsert_batch(batch_df, batch_id):
    w = Window.partitionBy("customer_id").orderBy(F.col("source_ts").desc(), F.col("source_offset").desc())
    latest = (batch_df.withColumn("rn", F.row_number().over(w))
                      .filter("rn = 1").drop("rn"))

    tgt = DeltaTable.forName(batch_df.sparkSession, "silver.customers")
    (tgt.alias("t")
        .merge(latest.alias("s"), "t.customer_id = s.customer_id")
        .whenMatchedUpdate(condition="s.source_ts >= t.source_ts",
                           set={"name": "s.name", "tier": "s.tier", "source_ts": "s.source_ts"})
        .whenNotMatchedInsertAll()
        .execute())

The s.source_ts >= t.source_ts condition also stops an older replayed batch from overwriting newer data.

For running totals, which cannot be replayed safely, record each batch in a control table in the same job and skip batches that are already there. Better still, aggregate from an append-only table that has idempotent writes.

The trap: resetting the checkpoint

If you delete the checkpoint or point the query at a new one, batchId starts again at 0. Delta still remembers the highest txnVersion for your old txnAppId, so it silently skips every write until the new batch ids pass that number. The stream reports progress, but the tables stop growing.

Check the latest app transaction versions in the log. _delta_log JSON files contain txn actions:

log = spark.read.json("abfss://lake@stdata.dfs.core.windows.net/bronze/events/_delta_log/*.json")
(log.filter("txn IS NOT NULL")
    .select("txn.appId", "txn.version")
    .groupBy("appId").max("version")
    .show(truncate=False))

Caution

Whenever you start a stream with a new checkpoint, change txnAppId too (for example events_ingest_v1 to events_ingest_v2). If you reuse the old id, data is dropped without any error until batchId passes the old high-water mark.

Older JSON commits can be removed by checkpoint compaction in _delta_log. If the query returns nothing, that does not prove that no app id exists. Changing the id on every checkpoint reset is the safe rule.

Clean up the duplicates already written

First, write down the current table version so you can roll back:

DESCRIBE HISTORY bronze.events LIMIT 1;

Then rewrite only the affected partition, keeping one row per key. Delta reads a consistent snapshot, so the job can read from and overwrite the same table:

day = "2026-11-29"   # partition that contains the replayed batch
clean = (spark.table("bronze.events")
           .where(f"event_date = '{day}'")
           .dropDuplicates(["event_id"]))

(clean.write.format("delta")
    .mode("overwrite")
    .option("replaceWhere", f"event_date = '{day}'")
    .saveAsTable("bronze.events"))

Pause the stream while this runs, so the cleanup does not conflict with new appends to the same partition. If the result is wrong, roll back with:

RESTORE TABLE bronze.events TO VERSION AS OF <version_before_cleanup>;

Prevent it next time

  • Give every foreachBatch Delta write txnAppId plus txnVersion = batchId, including every write in a multi-table function.
  • Version the app id together with the checkpoint path, and write both in the job config.
  • Deduplicate by key inside the batch before MERGE, and only update from source values.
  • Don't catch and retry inside foreachBatch. Let the query fail, and let the job's retry policy restart it.
  • Add a daily duplicate-key check on the target tables, and alert on any count above zero.