Skip to content

At-most-once, at-least-once, exactly-once

Deep diveConcept

A consumer crashes in the middle of a message. Is the message lost, handled twice, or neither? That depends on when you acknowledge it, and “exactly once” turns out to be something you build, not a setting you switch on.

01 Receive, work, acknowledge

Every consumer does three things with a message: it receives it, it does the work (writes a row, sends an email), and it acknowledges it so the broker can delete it. The broker only learns about the third. A crash can happen between any two, and the order you pick decides what a crash costs.

At-most-once
msg = queue.receive()
queue.ack(msg)
handle(msg) # crash here: lost
At-least-once
msg = queue.receive()
handle(msg) # crash here: redelivered
queue.ack(msg)
Where the crash happens, and what it costs
Consumer crashesAck first (at-most-once)Ack last (at-least-once)
Before the work startsLost: it was already ackedDelivered again; runs once
Halfway through the workLost, maybe half doneDelivered again; the done half repeats
After the work, before the ackDone once (the ack came first)Delivered again; runs twice
At-most-onceMay loseFine for metrics or log lines where a gap does no harm. Never for money.
At-least-onceMay repeatThe usual default (SQS, RabbitMQ with manual acks, Kafka consumers that commit after processing).
Exactly-once effectRepeats ignoredAt-least-once delivery plus a handler that notices a repeat and does nothing.

02 How at-least-once doubles a top-up

Ana tops up her wallet by £20. The message m7 goes through a queue to a consumer that writes to the ledger and acks last. Watch what one badly timed crash does.

Crash after the work, before the ack
Step 1 of 9
wallet-topups queue
Empty
Consumer
idle
wallet_ledger rows
Empty
  • just added
  • in flight, hidden
  • working on it
  • crashed
  • duplicate
  • consumer free

Nothing has happened yet. The queue and Ana’s wallet ledger are empty.

£0 ana’s balance

Nothing here is a bug in the broker. It did what at-least-once promises: it kept the message until it heard an ack. The bug is a handler that is not safe to run twice.

03 Why the network cannot deliver exactly once

The broker sends a message and waits for an ack. No ack comes back. Either the message never arrived, or it arrived, the work was done, and the ack got lost. From the broker’s side these look exactly the same.

  • If the broker resends, it may deliver twice: at-least-once.
  • If it does not, it may deliver zero times: at-most-once.
  • There is no third choice that is right in both cases. Waiting longer only narrows the gap, it never closes it.

So nobody really delivers exactly once over an unreliable network. What you can have is exactly-once effect: deliver at least once, and make the second delivery a no-op.

04 Exactly-once effect with a processed-ids table

Give every message a stable id, chosen once by the producer. In the consumer, record that id in the same database transaction as the work. A repeat then fails to insert the id, and you skip the work.

consumer.py
def handle(msg):
with db.transaction() as tx:
fresh = tx.execute(
"INSERT INTO processed_messages (message_id) VALUES (%s) "
"ON CONFLICT DO NOTHING",
[msg.id],
).rowcount == 1
if fresh:
tx.execute(
"INSERT INTO wallet_ledger (user_id, amount, message_id) "
"VALUES (%s, %s, %s)",
[msg.body["user"], msg.body["amount"], msg.id],
)
queue.ack(msg) # after COMMIT, never before
The same crash, now harmless
Step 1 of 9
wallet-topups queue
Empty
Consumer
idle
processed_messages
Empty
wallet_ledger rows
Empty
  • just added
  • in flight, hidden
  • working on it
  • crashed
  • already processed
  • consumer free

The same start, but the consumer now keeps a processed_messages table next to the ledger.

The id insert and the work must commit together. Check the table in one statement and write the ledger in another, without a shared transaction, and a crash between them, or two consumers racing, brings the duplicate straight back.

05 Effects outside your database

The trick needs the work and the id in one transaction. A card charge or an email is not in your database, so you cannot commit it with anything. Two options:

  • Pass the id on. Many payment APIs take an idempotency key and return the first result for a repeat. Stripe, for example, reads an Idempotency-Key header. Send m7 as the key and a redelivery cannot charge twice.
  • Accept a rare repeat. For an email, a duplicate once in a long while is usually cheaper than the machinery to prevent it. Decide this on purpose, per effect.

The producer has the mirror problem: it saves an order and publishes a message, and a crash between the two loses the message. The usual fix is an outbox: write the message into a table in the same transaction as the order, and let a separate process publish rows from that table, at least once.

06 What brokers mean by exactly-once

Some brokers advertise exactly-once. Each feature is real, but each covers a specific stretch of the path. Read what it leaves out.

Broker features and their limits
FeatureWhat it removesWhat it does not cover
Kafka idempotent producerDuplicate writes from producer retries, per partitionDuplicates your consumer creates
Kafka transactionsDuplicates in read-process-write between Kafka topics, with offsets committed in the same transactionWrites to your database, emails, API calls
SQS FIFO deduplicationRepeat sends with the same deduplication id within a 5-minute windowA consumer that does not delete the message before its visibility timeout

In Kafka, consumers must also read with isolation.level=read_committed to skip records from aborted transactions. Once your consumer touches anything outside Kafka, you are back to dedupe in your own store.

07 When the dedupe fails

The id is made too lateIf the producer creates a new id each time it retries a send, two copies of the same top-up carry different ids and both pass. Assign the id once, or derive it from the business fact (the top-up’s own id).
Ack before commitAcknowledge before the transaction commits and a crash in between loses the message: you have rebuilt at-most-once.
DELETE FROM processed_messagesCleaning up too earlyThe ids table grows by one row per message. Expire old rows, but only well after the longest time a message can be redelivered, or a late repeat slips through.
A side effect inside the transactionSend an email inside the transaction, then roll back, and the email is out while the id is not saved. The retry sends it again. Do external calls after commit, with their own key.
Repeats arrive out of orderA redelivered m7 can arrive after m8. If messages say “set balance to £40” rather than “add £20”, a late repeat can overwrite newer data. Prefer messages that are safe in any order, or carry a version number.

08 Check yourself

Question

A consumer does receive, then ack, then handle. What does it guarantee?

Question

The handler inserts the id and the ledger row in one transaction, commits, then crashes before the ack. What happens on redelivery?

Question

You turn on Kafka transactions. Each event makes your consumer write to Postgres and send an email. Is the email now exactly-once?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?