Exactly Once Semantics
At Least Once vs Exactly Once Processing
Exactly once semantics means a pipeline's results reflect every record 1 time, so no record is lost or counted twice, even when crashes force it to retry. At least once processing also loses nothing but can repeat a record after a failure, so the difference between the 2 is whether a replay can change the result a second time.
What is exactly once semantics?
Exactly once semantics is a guarantee about results: after any crash or retry, and after any rebalance, the state and output of a pipeline are what they would be if every input record had been processed 1 time. It is the strongest of the 3 delivery guarantees. At most once lets records be lost, at least once lets them be repeated, and exactly once allows neither.
The guarantee describes results, which is what semantics means here. No system promises that a record crosses the network once or that your code runs on it once. Retries still happen, and the promise is that they leave no trace: a record that was read twice and computed twice still moves the count by 1.
The Apache Kafka design documentation defines the 3 levels in a line each. At most once: messages may be lost but are never redelivered. At least once: messages are never lost but may be redelivered. Exactly once: each message is processed once and only once.
At most once vs at least once vs exactly once
- Records lost
- Records repeated
- Offset is committed
- Sink must be
- Added latency
- Records lostPossible
- Records repeatedNever
- Offset is committedBefore the write
- Sink must beAnything
- Added latencyNone
- Records lostNever
- Records repeatedPossible
- Offset is committedAfter the write
- Sink must beAnything
- Added latencyNone
- Records lostNever
- Records repeatedNever in results
- Offset is committedWith the write
- Sink must beIdempotent or atomic
- Added latency1 commit interval
At least once vs exactly once: the same crash, 3 results
The 3 guarantees differ in 1 decision: when the consumer records its position relative to when it writes its output. Take a consumer that reads a payments topic of 100 records, each a payment of $25, in batches of 10, and adds each one to a totals table. The correct total is $2,500. The process dies while handling offsets 40 to 49, after 6 of the 10 writes have landed.
If the consumer commits the offset first and writes second, the committed position is already 50 when it restarts. Offsets 46 to 49 were never written and never will be: 4 records are lost, and the table holds 96 payments worth $2,400. That's at most once. If it writes first and commits second, the committed position is still 40, so the restart replays the whole batch on top of the 6 writes that survived. Nothing is lost, 6 records are written twice, and the table holds 106 payments worth $2,650. That's at least once.


Exactly once removes the gap between the 2 steps. The 10 writes and the move to offset 50 become 1 atomic change, so a crash leaves either both or neither. A restart then finds the position at 40 with none of the batch visible. It replays the batch, and the table ends at 100 payments worth $2,500.
At least once and exactly once both replay the batch. The difference is whether the replay can change the result a second time, and that is decided by the sink, not by the broker.
Know Exactly Once Semantics the way the interviewer who asks it knows it.
Why exactly once delivery is impossible and exactly once processing is not
A sender that gets no acknowledgment cannot tell 3 cases apart: the message never arrived, the receiver crashed after handling it, or the acknowledgment was lost on the way back. It can resend and risk a duplicate, or it can give up and risk a loss. No protocol removes that choice, which is why no network delivers a message exactly 1 time.
Exactly once processing accepts the duplicate and neutralizes it. Delivery stays at least once, and the receiving side makes a second arrival harmless. Some engineers call the result effectively once for that reason, and the name is more accurate, though the industry has settled on exactly once.
The engines say the same in their own words. The Flink documentation on fault tolerance states that exactly once does not mean every event is processed exactly once. It means every event affects the state Flink manages exactly once. Google Dataflow describes its guarantee as records processed at least once with results committed exactly once.
How exactly once processing is built: 2 mechanisms
Every exactly once system starts from a replayable source and at least once delivery, then adds 1 of 2 mechanisms so that a replay cannot change the result twice.
An idempotent write is one where the same record written twice leaves the sink as it was after the first write. An upsert keyed on an event id, a file written to a path derived from the batch id, and a MERGE on a natural key are all idempotent. A blind INSERT and a total = total + amount update are not. A deduplication table of seen ids is the same idea with the key held beside the data. The guide to idempotency in data engineering covers the write patterns in depth.
An atomic commit changes the output and the record of how far the input has been read in 1 transaction. A process that dies before the commit leaves neither behind, so the replay starts clean. Kafka transactions do this inside Kafka, Flink does it with checkpoints and a 2 phase commit, and a consumer writing to Postgres can do it by storing its offsets in the same database transaction as its rows.
Idempotent writes are cheaper and survive replays from any point in time, including a backfill months afterwards. Atomic commits work for writes that can't be keyed, such as appends to a log, but only within the system that runs the transaction.
The Kafka idempotent producer
Kafka has had an idempotent producer since version 0.11.0.0. The broker assigns each producer an id, and the producer numbers every batch it sends to a partition in sequence. When a send times out and the producer retries, the broker sees a sequence number it has already written and drops the batch instead of appending it again. A retry can no longer put the same record in the log twice or out of order.
It is on by default: enable.idempotence defaults to true and acks to all, with up to 5 requests in flight per connection.
Its scope is narrow. The producer id belongs to 1 producer session, so a restarted producer gets a new id and the broker cannot recognize what the old one sent. It also dedupes only the client's own retries. If your code calls send() twice for the same event, because an upstream job was rerun, Kafka writes 2 records. And it says nothing about the consumer side, where the commit order decides between loss and duplicates.
Kafka transactions: output and offsets in 1 commit
Transactions extend the idempotent producer to the read, process, write loop. A producer configured with a transactional.id can write to several partitions atomically, and it can include the consumer's offsets in the same transaction with sendOffsetsToTransaction(). Offsets are records in the __consumer_offsets topic, so committing a position is 1 more write in the set.
Run the batch of 10 payments through it. The application reads offsets 40 to 49, begins a transaction, writes 10 records to payment_totals, adds offset 50 for its consumer group and commits. The coordinator writes a commit marker to every partition involved. If the process dies before that, the coordinator aborts: the 10 records stay in the log behind an abort marker, and the group's position stays at 40.


The transactional.id survives restarts, which closes the gap the plain idempotent producer leaves. When a new instance registers with the same id, the coordinator raises its epoch and rejects writes from the old instance, so a process that was presumed dead and wakes up cannot commit stale work.
Readers have to opt in. Aborted records are physically in the partition, and a consumer skips them only when its isolation.level is read_committed. The default is read_uncommitted, which returns everything. A transaction left open longer than transaction.timeout.ms, 60,000 ms by default, is aborted by the coordinator.
Kafka Streams wraps all of this in 1 setting called processing.guarantee=exactly_once_v2. Kafka Connect has supported exactly once source connectors since version 3.3.0. The settings come up often in Kafka interview questions.
Kafka settings behind exactly once, with their defaults
enable.idempotenceackstransactional.idtransaction.timeout.msisolation.levelprocessing.guaranteecommit.interval.msexactly.once.source.supportExactly once in Flink: checkpoints and 2 phase commit
Flink gets exactly once for its own state from checkpoints. At an interval you set, it injects barriers into the stream, and each operator snapshots its state when the barrier reaches it. Together with the source offsets recorded in the same checkpoint, the snapshots describe 1 consistent moment of the whole job. After a failure Flink restores that moment and rewinds the sources to the recorded offsets. Records after the checkpoint are processed again, but the state they are applied to has been rolled back, so each one counts once.
That covers state inside Flink. Output is a different matter: records emitted between the checkpoint and the failure have already left. For exactly once end to end, the documentation names 2 requirements: sources must be replayable, and sinks must be transactional or idempotent.
The transactional sink is a 2 phase commit tied to the checkpoint. The sink writes into an open transaction, pre-commits it when the checkpoint barrier arrives, and commits only after Flink confirms that the checkpoint completed everywhere. Flink 1.4.0, released in December 2017, packaged the pattern as TwoPhaseCommitSinkFunction. With the Kafka sink set to DeliveryGuarantee.EXACTLY_ONCE, records become visible to read_committed consumers only when a checkpoint completes, so the checkpoint interval is the floor on latency.
If a job stays down longer than the Kafka transaction.timeout.ms, the broker aborts the pre-committed transaction and those records are gone, so the Flink documentation asks for a timeout larger than the longest checkpoint plus the longest restart you expect.
Exactly once in Spark Structured Streaming
Structured Streaming builds the guarantee from replay plus idempotence. Before it processes a micro-batch, the engine records the batch's offset range in a write ahead log in the checkpoint location. After a failure it reruns the same range under the same batch id, and a sink that recognizes the batch id discards the repeat.
The guarantee therefore varies by sink, and the Spark documentation lists each one. The file sink is exactly once. The Kafka sink is at least once, and so is foreach. foreachBatch is at least once by default, and the documentation says the batchId passed to your function is the way to deduplicate and reach exactly once.
In practice that means a foreachBatch that writes to a warehouse should either MERGE on a key or record the batch id in the same transaction as the rows and skip a batch id it has seen. For duplicates that arrive in the data itself, dropDuplicates on an event id with a watermark keeps the deduplication state bounded.
Exactly once guarantees by system and where each one stops
| System | How it gets there | Where the guarantee stops |
|---|---|---|
| Kafka transactions and Kafka Streams | Output records and consumer offsets commit in 1 transaction | At the cluster edge and at any consumer left on read_uncommitted |
| Flink | Checkpointed state, replayable sources and sinks that commit with the checkpoint | At a sink that is neither transactional nor idempotent |
| Spark Structured Streaming | Offset ranges in a write ahead log and sinks that are idempotent per batch | At the Kafka and foreach sinks, which are at least once |
| Google Dataflow | Records processed at least once, results committed once | At side effects such as calls to an outside service |
| Google Pub/Sub exactly once delivery | No redelivery of an acknowledged message, on pull subscriptions within 1 region | At duplicates the publisher itself sent |
| Amazon SQS FIFO queues | A retried send with the same deduplication id is dropped for 5 minutes | At a retry that arrives after the 5 minute interval |
Where exactly once ends
Every exactly once guarantee has a boundary, and most production duplicates come from just outside it.
Side effects are outside. An email or a webhook sent from inside a transform is not rolled back when the batch is, and neither is a charge. Google says so directly for Dataflow: side effects aren't guaranteed to have exactly once semantics. The fix is to pass an idempotency key that the receiving service dedupes on, or to write the intent to a table and send from there.
Upstream is outside. If a mobile client retries an upload or a CDC job is restarted from an old position, the same business event enters the pipeline as 2 distinct records. The engine processes each of them exactly once, and the total is still wrong. Only a key that identifies the event, carried from the producer, lets anything downstream tell.
Time windows are a boundary too. Deduplication state cannot be kept forever, so it expires by a watermark or a fixed interval, and a duplicate that arrives after the window passes through. Late records are a separate question: exactly once says a record that is processed counts once, not that every record arrives in time to be processed.
A warehouse table that already holds duplicates needs a cleanup pass of its own, and removing duplicates in a data pipeline covers the SQL for it.
Exactly once into a database or warehouse
Kafka transactions end at the edge of the cluster, so the last hop into Postgres or a lake table, or into a warehouse such as Snowflake or BigQuery, needs its own answer. The Kafka documentation gives the simple one: let the consumer store its offset in the same place as its output.
For a database that means 1 transaction that inserts the batch and updates a small offsets table keyed by topic and partition. On restart the consumer reads its position from that table, not from Kafka. In the payments example, a crash mid-batch rolls back the 6 rows together with the offset, and the consumer resumes from 40 with nothing to clean up.
Where a transaction across data and offsets isn't available, the write has to be idempotent. Each record needs a deterministic key, the event id if the producer supplies one, or topic, partition and offset if not, and you MERGE on it so a replayed row updates itself. For files, the path is derived from the batch id or the offset range and overwritten, so a replay replaces the same object.
An increment is the 1 write that cannot be made idempotent in place. Store the events and derive the total from them, or keep the offset the total was computed up to in the same row, so a replay can see it has already been applied.
What exactly once costs and when at least once is enough
The cost is mostly latency. Output stays invisible until its transaction commits, so a reader waits for the commit interval. Kafka Streams shows the trade in its defaults: commit.interval.ms is 30,000 under at least once and 100 under exactly_once_v2, because each commit now gates what downstream consumers see. In Flink the wait is the checkpoint interval. Google notes that Pub/Sub subscriptions with exactly once delivery have significantly higher publish to subscribe latency, and that Dataflow's at least once mode can cut cost and latency for pipelines that tolerate duplicates.
Part of the cost is operational: transaction timeouts to size, transactional ids to keep unique, consumers that must all read committed data, and failure modes that stall a partition instead of duplicating a record.
The decision rule is to ask what a duplicate does at the sink. If the write is an upsert on a key or a set insert, a replay changes nothing and at least once is already correct, and the same holds for a max or a latest value. If the write adds or counts, or if it appends or triggers something outside, a replay is a wrong number or a second charge, and the pipeline needs either an idempotent key or a transaction.
Most teams land on at least once delivery with idempotent writes for everything that reaches a warehouse, and reserve transactions for stream to stream jobs inside Kafka or Flink. The same reasoning applies to batch jobs, which is 1 of the points where batch vs streaming designs differ less than they first appear.
How exactly once comes up in data engineering interviews
Interviewers rarely ask for the definition. They ask what happens to your design when a worker dies between the write and the commit, and they listen for whether you name the boundary of the guarantee. An answer that says the pipeline is exactly once because Kafka is exactly once has missed the sink.
A strong answer walks the path: the source is replayable, delivery is at least once, the write is keyed so a replay is a no-op, and the 1 place a duplicate could still enter is named along with what catches it. The follow-up is usually about cost, so know what the commit interval does to latency and when you would decline the guarantee.
The data pipeline interview questions include the delivery and failure questions asked in design rounds, and the data pipeline practice problems let you draw a streaming design and defend where its duplicates go. For the format of the round itself, see the guide to the data engineering system design round.
Exactly once semantics FAQ
What does exactly once semantics mean?+
What is the difference between at least once and exactly once?+
Is exactly once delivery actually possible?+
Does Kafka guarantee exactly once?+
Is Kafka exactly once by default?+
What is the difference between exactly once and idempotence?+
When is at least once processing enough?+
The candidate who gets the offer
- 01
Reading a solution is not the same as writing one
Every engineer who has frozen on a query they had read a dozen times knows the gap. The only preparation that closes it is producing the answer yourself, under time, before the interview does it for you
- 02
76% of hiring managers reject on the coding task, not the resume
From HackerRank's 2024 Developer Skills Report. Candidates who look strong on paper still fail the live screen if they haven't done timed, executable practice
- 03
System design comes down to the calls you defend out loud
Ingestion, batch vs streaming, the bronze/silver/gold layers, idempotency, backfill and replay. Sketching the pipeline and naming the failure modes is the signal, not the boxes
Related guides
Idempotency in data engineering
The write patterns that make a replay harmless
Remove duplicates in a data pipeline
Deduplication SQL for rows that already landed twice
Batch vs streaming data pipelines
How the 2 processing models differ and when each fits
Kafka interview questions
Questions on producers and consumers, plus offsets and transactions
Data pipeline interview questions
The pipeline design and failure questions interviewers ask
Data pipeline practice problems
Pipeline design problems to practice before the loop
Data engineering system design round
What the design round asks and how to prepare for it
Compete in the Weekly
Dirty, production-shaped data, scored blind each week.