SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

Exactly-Once Processing

What it really takes for an effect to happen once: idempotence, transactions and dedupe working together.

โฑ 14 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Exactly-once processing means that the effect of a message (a charge, a row, a count) happens one time, even when the message is delivered more than once. True exactly-once delivery over a network is impossible, so we build it from at-least-once delivery plus safe repeats.

  • Retries and crashes are normal, so duplicates will reach your code.
  • Three tools remove the harm: idempotency keys, a transaction that saves the result and the offset together, and the outbox/inbox pair.
  • Say "effectively once". It is honest, and it is what real systems promise.

02Concept: What is it?

A message system can fail in two places: the send (the ack is lost, so the sender sends again) and the receive (the consumer does the work, then crashes before it records that it did). In both cases the safe choice is to try again, because a lost message is worse than a repeated one. That gives at-least-once delivery.

The reason we cannot have "exactly once" on the wire is the Two Generals problem. A sender can never be sure whether a missing ack means "the message was lost" or "the message arrived and only the ack was lost". It must choose between risking a loss and risking a repeat.

So the goal moves from delivery to processing. We accept repeats, and make sure applying the same message twice has the same effect as applying it once. This is effectively-once (or "exactly-once semantics"). The two ingredients are always the same: at-least-once delivery and idempotent or atomic processing.

Where exactly-once comes from
๐Ÿ”At-least-onceretry until acked
โ†’โ†“plus
๐Ÿ›ก๏ธDedupe or transactionrepeats do nothing
โ†’โ†“gives
๐ŸŽฏExactly-once effectone charge, one row
At-least-once never loses a message. Idempotence or a transaction makes the repeats harmless.
๐Ÿง Delivery versus effect
Messages may arrive twice. The effect must happen once. When someone says "exactly-once", ask which boundary they mean: the broker, the stream job, or the final database.

03Real-Life Example

๐ŸตPosting a Cheque into the Bank
You post a cheque to the bank. Your letter might get lost, so if you hear nothing you post a second copy. The bank might now receive both. A good bank writes the cheque number in a book the first time it pays. When the second copy arrives, it sees the number is already in the book and does nothing. You were free to send as many copies as you liked. The money moved once.
The cheque
Exactly-once processing
Posting copies until you hear back
At-least-once delivery with retries
The cheque number
An idempotency key or message id
The bank's book of paid numbers
A processed-ids table
Writing the number and paying in one step
Saving the effect and the id in one transaction
Paying, then the bank burns down before writing it down
A crash between the effect and the offset
Second copy is ignored
Duplicate dropped
One payment on your account
Exactly-once effect
The same message, twice
๐Ÿ“จpay-2first delivery
โ†’โ†“charge, save id
๐Ÿ’ณCharged $10id pay-2 recorded
โ†’โ†“pay-2 again
๐Ÿ›ก๏ธId already seenskip, no second charge

04Why Do We Need It?

๐Ÿ’ธMoney must move once
A double charge or a double payout is a real loss and a support ticket.
๐Ÿ”Retries are unavoidable
Timeouts, lost acks and restarts happen every day. The only safe reaction is to try again.
๐Ÿ“ŠCorrect numbers
Counts, sums and balances come out wrong if some events are counted twice.
๐ŸšซLosing is worse
At-most-once drops data. For most business flows, dropping is not acceptable.
๐Ÿง˜Simpler consumers
If the platform handles repeats, application code can stay plain.
๐Ÿ”ญFewer 2 a.m. fixes
No manual clean-up of duplicate rows after an outage.
You cannot stop the repeats, so you make the repeats harmless.

05Where Do We Use It?

๐Ÿ’ณPayments
Charge once per order id, even if the request is retried.
๐ŸŒŠStream processing
Counting, joining and aggregating events in Kafka Streams or Flink without double counts.
๐Ÿ“ฌMessage consumers
Order, email and inventory handlers that read from a queue.
๐ŸฆLedgers
Each transfer must post once, or the books will not balance.
๐Ÿ“ฅData pipelines
Loading events into a warehouse without duplicate rows.
๐ŸชWebhooks
A sender retries a callback until it gets a 200. The receiver must tolerate that.

06Types / Parts / How It Works

Where the duplicates come from

FailureWhat happensResult
Producer ack lostThe producer sends the same message againTwo copies in the log
Consumer crashes after the work, before the ack or offsetThe message is redelivered after restartThe work is done twice
Consumer is slow, and the broker redeliversTwo consumers hold the same messageParallel duplicate work
Network retries by a client or proxyThe same request arrives twiceA duplicate write
Replay by an operatorOld events are processed again on purposeEverything is repeated

Three tools that make it effectively-once

Choose a tool, or combine them
1. Idempotency key
๐Ÿ”‘Unique id per actionstore it, skip repeats
๐Ÿ—„๏ธUnique constraintthe database refuses a repeat
2. Atomic offset + result
๐ŸงพOne transactionresult and offset together
๐Ÿ“กKafka EOS, Flinktransactions or checkpoints
3. Outbox and inbox
๐Ÿ“คOutboxpublish what you saved
๐Ÿ“ฅInboxremember what you got
Each one solves a different gap in the journey.
ToolHow it worksWorks when
Idempotency keyEach action carries a unique id. The receiver stores it, and ignores a repeatThe effect is in a store you control
Atomic offset and resultThe consumer writes its output and its read position in one transaction. Both commit or both roll backInput, output and offsets live in the same system
Kafka transactions (EOS)An idempotent producer plus transactional writes to output topics and offsets. Readers use read_committedKafka to Kafka flows
Flink two-phase commit sinkA checkpoint marks a consistent point. The sink pre-commits, then commits after the checkpoint succeedsThe sink supports transactions or idempotent writes
Inbox tableSave the message id and the effect in one local transactionThe effect is a database write
Outbox tableSave the change and the outgoing event in one transaction. A relay publishes it, possibly more than onceYou need to publish events reliably
Works anywhere Works inside one system Works at the edges of a service

What each layer gives you

๐Ÿ“คProduceridempotent: no duplicate in the log
โ†’โ†“
๐Ÿ“œBroker logstores each message once
โ†’โ†“
โš™๏ธConsumeratomic result and offset
โ†’โ†“
๐Ÿ—„๏ธFinal storeidempotent write or dedupe
VisualizerCount the duplicate chargesSwitch on the lost ack and the consumer crash with 'Nothing', and see pay-2 charged more than once. Then try dedupe by id, and then the transaction option.
Producer ack lost, so it retries pay-2
Consumer crashes after charging, before saving offset
How does the processing protect itself?
๐Ÿ’ธ
pay-1
Applied 1 time
Customer charged $10
๐Ÿ’ธ
pay-2
Applied 3 times
Customer charged $30
๐Ÿ’ธ
pay-3
Applied 1 time
Customer charged $10
Deliveries
5
messages the consumer saw
Real effects
5
charges applied
Duplicate effects
2
should be 0
Total charged
$50
should be $30
  1. Producer: the ack for pay-2 was lost, so it sends pay-2 again.
  2. Consumer: pay-1 charged $10.
  3. Consumer: pay-2 charged $10, then it CRASHES before committing the offset.
  4. Consumer restarts and re-reads pay-2, because its offset was never saved.
  5. Consumer: pay-2 charged $10.
  6. Consumer: pay-2 (repeat) charged $10.
  7. Consumer: pay-3 charged $10.
At-least-once delivery with no protection: pay-2 reached the consumer more than once (a producer retry and/or a crash before the offset was saved), so the customer was charged $50 instead of $30. Retries and crashes are normal, so the consumer has to cope with repeats.

A simplified model with one fixed failure pattern (no random numbers). The log lines show only the unusual events.

07How to Use It / Steps / Implementation

Building it

  1. 1
    Pick at-least-once delivery
    Ack only after the work is done. Never use at-most-once for data that matters.
  2. 2
    Give every message a stable id
    The id must be the same on every retry. Make it from the business (order id), or let the producer set it once.
  3. 3
    Make the producer idempotent
    Turn on the idempotent producer (in Kafka, enable.idempotence). The broker then drops resends of the same sequence number.
  4. 4
    Save the effect and the id together
    Insert into the processed-ids table and apply the change in one local transaction. A unique key stops a second insert.
  5. 5
    Or save the effect and the offset together
    If input and output are in one system, commit the output and the new offset atomically. Kafka transactions do this for Kafka.
  6. 6
    Make outgoing calls idempotent too
    Pass the same idempotency key to the payment API, so its own retries are safe.
  7. 7
    Use read_committed on readers
    When writers use transactions, readers must ignore uncommitted data.
  8. 8
    Test the nasty cases
    Kill the consumer between the effect and the ack. Replay a day of events. Count the rows.
๐Ÿ’กA few lines of code
BEGIN; INSERT INTO processed(id) VALUES (:id) ON CONFLICT DO NOTHING; if inserted: apply effect; COMMIT; ack
โš ๏ธThe boundary is the limit
Exactly-once in Kafka covers Kafka to Kafka. The moment you call a payment API, send an email or write to another database, you need an idempotency key at that edge.

08Key Terms to Know

TermMeaning in easy words
Exactly-once processingThe effect of each message happens one time, even if it is delivered more than once
At-least-onceA message is retried until acked, so it may arrive more than once
Effectively-onceAnother name for exactly-once effect: at-least-once plus safe repeats
Idempotency keyA unique id that lets a receiver recognise a repeat
Idempotent producerA producer whose resends are dropped by the broker using sequence numbers
OffsetThe reader's position in a log. Saving it marks the work as done
Transactional writeOutput and offset saved together, so both happen or neither
read_committedA reader mode that ignores data from unfinished transactions
CheckpointA consistent snapshot of a stream job (as in Flink) that it can restart from
Two-phase commit sinkA sink that pre-commits, then commits after the checkpoint succeeds
Inbox / OutboxTables that remember received messages and queue messages to publish
Zombie producerAn old instance that still writes after a new one took over. Epochs or fencing stop it

09Pros, Cons and Trade-offs

โœ… Pros
  • Correct results despite retries and crashes
  • No lost data and no double data
  • Simple mental model: repeats are harmless
  • Platform support reduces custom code
  • Safe to replay history
โš ๏ธ Cons
  • Extra storage for ids or transaction state
  • Extra latency from transactions and commits
  • Only holds inside a boundary, not forever
  • Hard to test failure points
  • Dedupe tables need cleaning up

Trade-offs

ChoiceWe gainWe lose
Dedupe tableWorks with any brokerStorage, and a lookup for each message
Kafka transactionsAtomic read, process, writeLower throughput, Kafka-only boundary
Short id retentionSmall tableA late duplicate may slip through
Long id retentionCatches late repeatsMore storage and cleanup
Natural idempotent write (upsert, set)No extra tableNot every effect can be an upsert
At-most-once insteadLowest costLost data

10Common Problems and Mistakes

Common mistakes

  1. Believing the broker label. Exactly-once in one system does not cover the email or API call that follows.
  2. Saving the id in a different store from the effect. A crash between the two writes brings back the duplicate (or a loss).
  3. Acking before the work. That is at-most-once. A crash loses the message.
  4. A new id for each retry. Generating the key inside the retry loop defeats the check.
  5. Deleting ids too soon. A slow redelivery after the cleanup is processed again.
  6. Non-idempotent effects such as counter + 1. A repeat adds again. Use set-to-value or add with an id.
  7. Readers that see uncommitted data. Without read_committed, an aborted transaction is still read.

Things to watch

๐ŸงŸZombie writers
An old instance may still write. Use producer epochs or fencing tokens to shut it out.
โฑ๏ธTransaction timeouts
Long processing can abort a transaction and cause a retry. Keep units of work short.
๐Ÿ”€Ordering
Retries can reorder messages. Keep one key on one partition, or use version checks.
๐ŸงนDedupe cleanup
Expire ids by time, longer than your maximum redelivery delay.

11Real-World Examples

๐Ÿ“กKafka exactly-once semantics
Idempotent producers, transactions and read_committed let a Kafka Streams job read, process and write once.
๐ŸŒŠApache Flink
Checkpoints plus two-phase commit sinks give end-to-end exactly-once into sinks like Kafka.
๐Ÿ’ณStripe idempotency keys
Send the same Idempotency-Key and Stripe returns the first result, instead of charging again.
โ˜๏ธAWS SQS FIFO
A deduplication id drops repeats of the same message within a five minute window.
๐Ÿ—„๏ธDatabase upserts
INSERT ... ON CONFLICT DO NOTHING makes a plain table an inbox.
๐Ÿ“ˆSpark and warehouses
Idempotent batch writes or merge-by-key stop re-run jobs from duplicating rows.
๐Ÿ“Note
Different vendors mean different things by "exactly-once". Read the fine print for what is covered and what is not.
Mini case: crash after the charge
โš™๏ธConsumercharges, saves id, crashes before ack
โ†’โ†“redelivered
๐Ÿ”Look up idfound in the same database
โ†’โ†“skip
โœ…Ackno second charge
The id and the charge are saved in one transaction, so the retry finds the id and stops.

12Related Topics to Read Next

Delivery Semanticsโ†’

At most once, at least once and exactly once, side by side.

Idempotent Consumer and Inbox Patternโ†’

The dedupe table in detail.

Outbox Patternโ†’

Publishing events from a transaction without losing them.

Idempotencyโ†’

The core idea behind every tool on this page.

Two Generals Problemโ†’

Why exactly-once delivery is impossible.

Fencing Tokensโ†’

Keeping zombie writers out.

Kafka Deep Diveโ†’

Offsets, partitions and consumer groups.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Fact: exactly-once delivery is impossible. Exactly-once effect is possible.
  • โœ”Recipe: at-least-once delivery + idempotence or atomic commit.
  • โœ”Key: a stable unique id that survives retries.
  • โœ”Atomic: save effect and id (or offset) in one transaction.
  • โœ”Kafka: idempotent producer + transactions + read_committed.
  • โœ”Flink: checkpoints + two-phase commit sink.
  • โœ”Edges: external calls need their own idempotency key.
  • โœ”One line: โ€œYou cannot stop the repeats, so make every repeat do nothing.โ€
โ† Previous
Outbox Pattern
Next โ†’
Inverted Index