Skip to content
Silver 9 min read · Exactly-once 2 practice problems ↓

Delivery guarantees end to end

When something fails half way, a pipeline can lose an event, repeat it, or (with some care) do neither. Interviewers ask which one yours does, and why. This lesson starts with an online payment and ends with the exact settings that make a Spark pipeline safe to retry.

Step 4 · Structured Streaming · Silver · Correct results end to end, lesson 1 of 3

Read first: Structured Streaming basics · Deduplicating a stream (skip if you know them)

In plain words first

You click Pay and the page hangs. Did the payment go through? You cannot tell, so you have three choices:

Do not click again

If the first click was lost, you never paid. Nothing is ever paid twice, but a payment can go missing: at-most-once.

Click again

You will certainly pay, but maybe twice. Nothing goes missing, but a payment can repeat: at-least-once.

Click again, same order number

The shop sees order 1042 a second time and ignores it. You pay once, however often you click: exactly-once.

Pipelines face the same choice after every failure, and they solve it the same way: retry, and make the retry harmless with an id the receiver can check.

The three guarantees

Each guarantee answers one question: after a failure, how many times can one event affect the output? The answer depends on what a system records first: its position in the input, or the result of its work.

GuaranteeAfter a failureHow it happensExample
At-most-onceAn event can be lost, never repeatedRecord the position, then process. A crash in between skips the eventA consumerconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → that commits its offsetoffset: The position of a message inside a Kafka partition: 0, 1, 2, ... A stream stores the offsets it has read in its checkpoint. Learn more → before processing; metrics sent and never retried
At-least-onceAn event can be repeated, never lostProcess, then record the position. A crash in between processes the event againSpark's KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more → sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more →, foreachBatch by default, most queue consumers
Exactly-onceEach event affects the output onceAt-least-once processing plus a sink that recognises a repeat and ignores itKafka → Spark → Delta with a checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more →

Exactly-once is about the effect, not the delivery. After a crash, Spark still reads and processes the unfinished batch a second time; the sink makes the second write a no-op. That is why some engineers prefer the name "effectively once".

Why most systems are at-least-once

A sender that gets no acknowledgement cannot tell whether the message was lost or only the acknowledgement was. It has two choices: send again (at-least-once) or give up (at-most-once). Losing data is usually worse than repeating it, so almost every system sends again. Duplicates then enter a pipeline in a few predictable places:

  • Producersproducer: An application that writes events to a topic. Learn more → retrying. Kafka's idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more → producer (on by default in current clients) removes copies caused by its own retries, but not a send repeated by the application after it restarts (Kafka producers).
  • Spark writing to Kafka. The Spark docs are explicit: Kafka only supports at-least-once writes, so a retried micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → sends its messages again.
  • foreachBatch. At-least-once by default: a batch that crashes after your write runs again with the same batch_id.
  • Consumers that process a message and commit its offset afterwards.

The weakest hop decides

  1. App → Kafka

    At-least-once: a resend after a timeout or a restart writes a second copy

  2. Kafka → Spark

    Replayablereplayable: A source that can give back exactly the same data again from a saved position, so a failed micro-batch can be run again. Learn more →: the offsets of each batch are in the checkpoint

  3. Spark → Delta

    Exactly-once: the commit records the batch id, so a retry is skipped

  4. Delta → readers

    Readers only ever see committed versions

Spark's exactly-once covers the hop from a replayable sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → to an idempotent sink. It cannot remove duplicates that a producer already wrote into the topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more →: two copies in Kafka become two rows in Delta, each written exactly once. An end-to-end guarantee is as strong as the weakest hop, unless a later hop removes the duplicates.

Idempotent sinks

An idempotent write has the same effect whether it runs once or twice. Each sink gets there differently:

SinkHow a repeated batch becomes a no-op
Delta with writeStreamThe commit stores the query id and batch id; a batch already committed is skipped
Delta inside foreachBatchPass txnAppId and txnVersion (the batch id); Delta ignores a pair it has already seen
A table with a keyMERGE that inserts only ids that are not there yet, or keeps the latest version per key
A database over JDBCUpsertupsert: Update a row if its key already exists, insert it if not. Done with MERGE in Delta. Learn more → on a unique key, or delete the batch's rows and insert them again in one transaction
KafkaNot idempotent: consumers must deduplicate on a key
PySpark · An append in foreachBatch that is safe to repeat
def to_silver(batch_df, batch_id):
    (batch_df.write.format("delta")
        .option("txnAppId", "orders_to_silver")  # stable for this query
        .option("txnVersion", batch_id)          # skipped if already written
        .mode("append")
        .saveAsTable("silver.orders"))

orders.writeStream.foreachBatch(to_silver) \
    .option("checkpointLocation", "s3://chk/orders_silver/").start()
Watch out: a new checkpoint starts counting batches from 0 again. Keep the old txnAppId and Delta ignores the new query's first writes as already done. Give a query a new txnAppId whenever it gets a new checkpoint.

Deduplicate on a unique event id

An idempotent sink handles Spark's own retries. Copies that are already in the input need something to recognise them: a unique event id, set by the producer when the event is created. An id assigned at ingestion is useless, because a retried send gets a fresh one. With the id in place, deduplicate in two layers, as Deduplicating a stream shows: dropDuplicatesWithinWatermark in the stream for copies that arrive close together, and a MERGE that inserts only new ids at the sink for copies of any age.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session with Delta Lake, with spark already created: each builds its own data.

Goal: Replay a micro-batch the way a crash does, and see which write survives it unchanged.

Production patternPySpark · A crash before the commit replays a batch: plain append vs txnVersion
import json, os

os.makedirs("lab/delivery/in", exist_ok=True)
with open("lab/delivery/in/orders-1.json", "w") as f:
    f.write("\n".join(json.dumps({"order_id": i, "amount": 10 * i}) for i in (1, 2, 3)))


def write_both(batch_df, batch_id):
    print(f"foreachBatch called for batch {batch_id}")
    batch_df.write.format("delta").mode("append").save("lab/delivery/plain")
    (batch_df.write.format("delta")
        .option("txnAppId", "orders_to_silver")    # stable for this query
        .option("txnVersion", batch_id)            # Delta skips a version it has
        .mode("append")
        .save("lab/delivery/idempotent"))


def run():
    (spark.readStream.schema("order_id INT, amount INT").json("lab/delivery/in")
        .writeStream.foreachBatch(write_both)
        .option("checkpointLocation", "lab/delivery/_chk")
        .trigger(availableNow=True)
        .start().awaitTermination())


run()
# simulate a crash after the writes but before Spark recorded batch 0 as done
for f in ("0", ".0.crc"):
    os.remove(f"lab/delivery/_chk/commits/{f}")
run()                       # the restarted query runs batch 0 again

for name in ("plain", "idempotent"):
    rows = spark.read.format("delta").load(f"lab/delivery/{name}").count()
    print(f"{name}: {rows} rows")

Output from a real run

foreachBatch called for batch 0
foreachBatch called for batch 0
plain: 6 rows
idempotent: 3 rows

What to notice:

  • foreachBatch ran twice for batch 0: without commits/0, the restarted query treats the batch as unfinished and runs it again on the same input.
  • The plain append now holds 6 rows: every order twice.
  • The table written with txnAppId and txnVersion still holds 3: Delta saw version 0 of orders_to_silver again and skipped it.

Common mistakes

  • Calling a pipeline exactly-once because Spark is — Spark covers source to sink. Copies a producer wrote into Kafka come out the other end. Ask what every hop guarantees.
  • Generating the event id at ingestion — A retried send gets a new id, so nothing can tell it is a copy. The producer sets the id when the event is created.
  • Keeping txnAppId after replacing the checkpoint — Batch ids restart at 0 and Delta skips the writes as already committed. Use a new txnAppId.
  • A plain append inside foreachBatch — A re-run batch is appended twice. Pass txnVersion, or MERGE on the event id.

Key takeaways

  • At-most-once can lose events, at-least-once can repeat them, exactly-once means each event affects the output once.
  • Most hops are at-least-once: a sender cannot tell a lost message from a lost acknowledgement, and resending is safer than losing.
  • Exactly-once = replayable source + at-least-once processing + an idempotent sink.
  • Duplicates already in the input need a unique event id set by the producer, removed in the stream or at the sink.

Interview prep

THE QUESTION

"Your pipeline is Kafka → Spark → Delta and the team says it is exactly-once. Is it?"

From Kafka to Delta, yes: offsets are replayable, the checkpoint records each batch before it runs, and the Delta sink skips a batch it has already committed. End to end, not necessarily: producers writing to Kafka are at-least-once, so a resend after a timeout or an application restart puts two copies of an event in the topic, and Spark writes both. To close the gap, the producer stamps every event with a unique id when it is created, the stream drops duplicates within a watermark, and the sink inserts an id only if it is new. Exactly-once is a property of the whole chain, decided by its weakest hop.

Avoid: "Spark is exactly-once, so the pipeline is" without asking what the producers upstream and the consumers downstream guarantee.

Follow-ups · answer out loud, then open

Follow-up"What does Kafka's idempotent producer protect against, and what not?"
Duplicates from its own retries: the broker tracks a producer id and a sequence number per partition, and drops a resent batch it already has. It does not help when the application sends again, for example after a crash and restart: the new producer session gets a new producer id. For that you need an event id and deduplication downstream, or Kafka transactions read by read_committed consumers.
Scenario"foreachBatch writes each micro-batch to a Postgres table, and after a restart some rows appear twice. Fix it."
The batch was re-run after the insert but before Spark recorded its commit, so the plain INSERT ran twice. Make the write idempotent: a unique constraint on event_id with INSERT ... ON CONFLICT (event_id) DO NOTHING, or, in one transaction, delete the rows tagged with this batch_id and insert them again.
Trap"Exactly-once means Spark reads each Kafka message once."
No. After a crash Spark reads and processes the unfinished batch again. Exactly-once describes the effect on the output: the sink recognises the repeated batch and skips it. Side effects outside the sink, such as calling an API from a UDF, can still happen twice.

Check yourself

3 questions

A consumer commits its offset, then processes the message, and crashes in between. Which guarantee is that?

Show the answer

At-most-once. The position moved past a message that was never processed: it is lost, but never processed twice.

A Spark query writes to Kafka and a micro-batch is retried. What can consumers see?

Show the answer

Duplicate messages. The Kafka sink is at-least-once: the retried batch sends its messages again.

A foreachBatch query gets a new checkpoint but keeps its txnAppId. What happens to its first writes?

Show the answer

Ignored as already committed. Batch ids restart at 0, and Delta skips (txnAppId, txnVersion) pairs it has already recorded.

Practise this

Interview problems on streaming, graded on hidden tests

Keep going

Up next · Correct results end to end · lesson 2 of 3 · 7 min read
Ordering and out-of-order events
What order Kafka really guarantees, why global order is expensive, and how event time and sequence numbers put events back in order.

Related lessons

Previous: Schemas and Schema Registry

Primary sources: Fault tolerance semantics · foreachBatch · Writing data to Kafka · Idempotent table writes in foreachBatch · Kafka producer configs: enable.idempotence