Sub topic 8
Delivery guarantees and idempotent writes
This chapter assumes you can write a basic streaming query with a checkpoint, and that you know what a Delta table commit is. It covers what "exactly-once" means in Structured Streaming and how to keep it when you write your own sink logic.
What the guarantee covers
Structured Streaming gives end-to-end exactly-once results when three parts work together:
- A replayable source. Files in Auto Loader, Delta tables and Kafka can all be re-read from a known position.
- A checkpoint. Before a micro-batch runs, the engine writes the offset range it will process. After the batch finishes, it records a commit.
- An idempotent sink. Writing the same batch twice must leave the same result as writing it once.
The sequence below shows what happens when a failure hits mid-batch.
The engine replays the same offset range with the same batch ID. That makes at-least-once delivery the baseline, and the sink has to turn it into exactly-once.
Built-in Delta sinks
When you use toTable on a Delta table, the sink records the query ID and batch ID inside the Delta transaction. A replayed batch is detected and skipped. You don't need to do anything extra.
Custom logic in foreachBatch
foreachBatch runs your own code, so Spark can't know whether a replay is a duplicate. You must make the function safe to run twice. Two common ways:
- Use MERGE on a business key. A replay updates the same rows to the same values. The batch must hold at most one row per key.
- Tag the write with a batch ID. Delta supports idempotent writes with the
txnAppIdandtxnVersionoptions.
def write_batch(batch_df, batch_id):
(
batch_df.write.format("delta")
.option("txnAppId", "orders_app_v1")
.option("txnVersion", batch_id)
.mode("append")
.saveAsTable("main.demo.orders_silver")
)
(
spark.readStream.table("main.demo.orders_bronze")
.writeStream
.foreachBatch(write_batch)
.option("checkpointLocation", "/Volumes/main/demo/chk/orders_silver")
.start()
)Delta remembers the highest txnVersion for each txnAppId. If a replayed batch arrives with a version it has already seen, Delta skips the write.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Appending in `foreachBatch` with no key or `txnVersion` | Duplicate rows after a retry | Use MERGE or `txnAppId` and `txnVersion` |
| Calling an external API or sending an email in `foreachBatch` | The side effect repeats on replay | Make the call idempotent, or record sent IDs |
| Two queries sharing one checkpoint | Corrupted offsets and state | Give every query its own checkpoint path |
| Deleting the checkpoint to "fix" a failure | The query reprocesses the source from scratch | Fix the cause. Reset deliberately and plan for duplicates |
| Changing the source's data between replays | The replayed batch differs from the original | Don't mutate or delete files and offsets that the query still needs |
Exercise
A foreachBatch function appends each batch to a Delta table with no extra options. The cluster dies after the append but before the checkpoint commit. What happens on restart, and how do you prevent it?
Show answer
The engine replays the same batch because it was never committed, so the append runs again and writes duplicate rows. Prevent it by writing with the txnAppId and txnVersion options (using batch_id as the version), or by replacing the append with a MERGE on a unique key.