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.

Last updated: Proudly published by: Jeff Wahl13 min read

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

At most once
  • Records lostPossible
  • Records repeatedNever
  • Offset is committedBefore the write
  • Sink must beAnything
  • Added latencyNone
At least once
  • Records lostNever
  • Records repeatedPossible
  • Offset is committedAfter the write
  • Sink must beAnything
  • Added latencyNone
Exactly once
  • 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.

A batch of 10 records with a crash after the 6th write, under 3 guarantees: at most once commits first and loses 4 records, at least once writes first and writes 6 records twice, exactly once uses 1 transaction and writes all 10 onceA batch of 10 records with a crash after the 6th write, under 3 guarantees: at most once commits first and loses 4 records, at least once writes first and writes 6 records twice, exactly once uses 1 transaction and writes all 10 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.

Prepare for the interview
01 / Open invite
02min.

Know Exactly Once Semantics the way the interviewer who asks it knows it.

a Exactly Once Semantics query, the same shape a screen would give you.
The diff against expected. Where ties broke. What you missed.
sandbox
1source → bronze → silver → gold
2 ingest : CDC + Kafka
3 transform : dbt + Airflow
4 serve : Snowflake
5
Execute your solution0.4s avg.
PinterestInterview question
Solve a Exactly Once Semantics problem

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.

2 outcomes of 1 Kafka transaction: committed, the 10 records in payment_totals are visible behind a commit marker and the offset in __consumer_offsets advances to 50; aborted, the 10 records are hidden behind an abort marker and the offset stays at 402 outcomes of 1 Kafka transaction: committed, the 10 records in payment_totals are visible behind a commit marker and the offset in __consumer_offsets advances to 50; aborted, the 10 records are hidden behind an abort marker and the offset 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.idempotence
Producer, default true: the broker drops a retried batch it has already written
acks
Producer, default all: required by idempotence
transactional.id
Producer, unset by default: setting it turns transactions on and fences older instances
transaction.timeout.ms
Producer, default 60,000: the coordinator aborts a transaction open longer than this
isolation.level
Consumer, default read_uncommitted: set read_committed to skip aborted records
processing.guarantee
Kafka Streams, default at_least_once: exactly_once_v2 needs brokers on 2.5 or newer
commit.interval.ms
Kafka Streams, default 30,000: drops to 100 under exactly_once_v2
exactly.once.source.support
Kafka Connect worker: set enabled for exactly once source connectors, distributed mode only

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

SystemHow it gets thereWhere the guarantee stops
Kafka transactions and Kafka StreamsOutput records and consumer offsets commit in 1 transactionAt the cluster edge and at any consumer left on read_uncommitted
FlinkCheckpointed state, replayable sources and sinks that commit with the checkpointAt a sink that is neither transactional nor idempotent
Spark Structured StreamingOffset ranges in a write ahead log and sinks that are idempotent per batchAt the Kafka and foreach sinks, which are at least once
Google DataflowRecords processed at least once, results committed onceAt side effects such as calls to an outside service
Google Pub/Sub exactly once deliveryNo redelivery of an acknowledged message, on pull subscriptions within 1 regionAt duplicates the publisher itself sent
Amazon SQS FIFO queuesA retried send with the same deduplication id is dropped for 5 minutesAt 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?+
Exactly once semantics means the results of a pipeline look as if every record had been processed 1 time, even though failures force the system to retry. Records can be read and computed more than once behind the scenes. The guarantee is that state and output reflect each record once, so no record is lost or counted twice.
What is the difference between at least once and exactly once?+
At least once never loses a record but can process it again after a failure, so the output may hold duplicates. Exactly once also never loses a record, and it adds either an atomic commit or an idempotent write so that a replay can't change the result a second time.
Is exactly once delivery actually possible?+
Delivering a message over a network exactly 1 time is not possible, because a sender that gets no acknowledgment cannot tell a lost message from a lost acknowledgment and has to choose between resending and giving up. Exactly once processing is possible: the system retries, and makes the retries invisible in the results.
Does Kafka guarantee exactly once?+
Kafka has supported it since version 0.11.0.0, through an idempotent producer and transactions that commit output records and consumer offsets together. The guarantee covers work that reads from Kafka and writes to Kafka, and only for consumers that set isolation.level to read_committed. A write to an external database needs its own idempotent or transactional sink.
Is Kafka exactly once by default?+
Only partly. The producer's enable.idempotence setting defaults to true, so retries of a send do not duplicate records in the log. Transactions are off until you set a transactional.id, a consumer's isolation.level defaults to read_uncommitted, and Kafka Streams defaults to at_least_once.
What is the difference between exactly once and idempotence?+
Idempotence is a property of an operation: applying it twice leaves the same result as applying it once. Exactly once is a guarantee about a whole pipeline's results. Idempotent writes are 1 of the 2 ways to build that guarantee on top of at least once delivery, and atomic transactions are the other.
When is at least once processing enough?+
When the sink removes duplicates by itself or duplicates do not matter. An upsert keyed on an event id tolerates a replay, and so does a max or a latest value. The same goes for a cache refresh and most monitoring metrics. Sums and counts do not, and neither do payments and notifications, unless the write carries a key that makes the replay a no-op.
02 / Why practice

The candidate who gets the offer

  1. 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

  2. 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

  3. 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