Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once Effects
It is 02:14 on Black Friday. The payment worker fleet is autoscaling from 40 to 120 pods, and every new pod triggers a consumer group rebalance. Support tickets start arriving at 02:30: “I was charged twice.” By morning there are 1,900 of them. Nothing crashed in the usual sense. Every component did exactly what it was configured to do.
The worker reads a “charge order” message, calls the payment provider, then commits its position in the queue. During each rebalance a few workers had already charged the card but not yet committed. Their partitions moved to other pods, which started from the last committed position and charged the same orders again.
The team had a queue with “exactly-once” in its marketing copy. What they did not have was a consumer that could tell a message it had already acted on from a new one. This article is about that gap: what the delivery guarantees actually promise, where duplicates and losses come from, and how to build exactly-once effects on top of a channel that can only ever give you at-least-once.
What delivery semantics are
A delivery semantic is the promise a messaging system makes about how many times a message reaches a consumer and gets acted on, in the presence of crashes, timeouts and retries.
| Semantic | Promise | What you risk | Typical mechanism |
|---|---|---|---|
| At-most-once | 0 or 1 times | Silent loss | Ack or commit before processing, no retries |
| At-least-once | 1 or more times | Duplicates | Ack after processing, redeliver on timeout |
| Exactly-once effect | Side effect happens once | Complexity, latency | At-least-once plus dedup or atomic commit |
Notice the third row says “effect”, not “delivery”. That distinction is the whole article.
How it works
Why exactly-once delivery is impossible end to end
Picture two generals on hills either side of a valley. They can only communicate by messengers who may be captured. General A sends “attack at dawn”. To be sure it arrived, she needs an acknowledgement. But B cannot know whether his acknowledgement arrived either, so he needs an acknowledgement of the acknowledgement, and so on forever. No finite exchange over a lossy channel gives both sides certainty. This is the Two Generals problem, and it applies to every network you will ever use, a point the distributed systems primer makes with the fallacy “the network is reliable”.
Translate it to a queue. A consumer processes a message and sends an ack. The ack is lost, or the consumer crashes a millisecond before sending it. The broker now sees exactly the same thing in both cases: no ack. It has two choices.
flowchart TD
A["Broker delivers message"] --> B["Consumer processes it"]
B --> C["Ack sent"]
C --> D{"Ack reaches broker?"}
D -->|"yes"| E["Done, delivered once"]
D -->|"no: lost or consumer crashed"| F{"Broker policy"}
F -->|"redeliver"| G["At-least-once:<br/>possible duplicate"]
F -->|"give up"| H["At-most-once:<br/>possible loss"]
style E fill:#E1F5EE,stroke:#0F6E56,color:#085041
style G fill:#FAEEDA,stroke:#854F0B,color:#633806
style H fill:#FCEBEB,stroke:#A32D2D,color:#791F1F
style F fill:#EEEDFE,stroke:#534AB7,color:#3C3489
There is no third branch. Any system that claims “exactly-once delivery” either redelivers and hides the duplicate from you (dedup on the broker or client), or scopes the claim to a closed world where the effect and the acknowledgement are committed atomically in the same store. Both are real and useful. Neither is magic delivery over an unreliable network.
Exactly-once effect is achievable
You get an exactly-once effect by combining two things:
- At-least-once delivery, so nothing is lost. Retry until acknowledged.
- Idempotent or atomic processing, so the second, third and tenth copy change nothing.
There are two ways to make processing safe:
- Make the operation idempotent. “Set balance to 120” is naturally idempotent. “Add 20 to balance” is not. You can turn the second into the first with an idempotency key: the downstream system remembers keys it has seen and returns the stored result for repeats.
- Commit the effect and the progress marker together. If the consumer’s database write and its “I processed message 812” record commit in one transaction, a crash either loses both (retry is safe) or keeps both (the retry is detected and skipped).
Where duplicates and losses come from
Duplicates are not rare edge cases. They come from ordinary operations that happen every day.
Producer retries. The producer sends a message, the broker writes it, and the response times out. The producer retries, as retry policy tells it to, and the broker writes a second copy. Without producer-side dedup, every timeout under load is a potential duplicate.
Consumer crash between effect and ack. The worker charges the card, then dies before deleting the SQS message or committing the Kafka offset. The message is delivered again.
Rebalances. In Kafka, when partitions move between consumers, the new owner starts from the last committed offset. Anything processed but not yet committed is processed again. Autoscaling, deploys and long GC pauses all trigger rebalances.
Visibility timeout too short. In SQS, a received message is hidden for the visibility timeout (default 30 seconds, maximum 12 hours). If processing takes 45 seconds, the message reappears at 30 seconds and a second worker picks it up while the first is still working. Two workers, one message, both succeed.
Broker failover. A broker or partition leader fails after accepting a write but before replicating it. Depending on configuration, the write is either lost (at-most-once in practice) or the producer retries into the new leader (duplicate if the old write survived).
Auto-ack. RabbitMQ consumers with automatic acknowledgement, or Kafka consumers committing before processing, get at-most-once: a crash after the ack loses the message silently.
The building blocks
Idempotent producers
Kafka’s idempotent producer gives each producer instance a producer ID and attaches a sequence number per partition to every batch. The partition leader tracks the last sequence numbers per producer and discards a retried batch it has already written. Since Kafka 3.0, enable.idempotence=true and acks=all are the producer defaults, and ordering is preserved with up to 5 in-flight requests per connection.
The scope is narrow: one producer session writing to one partition. If the producer process restarts without a stable transactional.id, it gets a new producer ID and the broker cannot recognise its retries. And it does nothing about duplicates that originate upstream, such as a user double clicking. Mechanics are covered in Kafka internals.
SQS FIFO queues do producer-side dedup differently: they drop a message with the same deduplication ID (or content hash, if content-based dedup is enabled) within a 5 minute window. Retries after that window are new messages.
Transactional read-process-write in Kafka
Kafka transactions let a consumer-producer read from input topics, write to output topics and commit its input offsets as one atomic unit. Downstream consumers set isolation.level=read_committed and never see output from aborted transactions. Kafka Streams wraps this as processing.guarantee=exactly_once_v2.
sequenceDiagram participant In as Input topic participant App as Processor participant Co as Transaction coordinator participant Out as Output topic App->>Co: initTransactions (fences old instance) In->>App: poll records at offsets 100 to 149 App->>Co: beginTransaction App->>Out: produce 50 results (pending) App->>Co: sendOffsetsToTransaction (input at 150) App->>Co: commitTransaction Co->>Out: write commit markers Note over Out: read_committed consumers now see the 50 results Note over App,Out: crash before commit means abort: results hidden, offsets not advanced
This is genuinely exactly-once, but only inside Kafka. The moment your processor calls an HTTP API, writes to Postgres or sends an email, that side effect is outside the transaction. If the transaction aborts and retries, the email goes out twice. For external effects you still need an idempotent sink, or the outbox and inbox patterns from Outbox, inbox and CDC.
Other limits worth knowing: transactions add latency (commit markers, coordinator round trips), consumers left on the default read_uncommitted isolation level still see aborted data, and a zombie instance is only fenced if every instance uses the same transactional.id for the same input partitions.
Idempotent consumers with a dedup table
The general-purpose technique, independent of broker, is a processed-messages table in the consumer’s own database:
CREATE TABLE processed_messages (
consumer text NOT NULL,
message_id text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
BEGIN;
INSERT INTO processed_messages (consumer, message_id)
VALUES ('billing', 'msg-7f3a')
ON CONFLICT DO NOTHING;
-- if 0 rows inserted: duplicate, ROLLBACK and ack the message
UPDATE orders SET status = 'charged' WHERE id = 42;
COMMIT;
-- only now ack or commit the offset
Three rules make it work. The dedup insert and the business write must commit in the same transaction, or a crash between them reopens the window. The message ID must be stable across redeliveries and set by the producer, not generated by the consumer. And the table must keep entries at least as long as a duplicate can arrive: the queue’s retention plus the longest replay you might run. For Kafka with 7 day retention, keep at least 7 days and prune older rows on a schedule.
When the side effect lives in another system, such as a payment provider, the dedup table protects your own state but not theirs. Pass a deterministic idempotency key to the provider as well.
Ordering guarantees
Ordering is a separate guarantee from delivery count, and retries interact with it.
- Kafka orders records within a partition. Same key, same partition, same order. No order across partitions.
- SQS FIFO orders within a message group ID and blocks the group while a message is in flight. Other groups proceed in parallel.
- Google Pub/Sub orders by ordering key when message ordering is enabled on the subscription.
- SQS standard, Pub/Sub without ordering keys, Kafka share groups give no ordering at all.
The trap: per-key ordering plus retries means a failed message must block its key until it succeeds or is dead-lettered. If you retry message 1 later and let message 2 through, you have broken the order you paid for. That is head-of-line blocking, and it is the price of ordering. Many systems decide they do not need strict ordering and instead make handlers tolerate reordering by checking a version or timestamp on the entity (“ignore an update older than what I have”).
Acks and visibility timeouts
Every broker has a knob for when a message counts as done, and its position relative to your side effect decides your semantic:
| Broker | At-most-once setting | At-least-once setting |
|---|---|---|
| Kafka consumer | Commit offset, then process | Process, then commit offset |
| Kafka producer | acks=0 | acks=all with idempotence |
| SQS | Delete immediately on receive | Delete after processing, visibility timeout for retry |
| RabbitMQ | Automatic ack | Manual ack after processing, publisher confirms |
| Pub/Sub | Ack immediately | Ack after processing, ack deadline for retry |
Set the visibility timeout or ack deadline comfortably above your p99 processing time, and extend it with a heartbeat for long jobs. Too short creates duplicates; too long delays retries after a real crash. For SQS triggering Lambda, AWS recommends a visibility timeout of at least six times the function timeout. Queue mechanics are covered in message queues.
Where it breaks
“The broker says exactly-once, so we are safe.” Broker features dedup inside the broker. Pub/Sub’s exactly-once delivery, for example, works only for pull subscriptions and only when subscribers connect in the same region; a subscriber that acks too late still gets a redelivery. Your handler must still be idempotent.
Dedup on a non-stable ID. Consumers that hash the payload break when the producer adds a timestamp field. Consumers that use the broker’s internal ID break when the producer retries, because each retry gets a new broker ID. Use a business or producer-assigned ID.
Dedup window shorter than the duplicate window. A 5 minute dedup window does nothing for a replay from yesterday’s offset, or a DLQ redrive a week later.
Non-transactional dedup. Checking Redis “have I seen this?” and then writing to Postgres is two writes. A crash between them either loses the message or double-applies it. If you cannot put both in one transaction, make the business write itself idempotent (upsert with a version check).
Exactly-once on one hop, at-least-once on the next. A Kafka Streams job with exactly_once_v2 feeding a sink connector that retries HTTP calls gives duplicates at the edge. Exactly-once is a property of the whole path, and the weakest hop wins.
Over-applying it. Metrics counters, cache invalidations and “user is typing” signals are fine with at-most-once or with duplicates. Paying for transactions there buys nothing.
Real-world systems
- Apache Kafka: idempotent producer on by default since 3.0, transactions for read-process-write,
read_committedconsumers. Ordering per partition. Share groups (production ready in 4.2) trade ordering for per-message acks. - Amazon SQS: standard queues are at-least-once with best-effort ordering. FIFO queues add per-group ordering and 5 minute deduplication by deduplication ID.
- Google Cloud Pub/Sub: at-least-once by default; optional exactly-once delivery on pull subscriptions within a region; ordering keys for per-key order.
- RabbitMQ: publisher confirms for producer safety, manual consumer acks for at-least-once. Quorum queues track delivery counts and dead-letter messages after a delivery limit (default 20 since 4.0).
- Payment APIs: most major payment providers accept an idempotency key on create-charge calls and return the original result for a repeated key within a retention window.
How to apply it
Start from the side effect and work backwards.
- Classify the effect. Is a duplicate harmful (money, inventory, email)? Is a loss harmful? If neither, use at-most-once and move on.
- Default to at-least-once. Ack after processing. Retries with backoff. Dead-letter after N attempts.
- Make the handler idempotent. Natural idempotency first (upserts, set-to-value). Otherwise a dedup table in the same transaction as the business write.
- Propagate keys outward. Any call to an external system that has effects carries a deterministic idempotency key derived from the message ID.
- Use broker features as optimisations, not guarantees. Idempotent producers and FIFO dedup reduce duplicate volume. They do not replace step 3.
- Reach for Kafka transactions when the whole pipeline is Kafka to Kafka (stream processing). Covered in stream processing.
- Avoid dual writes between your database and the broker. Write the event to an outbox table in the same transaction and relay it. Covered in Outbox, inbox and CDC.
Interview questions
Q1: A consumer reads from Kafka and writes rows into Postgres. How do you avoid duplicate rows when the consumer crashes and restarts?
Model answer: Kafka transactions do not cover Postgres, so the solution lives in Postgres. Option one: make the write idempotent with a natural key, for example an upsert on order_id, so reprocessing overwrites with the same values. Option two: store the consumed offset in Postgres in the same transaction as the rows, keyed by topic and partition, and on startup seek the consumer to the stored offset instead of the Kafka committed offset. Either way the row and the progress marker commit atomically, so a crash loses both or keeps both. Committing the Kafka offset after the Postgres commit is still at-least-once, which is fine because the write is now idempotent.
Q2: Your SQS consumer occasionally processes the same message twice even though it never crashes. What is going on and how do you fix it?
Model answer: The most likely cause is processing time exceeding the visibility timeout. The message becomes visible again and a second consumer receives it while the first is still working. Fixes: raise the visibility timeout above p99 processing time, extend it with ChangeMessageVisibility as a heartbeat during long work, and make the handler idempotent with a dedup record keyed by a producer-assigned message ID. Standard queues can also deliver duplicates occasionally by design, so idempotency is required regardless of the timeout.
Q3: Does setting enable.idempotence=true on a Kafka producer give you exactly-once processing?
Model answer: No. It prevents duplicates caused by producer retries within one producer session to one partition: the broker discards a batch whose producer ID and sequence number it has already written. It does not cover a producer that restarts and resends with a new producer ID, duplicates created upstream of the producer, or duplicate processing on the consumer side. For end-to-end exactly-once within Kafka you need transactions with a stable transactional.id and read_committed consumers; for external effects you need idempotent sinks.
✅ Key takeaways
- Exactly-once delivery is impossible over a lossy network because a lost message and a lost ack look identical; exactly-once effect is achievable.
- Exactly-once effect equals at-least-once delivery plus idempotent processing, or an atomic commit of the effect and the progress marker.
- Duplicates come from normal operations: producer retries, crashes before ack, rebalances, visibility timeouts that are too short and broker failover.
- Kafka’s idempotent producer and transactions are scoped: one producer session, and Kafka-to-Kafka pipelines. External side effects need idempotent sinks.
- A dedup table must commit in the same transaction as the business write, use a stable producer-assigned ID, and retain entries longer than any possible redelivery.
- Ordering is per partition or per message group, and keeping it under retries costs head-of-line blocking.
🧠 Check your understanding
0 / 4-
1A consumer commits its Kafka offset immediately after poll and before processing. What semantic does it get?
Committing first means a crash during processing moves the group past records that were never handled, so they are lost. Retention does not help because the committed offset is already ahead. Producer idempotence has nothing to do with consumer commit order.
-
2Why can no protocol guarantee exactly-once delivery over an unreliable network?
This is the Two Generals problem. With no ack the sender sees the same thing whether the message or the ack was lost, so it chooses duplicates or loss. Clock drift is a real problem but a different one, and TCP does order bytes within a connection.
-
3A Kafka Streams job uses exactly_once_v2 and, for each record, sends a webhook to a partner. What happens on a transaction abort and retry?
Kafka transactions only cover writes to Kafka topics and offset commits. An HTTP call is an external side effect that cannot be rolled back, so the partner needs an idempotency key. read_committed only affects what Kafka consumers can read.
-
4A team dedups with a Redis SET of seen message IDs, then writes to Postgres. What is the flaw?
If the process marks the ID in Redis and crashes before the Postgres commit, the retry is skipped and the effect is lost; reverse the order and you double-apply. The dedup record must commit in the same transaction as the business write. A TTL only controls how long protection lasts.
Where to go next
- Message queues: visibility timeouts, dead-letter queues and redrive in practice, where these semantics meet a real broker.
- Kafka internals: how producer IDs, sequence numbers and the transaction coordinator actually implement idempotence and EOS.
- Outbox, inbox and CDC: how to publish an event and update a database without a dual write, and the inbox version of the dedup table.
- Stream processing: exactly-once state in stream processors, checkpoints and how they extend these ideas to windows and joins.
Finished this lesson?
Mark it complete to track your progress across the roadmap.