Delivery Guarantees: At-Most-Once, At-Least-Once, Exactly-Once
"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." — Apache Kafka documentation, Design: Message Delivery Semantics
Summary: A delivery guarantee is a promise about what happens when something fails between two steps; every real system errs towards loss (at-most-once) or towards duplicates (at-least-once), and "exactly-once" is always a statement about a boundary. Focus: Where each hop (producer retry, broker replication and ack, consumer crash before or after ack) creates a loss or a duplicate, what Kafka's idempotent producer and transactions really cover, and what RabbitMQ, Redis Streams and Laravel queues give you instead. Learning goal: Name the semantics a given pipeline really has, choose the right one per flow (payments, notifications, analytics, audit), and build effectively-once processing from at-least-once delivery plus idempotency, then measure that it works.
This page is the complete reference for delivery semantics: the three guarantees, the two generals argument that explains why "exactly-once delivery" cannot exist end to end, the failure point at every hop that turns into a loss or a duplicate, the Kafka idempotent producer and transactions (enable.idempotence, transactional.id, isolation.level=read_committed, producer epochs and zombie fencing) as the one broker-side mechanism that goes beyond at-least-once, and what RabbitMQ, Redis Streams, NATS JetStream, Pulsar, Amazon SQS and Laravel queues provide. It deliberately stops at three borders. How acks, nacks, prefetch, offset commits and XACK work is in Message Acknowledgment. The dedup table, idempotency keys and "process then mark" are in Idempotent Consumers & the Inbox Pattern. Publishing reliably from a database transaction is in Transactional Outbox Pattern. The map of the whole section is Messaging Fundamentals.
Page map
| If you are looking for | Go to |
|---|---|
| The three semantics and the failure points in one table | Everything in one minute |
| Why no system can promise "exactly once" for free | Why delivery guarantees exist |
| Two generals, Gray 1978, KIP-98, the 2017 "exactly-once" debate | Where it comes from |
| At-most-once, at-least-once, exactly-once, effectively-once, durability | The semantics, one by one |
| Producer retry, replication, consumer crash before and after ack | Where losses and duplicates are created |
| What Kafka EOS covers and what it does not | Exactly-once: marketing vs reality |
| PID, sequence numbers, epochs, coordinator, LSO, knobs, error codes | Mechanics |
| Go and Laravel before/after | Go, Laravel |
| RabbitMQ confirms and quorum queues, Kafka EOS, Redis PEL and IDMP | Broker differences |
| Producer duplicates, consumer replays, DB sinks, third-party effects | Solving the classic problems |
| Which errors to retry | Retries and failure handling |
| Duplicate rate, loss detection with sequence numbers | Measuring delivery |
| Payments vs notifications vs analytics vs audit | Choosing semantics per use case |
| Monolith to distributed system | In architecture |
| A Go simulation with real numbers, broker commands | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The semantics. Every row is unpacked in the semantics section.
| Semantics | Promise | What fails | Tiny example | How you get it |
|---|---|---|---|---|
| At-most-once | Never twice | May be lost | A metrics sample vanishes when the consumer dies | No producer retry; ack or commit before processing |
| At-least-once | Never lost | May be twice | An email sent twice after a worker restart | Retry until acked; ack or commit after processing |
| Exactly-once delivery | Received once, sender knows | Impossible end to end over a lossy link | (none: the two generals) | Does not exist across a network |
| Exactly-once processing (Kafka EOS) | Effect inside Kafka happens once | Anything outside Kafka | Topic → transform → topic | Idempotent producer + transactions + read_committed |
| Effectively-once | Effect happens once, anywhere | Requires a key the effect store honours | Card charged once despite three deliveries | At-least-once + idempotent consumer, or effect and offset in one DB transaction |
Where losses and duplicates are created. Unpacked in the failure-point section.
| Hop | Failure | Result | Fix |
|---|---|---|---|
| Producer → broker | Request lost, producer does not retry | Loss | Retry until acked (publisher confirms, acks=all) |
| Broker → producer | Ack lost, producer retries | Duplicate in the log | Idempotent producer (Kafka), IDMP (Redis 8.6), Nats-Msg-Id (NATS), FIFO dedup id (SQS) |
| Broker leader → replicas | Leader acks, dies before replicas copy | Loss of an acknowledged message | acks=all + min.insync.replicas, quorum queues, WAIT (best effort) |
| Broker → consumer → effect | Crash after the effect, before the ack | Duplicate processing | Idempotent consumer |
| Consumer ack → effect | Ack or commit first, then crash | Loss of work | Ack after the work |
| Consumer lease / rebalance | Slow consumer loses its partition or its message | Duplicate, sometimes concurrent | Idempotent consumer, fencing |
What each broker gives you by default.
| Broker | Default you get | Strongest you can configure | Producer dedup |
|---|---|---|---|
| RabbitMQ | At-most-once (no confirms, autoAck is a client choice) | At-least-once (confirms + persistent + quorum queue + manual ack) | None |
| Kafka (clients 3.0+) | At-least-once, idempotent producer on | Exactly-once processing Kafka → Kafka | PID + sequence, per partition, per producer session |
| Redis Streams | At-least-once with consumer groups; durability depends on AOF/RDB | At-least-once | XADD ... IDMP from Redis 8.6, bounded window |
| Laravel queue (database, Redis, SQS, Beanstalkd) | At-least-once | At-least-once + ShouldBeUnique at dispatch + idempotent handle() | None in the driver |
| NATS JetStream | At-least-once with acks | Dedup window on Nats-Msg-Id (default 2 minutes) | Yes, windowed |
| Amazon SQS | Standard: at-least-once | FIFO: no duplicates introduced within a 5-minute dedup interval | Yes, windowed |
| Apache Pulsar | At-least-once | Idempotent producer per partition, transactions | Yes |
Why delivery guarantees exist
A message crosses at least two network links and two processes before its effect lands: producer → broker, broker → consumer, and then consumer → whatever it changes. Each link can drop the request or drop the answer, and each process can die between two steps. The sender of any message is left in the same state after a timeout: it does not know whether the receiver got it. It has exactly two choices, give up or send again, and that choice is the guarantee. Kafka's design doc splits it the same way: "the durability guarantees for publishing a message and the guarantees when consuming a message."
| Err towards loss (at-most-once) | Err towards duplicates (at-least-once) |
|---|---|
| No retries, no ack bookkeeping | Retries and acks on every hop |
| Lowest latency, highest throughput | Some latency for confirms and replication |
| Loss is silent | Duplicates are visible and countable |
| Consumer can be naive | Consumer must be idempotent |
| Fine when the next message supersedes this one | Required when every message matters |
The analogy we reuse on this page: paying by card at a restaurant. The terminal freezes on "processing". Did the payment go through? The waiter can run the card again (at-least-once: you may pay twice) or not (at-most-once: the restaurant may not get paid). No amount of staring at the terminal answers the question, because the answer was lost on the way back. The fix is not a better terminal. The bank recognises the second attempt by its transaction reference and refuses to book it twice. Exactly-once lives in the bank's ledger, not on the wire. Every section below maps back to this: the terminal is the producer, the bank is the broker or the database, the reference number is the idempotency key.
Three common misunderstandings, up front
- "Our broker is exactly-once, so we are." Kafka's exactly-once covers reads and writes of Kafka topics inside one transaction. The database insert, the email and the HTTP call in the same loop are at-least-once. Kafka's own docs: "Exactly-once delivery for other destination systems generally requires cooperation with such systems."
- "At-least-once means usually once." It means never lost. Duplicates appear exactly when things go wrong: deploys, rebalances, failovers, slow handlers. Design and test for the duplicate, not the happy path.
- "Acknowledged means safe." An ack only means what the broker was configured to wait for. A Kafka
acks=1ack or a RedisXADDreply is given before replicas have the data, and a failover can lose it.
Where it comes from
The impossibility at the heart of this topic is older than any broker. Akkoyunlu, Ekanadham and Huber published it in 1975, framed as gangsters coordinating over an unreliable channel (we know this from Wikipedia's summary; we could not obtain the ACM paper itself). Jim Gray gave it its lasting name in his 1978 Notes on Data Base Operating Systems, section 5.8.3.3.1 "The Generals Paradox", in the part that motivates two-phase commit. Two generals must attack a hill together; their only link is runners who "stand some chance of getting lost". Gray's proof is one line:
"There is a simple proof that: no fixed length protocol exists: Let P be the shortest such protocol."
If the last runner of the shortest protocol is lost, either that runner was useless, which contradicts minimality, or one general does not march. Gray then translates it into computing: a Tokyo computer must debit an account and a cash machine in Füssen must open its drawer, both or neither. His answer, two-phase commit, does not beat the paradox; it accepts an unbounded number of messages and a durable log on each side.
Hohpe and Woolf's Enterprise Integration Patterns (2003) named the broker-side half Guaranteed Delivery: "the send operation does not complete successfully until the message is safely stored in the sender's data store", and a message "is not deleted from one data store until it is successfully forwarded to and stored in the next". The consumer-side half is the Idempotent Receiver: "a message that has the same effect whether it is received once or multiple times".
Kafka 0.11 (2017) shipped KIP-98, the idempotent producer and transactions. The Confluent announcement by Neha Narkhede and Guozhang Wang was titled, pointedly, Exactly-Once Semantics Are Possible: Here's How Kafka Does It, and the same post answers its own headline under "Is This Magical Pixie Dust I Can Sprinkle on My Application?":
"No, not quite. Exactly-once processing is an end-to-end guarantee and the application has to be designed to not violate the property as well."
KIP-447 (adopted in Kafka 2.6.0) made transactional consumers in a group scale by fencing with consumer-group metadata. KIP-679 changed the producer defaults "in release version 3.0" to enable.idempotence=true and acks=all, so a modern Java producer is idempotent unless something conflicts. KIP-890 (approved) hardens transactions against "hanging transactions" by bumping the epoch on every commit or abort.
The semantics, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, the per-broker picture, and the fix.
At-most-once Must-know
In plain words: send once and forget; if anything fails on the way, the message is gone, but it is never handled twice.
Common misunderstanding: "At-most-once is what you get only if you choose it." Most accidental at-most-once comes from defaults and shortcuts: RabbitMQ publishes without confirms unless the client enables them, an autoAck=true consumer, Kafka auto-commit firing before a slow batch finishes, Redis XREADGROUP ... NOACK, or a Laravel job that dispatches on a sync connection inside a transaction that rolls back.
Definition: a pipeline is at-most-once when every hop either does not retry or records progress before doing the work. Kafka's docs define the consumer half as "read the messages, then save its position in the log, and finally process the messages", and the producer half as "disabling retries on the producer".
Producer Broker Consumer
1 send(m1) ───────────▶ append m1
2 deliver m1 ─────────▶ commit offset 43 (position saved first)
3 process m1 ... CRASH
4 restart: resume at 43
5 m1 is never processed -> LOSSReal scenarios: CPU and latency metrics where the next sample replaces the lost one; presence ("user is online") heartbeats; cache invalidation hints backed by a TTL; live sports scores pushed over Redis Pub/Sub; debug logs.
| Broker | How at-most-once happens |
|---|---|
| RabbitMQ | autoAck=true (automatic acknowledgement mode: the broker forgets the message once it is sent); publishing without confirms |
| Kafka | acks=0 (offset returned is always -1, retries do not apply), or enable.auto.commit committing before processing |
| Redis Streams | XREADGROUP ... NOACK (no PEL entry); Redis Pub/Sub "exhibits at-most-once message delivery semantics" |
| Laravel | Rare in drivers; a job that catches and swallows its own exception and returns marks itself done |
Fix: if loss is acceptable, keep it and say so in the code. If it is not, flip both halves: retry until acked, and ack after the work.
At-least-once Must-know
In plain words: keep sending until someone confirms, and only confirm after the work is done; nothing is lost, but some things happen twice.
Common misunderstanding: "We use acks, so we have no duplicates." Acks are exactly what creates duplicates: an ack lost on the way back makes the sender retry something that already arrived. RabbitMQ's Reliability Guide: "There is a possibility of message duplication here, because the broker might have sent a confirmation that never reached the producer."
Definition: every hop retries until it has a positive confirmation, and every consumer records progress only after its effect is durable. The RabbitMQ docs state it without hedging: "Use of acknowledgements guarantees at least once delivery."
Consumer A Broker Consumer B
1 deliver m7 ──▶ A
2 charge card for m7 (done)
3 ack m7 ... CRASH before ack leaves
4 A's channel closed: requeue m7 (redelivered=true)
5 deliver m7 ─────────────▶ B
6 charge card for m7 again -> DUPLICATEReal scenarios: a welcome email sent twice after a deploy; an inventory decrement applied twice after a Kafka rebalance; a webhook delivered twice because the receiver answered after the sender's timeout; a Laravel job run twice because it outlived retry_after.
| Broker | Primitives that give at-least-once |
|---|---|
| RabbitMQ | Publisher confirms + persistent messages + durable (quorum) queue + manual consumer ack after work |
| Kafka | acks=all + retries on the producer; enable.auto.commit=false and commit after processing |
| Redis Streams | XADD with retry; XREADGROUP + XACK after work; XAUTOCLAIM for dead consumers |
| Laravel | Every real driver: a reserved job not deleted within retry_after is handed out again |
| NATS JetStream | Explicit ack with AckWait redelivery |
| Amazon SQS | Standard queues; visibility timeout redelivery |
Fix: at-least-once is the right default for anything that matters. The remaining obligation is to make the second arrival harmless, which is the effectively-once block below.
Exactly-once delivery vs exactly-once processing Must-know
In plain words: "exactly-once delivery" (the wire carries it once and both sides know) is impossible over a lossy network; "exactly-once processing" (the effect happens once) is possible, but only inside a boundary that can commit atomically or dedup by key.
Common misunderstanding: "Exactly-once is a broker feature you turn on." It is a property of the whole path. Turning on Kafka transactions gives it for Kafka-to-Kafka steps only; every other effect still needs a key the target honours.
Definition: exactly-once processing means that for every input message the observable result equals processing it once, despite retries and crashes. There are only two ways to get it:
- Atomic commit of effect and progress. Write the output and the consumer position in one transaction so they cannot diverge. Kafka transactions do this when both live in Kafka; storing the offset in the same ACID transaction as the business row does it for a database.
- Idempotency. The effect store recognises a repeat by a key and ignores it: an upsert, a unique constraint, a dedup table, a payment provider's idempotency key.
Kafka read-process-write (transactional.id = enricher-1)
1 poll input offsets 41..43
2 beginTransaction
3 produce 3 output records (PID 7, epoch 3, seq 120..122)
4 sendOffsetsToTransaction(next offset 44, group metadata)
5 commitTransaction -> coordinator writes COMMIT markers on output + __consumer_offsets
6 CRASH between 3 and 5 instead: coordinator aborts; read_committed readers never see 120..122;
the group's offset stays at 41; the restarted instance (same id, epoch 4) redoes 41..43 onceReal scenarios: a Kafka Streams aggregation of payments per merchant; a CDC topic transformed into a cleaned topic; a fraud-scoring service that reads payments and writes payment-scores.
Fix: use Kafka transactions for Kafka → Kafka; for everything else, design the effect to be idempotent and keep the broker at at-least-once.
Effectively-once Important
In plain words: deliver at-least-once, and make the second (and third) arrival a no-op, so the world looks as if it happened once.
Common misunderstanding: "Dedup at the broker is enough." Broker-side dedup (Kafka idempotent producer, Redis IDMP, SQS FIFO, NATS Nats-Msg-Id) removes producer duplicates inside a time or session window. It does nothing about a consumer that crashes after its effect but before its ack.
Definition: effectively-once = at-least-once delivery + an idempotent effect. The effect is keyed by something stable that travels with the message (a business id such as payment_id, or a producer-assigned message id), not by the attempt. EIP calls the consumer an Idempotent Receiver; the implementation (inbox table, "process then mark", TTLs) is owned by Idempotent Consumers & the Inbox Pattern.
Consumer (handler idempotent on payment_id) Database
1 receive m7 (payment_id=p-91)
2 BEGIN; INSERT INTO processed(p-91); UPDATE balance; COMMIT
3 ack m7 ... lost; m7 redelivered
4 receive m7 again (redelivered=true)
5 BEGIN; INSERT INTO processed(p-91) -> unique violation; ROLLBACK; ack -> no second effectReal scenarios: charging a card with Stripe's Idempotency-Key; crediting a wallet with an insert into a ledger keyed by transfer id; an upsert of a product's search document; a Laravel job that checks status = 'paid' and uses a provider key derived from the order.
Fix: the solutions section shows the three standard shapes.
Durability is a separate axis Important
In plain words: "at-least-once" is only as strong as the broker's memory; if the broker forgets a message it acknowledged, nothing upstream will resend it.
Common misunderstanding: "Persistent message means it survives anything." A persistent message on a single node survives a restart, not a disk loss; a Kafka acks=1 write survives the leader's restart, not its replacement; a Redis XADD reply can come before the write is fsynced or replicated.
Definition: the ack contract of each broker says what has happened before the producer is told "yes":
| Broker and setting | Ack means | Loss window after the ack |
|---|---|---|
Kafka acks=0 | Nothing; "considered sent" when in the socket buffer | Everything |
Kafka acks=1 | Leader wrote to its local log | Leader dies before followers copy |
Kafka acks=all + min.insync.replicas=2 | All in-sync replicas (at least 2) have it | All of them lost at once |
| RabbitMQ confirm, classic durable queue, persistent message | Persisted to disk on that node | Node's disk lost |
| RabbitMQ confirm, quorum queue | A majority of replicas accepted it | A majority permanently lost |
Redis XADD, appendfsync everysec | In memory, AOF fsync within a second | Up to about one second; more on async-replica failover |
Redis XADD + WAIT 1 100 | At least one replica acknowledged | Small, but failover is "best effort" |
The Kafka producer docs on acks=all: "This guarantees that the record will not be lost as long as at least one in-sync replica remains alive." The broker-side guards (min.insync.replicas, unclean leader election) are taught in Kafka in Depth and the replication theory in Replication & Failover.
The two generals, applied Good to know
In plain words: after a timeout, the sender cannot tell "my message was lost" from "the answer was lost", so it must choose between risking loss and risking a duplicate.
Common misunderstanding: "Add one more ack round and you are safe." Gray's proof shows any fixed protocol has a last message whose loss leaves one side unsure. More rounds move the uncertainty; they do not remove it.
Definition: no finite protocol over a channel that can lose messages lets both parties agree with certainty that a message was delivered. The practical consequence is the rule of this page: delivery is at-most-once or at-least-once; "once" is built on top with state that survives the uncertainty (a key, a sequence number, a transaction log).
Producer Broker
1 send m1 ─────────────X (request lost: broker never saw it)
2 timeout
-- or --
1 send m1 ─────────────────────▶ append m1
2 X────────── ack m1 (ack lost)
3 timeout
Both cases look identical to the producer at step 2/3.Where losses and duplicates are created
Every loss and every duplicate in a messaging system is created at one of five places. The diagram numbers them; the table names the broker-specific version of each.
| # | Hop | What fails | Outcome | RabbitMQ | Kafka | Redis Streams | Laravel queue |
|---|---|---|---|---|---|---|---|
| 1 | Producer → broker | Request lost, no retry | Loss | No confirms: you never know | acks=0, or retries=0 | XADD error ignored | dispatch inside a rolled-back transaction without after_commit |
| 2 | Broker → producer | Ack lost, producer retries | Duplicate | Re-publish after a lost confirm | Without idempotence; with it, deduped by PID + seq | Duplicate entry unless IDMP (8.6+) | Re-dispatch after a timeout |
| 2b | Producer restart | New producer identity resends | Duplicate | Same as 2 | New PID: broker dedup does not apply (unless transactional.id) | New pid or iid expired | Same as 2 |
| 3 | Leader → replicas | Acked, then failover | Loss of an acknowledged message | Classic queue on a lost node; quorum queue needs a majority loss | acks=1, or ISR shrunk to 1 with min.insync.replicas=1 | Async replication; WAIT is best effort | Redis driver: same as Redis |
| 3b | Broker routing | Message routes to no queue | Silent loss | Unroutable + mandatory=false: dropped and confirmed | Topic auto-create off: error | Wrong stream key: new stream | Wrong queue name: job never picked |
| 4 | Consumer → effect → ack | Crash after the effect, before ack | Duplicate | Requeued, redelivered=true | Offset not committed: replay from last commit | Entry stays in PEL; re-read or XAUTOCLAIM | Job reserved again after retry_after |
| 5 | Ack → effect | Ack first, then crash | Loss | autoAck=true, or ack before work | Auto-commit or commit before processing | NOACK, or XACK before work | Rare; swallowing exceptions |
| 6 | Lease / rebalance | Slow consumer keeps working after it lost ownership | Duplicate, possibly concurrent | Delivery acknowledgement timeout (quorum queues) closes the channel | Rebalance; old member's late commit rejected | Idle entry claimed by another consumer | --timeout longer than retry_after |
Two of these deserve their own timelines because they surprise people.
3b, the confirmed loss in RabbitMQ. The confirms guide: "For unroutable messages, the broker will issue a confirm once the exchange verifies a message won't route to any queue." A publisher that checks only confirms sees success and the message is gone. mandatory=true makes the broker send basic.return (reply code 312 NO_ROUTE) "before basic.ack".
Publisher (confirm mode) Broker
1 publish(exchange=payments.x, key=eu.card, mandatory=false)
2 exchange has no binding for eu.card
3 <────────────────────────────────────────────── basic.ack (confirmed!)
4 message dropped; no queue ever held it -> LOSS that looks like success
with mandatory=true at step 1:
3' <────────────────────────────────────────────── basic.return 312 NO_ROUTE, then basic.ack6, the zombie worker in Laravel. The docs: "If your --timeout option is longer than your retry_after configuration value, your jobs may be processed twice."
Worker 1 (--timeout=120) Redis queue (retry_after=90) Worker 2
1 reserve job J at t=0
2 calling a slow API ...
3 t=90: J's reservation expired
4 J handed out again ──────────────▶ reserve J
5 t=100: API returns, charge done charge again -> DUPLICATEExactly-once: marketing vs reality
Kafka is the only one of the three main brokers with a mechanism beyond at-least-once. Its scope is precise, and the docs say so: "the transactional producer and the consumer using read-committed isolation level can be used generally to provide exactly-once delivery when reading, processing and writing data on Kafka topics. Exactly-once delivery for other destination systems generally requires cooperation with such systems."
| Claim | Reality |
|---|---|
| "Kafka is exactly-once" | Default is at-least-once; EOS needs transactional.id on the producer and read_committed on every downstream consumer |
| "The idempotent producer prevents duplicates" | Only producer retries within one producer session, per partition; an application that re-sends after a restart gets a new PID |
| "Transactions make my DB write exactly-once" | Nothing outside Kafka is rolled back on abort: DB rows, HTTP calls, emails stay |
"read_committed hides duplicates" | It hides records of aborted transactions; duplicates from a non-transactional producer are visible |
| "Kafka Streams is end-to-end exactly-once" | Inside Kafka with processing.guarantee=exactly_once_v2; sinks need an exactly-once connector or idempotent writes |
| "Exactly-once is slow" | Confluent measured a 3% producer throughput drop for 1 KB messages and 100 ms transactions; Streams lost 15–30% at a 100 ms commit interval |
| "Pulsar / SQS FIFO / NATS give exactly-once too" | Each gives producer dedup within a window or partition; consumer-side duplicates remain (Pulsar transactions are Kafka-like in scope) |
What Kafka EOS does not cover, listed so you can check a design against it:
- Side effects in the processing loop: database writes, HTTP calls, emails, files, caches.
- Producers without
transactional.idwriting into the same topics (their retries are deduped, their restarts are not). - Consumers using the default
read_uncommitted: they see aborted records. - The source of the data before Kafka (a REST call that produced the first record) and the sink after it.
- Two independent transactional apps with the same
transactional.id(they fence each other) or with a different one each restart (no fencing at all).
Outside Kafka, the "exactly-once" features of other systems are windowed producer dedup:
| System | Feature | Window | What it removes |
|---|---|---|---|
| Kafka | Idempotent producer | Producer session; last 5 batches per partition | Producer retries |
| Redis Streams 8.6+ | XADD ... IDMP pid iid / IDMPAUTO | IDMP-DURATION (default 100 s), IDMP-MAXSIZE (default 100 per producer) | Producer retries with the same pid + iid |
| NATS JetStream | Nats-Msg-Id header | Stream's duplicate window, default 2 minutes | Re-publishes with the same id |
| Amazon SQS FIFO | Message deduplication id or content-based (SHA-256 of body) | 5 minutes | SendMessage retries |
| Apache Pulsar | Idempotent producer; transactions | Per partition; transaction scope | Producer retries; consume-process-produce |
| RabbitMQ | None | n/a | Nothing; dedup is the consumer's job |
Mechanics
The idempotent producer: PID and sequence numbers Must-know
The broker assigns each producer a producer id (PID); the producer numbers every batch per partition with a sequence number. The broker keeps the last sequence numbers per PID and partition and drops a batch it has already written. The Kafka design doc: "the broker assigns each producer an ID and deduplicates messages using a sequence number that is sent by the producer along with every message." The enable.idempotence docs: "When set to 'true', the producer will ensure that exactly one copy of each message is written in the stream."
Conditions, from the producer config reference: idempotence "requires max.in.flight.requests.per.connection to be less than or equal to 5 (with message ordering preserved for any allowable value), retries to be greater than 0, and acks must be 'all'", because the "broker only retains at most 5 batches for each producer". If a conflicting setting is present and idempotence was not set explicitly, it is silently disabled; if it was set explicitly, the client throws a ConfigException.
Producer (PID 7) Partition leader (payments-3)
1 batch seq 120 ────────────────────▶ append, last_seq[7] = 120
2 X──────────────── ack lost
3 retry batch seq 120 ──────────────▶ seq 120 <= last_seq: do not append, ack again
4 batch seq 122 (121 missing) ──────▶ OUT_OF_ORDER_SEQUENCE_NUMBER (45)Transactions: transactional.id, coordinator, markers Must-know
A transactional producer has a transactional.id that is stable across restarts. On initTransactions the transaction coordinator (a broker that owns that id's partition of the internal __transaction_state topic) maps it to a PID, bumps the producer epoch, and aborts or completes whatever the previous incarnation left open. The producer then runs beginTransaction, sends records to any partitions, calls sendOffsetsToTransaction so the consumer group's offsets go into __consumer_offsets as part of the same transaction, and commitTransaction. The coordinator writes commit or abort markers (control records) into every partition touched.
A consumer with isolation.level=read_committed reads only up to the last stable offset (LSO), the first offset that still belongs to an open transaction, and skips aborted records. The default is read_uncommitted, which returns everything. The Kafka docs, "Using Transactions": "The consumer configuration must include isolation.level=read_committed and enable.auto.commit=false. The producer configuration must set transactional.id".
Defaults that matter: transaction.timeout.ms is 60000 in the Java client (franz-go's default is 40 s) and must not exceed the broker's transaction.max.timeout.ms; transactions need "a cluster of at least three brokers" by default because of transaction.state.log.replication.factor.
Zombie fencing and epochs Must-know
A zombie is an old instance that is still alive (GC pause, network partition) after a new instance took over its work. Without fencing both would commit, and the output would be duplicated. KIP-98: initTransactions "Bumps up the epoch of the PID, so that the any previous zombie instance of the producer is fenced off and cannot move forward with its transaction." Any later request from the old epoch fails with PRODUCER_FENCED (90) or INVALID_PRODUCER_EPOCH (47).
Instance A (txn.id=enricher-1) Coordinator Instance B (txn.id=enricher-1)
1 epoch 3, begin, produce ...
2 long GC pause
3 initTransactions from B <─ start (A thought dead)
4 abort A's open txn; epoch -> 4
5 epoch 4, begin, produce, commit
6 wakes up, commitTransaction (epoch 3) -> PRODUCER_FENCED: A must close and exitKIP-447 (Kafka 2.6.0) fixed the scaling problem: previously "the simplest solution is to create a separate producer for every input partition", which is what Kafka Streams did. Since 2.6, sendOffsetsToTransaction(offsets, ConsumerGroupMetadata) carries the group generation, and the group coordinator rejects offsets from a member that has been fenced out of the group, so one transactional producer per instance is enough. KIP-890 (approved) adds server-side verification and an epoch bump on every transaction end to close the "hanging transaction" cases where "read_committed consumers get stuck".
Knobs, per broker Important
| Broker | Knob | Default | Role in the guarantee |
|---|---|---|---|
| Kafka producer | acks | all (since 3.0) | How many replicas before the ack |
| Kafka producer | enable.idempotence | true if no conflict (since 3.0) | PID + sequence dedup of retries |
| Kafka producer | max.in.flight.requests.per.connection | 5 | Must be ≤ 5 for idempotence |
| Kafka producer | retries / delivery.timeout.ms | leave retries unset / 120000 (2 minutes) | How long to keep retrying; "prefer to leave this config unset and instead use delivery.timeout.ms" |
| Kafka producer | transactional.id | null | Enables transactions and fencing |
| Kafka producer | transaction.timeout.ms | 60000 | Coordinator aborts an open transaction after this |
| Kafka consumer | isolation.level | read_uncommitted | read_committed hides aborted records |
| Kafka consumer | enable.auto.commit | true | Must be false for commit-after-process and EOS |
| Kafka topic/broker | min.insync.replicas | 1 | With acks=all, minimum replicas for a write |
| Kafka Streams | processing.guarantee | at_least_once | exactly_once_v2 turns on EOS |
| RabbitMQ | confirm mode (confirm.select) | off | Publisher learns the broker took responsibility |
| RabbitMQ | mandatory flag | false | basic.return instead of silent drop |
| RabbitMQ | delivery_mode | 1 (transient) | 2 = persistent |
| RabbitMQ | x-queue-type | classic | quorum = Raft-replicated, always durable |
| RabbitMQ | consumer autoAck / no-ack | client choice | false for at-least-once |
| Redis | appendonly / appendfsync | RDB snapshots only / everysec once AOF is on | How much an acked XADD can lose |
| Redis | WAIT numreplicas timeout | n/a | Wait for replicas (best effort) |
| Redis 8.6+ | XCFGSET key IDMP-DURATION n IDMP-MAXSIZE m | 100 s / 100 | Producer dedup window |
| Laravel | retry_after (per connection) | 90 | When a reserved job is handed out again |
| Laravel | --timeout (worker) | 60 | Must be shorter than retry_after |
| Laravel | after_commit | false | Dispatch only after the DB transaction commits |
| Laravel | #[Tries], #[UniqueFor] / uniqueFor() | 1 attempt / lock until done | Retries and dispatch dedup |
Error codes you will catch Must-know
| Code | Name (protocol docs) | Meaning for delivery | What to do |
|---|---|---|---|
| Kafka 7 | REQUEST_TIMED_OUT | Unknown outcome: maybe written | Retry; safe only with idempotence |
| Kafka 19 | NOT_ENOUGH_REPLICAS | ISR below min.insync.replicas; not written | Retry later; alert |
| Kafka 20 | NOT_ENOUGH_REPLICAS_AFTER_APPEND | "written to the log, but to fewer in-sync replicas than required" | Retry creates a duplicate without idempotence |
| Kafka 45 | OUT_OF_ORDER_SEQUENCE_NUMBER | Sequence gap: a batch was lost | Client resets; may surface as a fatal producer error |
| Kafka 46 | DUPLICATE_SEQUENCE_NUMBER | Broker already has this batch | Treated as success by the client |
| Kafka 47 | INVALID_PRODUCER_EPOCH | "Producer attempted to produce with an old epoch" | You are a zombie: close |
| Kafka 59 | UNKNOWN_PRODUCER_ID | Broker no longer has your PID state (retention removed it) | Client resets the sequence |
| Kafka 90 | PRODUCER_FENCED | "a newer producer with the same transactionalId" exists | Close the producer; do not retry |
| Kafka 120 | TRANSACTION_ABORTABLE | Abort the transaction to continue | abortTransaction, replay the batch |
| AMQP 312 | NO_ROUTE (basic.return) | Mandatory message was unroutable | Fix topology or retry elsewhere |
| AMQP 406 | PRECONDITION_FAILED | Channel closed, e.g. unknown delivery tag on a double ack | Reconnect; unacked messages are requeued |
Go
Before
Three consumers that are at-most-once by accident. The RabbitMQ one uses autoAck=true and a fire-and-forget publish. The Kafka one disables producer idempotence and commits offsets before charging. The Redis one reads with NOACK, so nothing enters the pending list.
// Package rabbitbefore loses messages at both ends without noticing:
// the publisher never learns whether the broker took the message, and the
// consumer tells the broker "done" before any work has happened.
package rabbitbefore
import (
"context"
amqp "github.com/rabbitmq/amqp091-go"
)
// Publish is fire-and-forget: no confirm mode, so a broker crash or a dropped
// connection right after this call silently loses the payment request.
func Publish(ctx context.Context, ch *amqp.Channel, body []byte) error {
return ch.PublishWithContext(ctx, "", "payments", false, false, amqp.Publishing{
ContentType: "application/json",
Body: body,
})
}
// Consume uses automatic acknowledgement. RabbitMQ considers each delivery
// done the moment it is written to the socket. If charge fails or the process
// dies mid-way, the message is already gone: at-most-once, by accident.
func Consume(ch *amqp.Channel, charge func([]byte) error) error {
deliveries, err := ch.Consume("payments", "billing", true, false, false, false, nil)
if err != nil {
return err
}
for d := range deliveries {
_ = charge(d.Body) // an error here has nowhere to go
}
return nil
}// Package kafkabefore weakens both halves of the pipeline: the producer opts
// out of idempotence and only waits for the leader, and the consumer commits
// its offset before processing.
package kafkabefore
import (
"context"
"github.com/twmb/franz-go/pkg/kgo"
)
func NewProducer(brokers []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(brokers...),
// No broker-side dedup: a retried batch can land twice in the log.
kgo.DisableIdempotentWrite(),
// Ack once the leader has it; a leader crash before replication loses it.
kgo.RequiredAcks(kgo.LeaderAck()),
)
}
func Consume(ctx context.Context, brokers []string, charge func(*kgo.Record) error) error {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("payments"),
kgo.DisableAutoCommit(),
)
if err != nil {
return err
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return ctx.Err()
}
records := fetches.Records()
// Position saved first, work second. A crash between the two lines
// skips these records for good: "read, save position, process".
if err := cl.CommitRecords(ctx, records...); err != nil {
return err
}
for _, r := range records {
_ = charge(r)
}
}
}// Package redisbefore reads from a consumer group with NOACK, so entries never
// enter the pending entries list and a crash loses them.
package redisbefore
import (
"context"
"github.com/redis/go-redis/v9"
)
func Consume(ctx context.Context, rdb *redis.Client, charge func(map[string]any) error) error {
for {
streams, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "billing",
Consumer: "worker-1",
Streams: []string{"payments", ">"},
Count: 10,
Block: 0,
// NOACK: delivered means done. Nothing to re-read after a crash.
NoAck: true,
}).Result()
if err != nil {
return err
}
for _, s := range streams {
for _, msg := range s.Messages {
_ = charge(msg.Values)
}
}
}
}After
The same pipelines flipped to at-least-once on both sides, with the handler named chargeOnce to make the remaining obligation explicit. The broker-specific versions are under Broker differences; here is Kafka's.
// Package kafkaafter: idempotent producer (no duplicates from producer
// retries) plus process-then-commit on the consumer (no loss on crash).
// The result is at-least-once processing; consumer-side duplicates remain.
package kafkaafter
import (
"context"
"github.com/twmb/franz-go/pkg/kgo"
)
// NewProducer relies on franz-go's default: idempotent writes are on unless
// DisableIdempotentWrite is passed. That is the Java client's
// enable.idempotence=true, which requires acks=all.
func NewProducer(brokers []string) (*kgo.Client, error) {
return kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.RequiredAcks(kgo.AllISRAcks()),
)
}
func Consume(ctx context.Context, brokers []string, chargeOnce func(*kgo.Record) error) error {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.ConsumerGroup("billing"),
kgo.ConsumeTopics("payments"),
kgo.DisableAutoCommit(),
)
if err != nil {
return err
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return ctx.Err()
}
records := fetches.Records()
for _, r := range records {
// Idempotent on r.Key (payment id): a replay after a crash or a
// rebalance must not charge twice.
if err := chargeOnce(r); err != nil {
return err // stop; uncommitted records are re-read on restart
}
}
// Work first, position second: "read, process, save position".
if err := cl.CommitRecords(ctx, records...); err != nil {
return err
}
}
}The Go angle
None of the three Go clients has a "guarantee" setting. The guarantee is the order of two calls in your loop: d.Ack vs your handler, CommitRecords vs your handler, XAck vs your handler. Code review is how you check it.
Defaults matter, though. franz-go turns idempotent writes on by default; you opt out with kgo.DisableIdempotentWrite(), which "is incompatible with specifying a transactional id". amqp091-go publishes without confirms unless you call Channel.Confirm, and returns are only delivered to a channel registered with NotifyReturn. go-redis exposes Redis 8.6 producer idempotency as the ProducerID and IdempotentID fields of XAddArgs. Whatever the client, pass context.Context through so a shutdown stops the loop before the next message, not between the effect and the ack.
Laravel
Before
The job charges the card, then marks the order paid. With #[Tries(3)], any failure after the charge (a crash, an exception in update, or a job that outlives retry_after) re-runs the whole method.
<?php
// app/Jobs/ChargeOrder.php — correct on the happy path, wrong on a retry.
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Stripe\StripeClient;
#[Tries(3)]
class ChargeOrder implements ShouldQueue
{
use Queueable;
public function __construct(public Order $order) {}
public function handle(StripeClient $stripe): void
{
// 1. Money moves at Stripe.
$intent = $stripe->paymentIntents->create([
'amount' => $this->order->total_cents,
'currency' => 'eur',
'customer' => $this->order->stripe_customer_id,
'payment_method' => $this->order->stripe_payment_method_id,
'off_session' => true,
'confirm' => true,
]);
// 2. If the worker dies here, or the update below throws, or the job
// runs longer than retry_after, the queue hands the job out again.
// Attempt two starts at step 1 and charges the customer a second time.
$this->order->update([
'status' => 'paid',
'payment_ref' => $intent->id,
]);
}
}After
Three tools, each solving a different problem. ShouldBeUnique stops two dispatches for one order. WithoutOverlapping stops two concurrent runs. Neither stops a sequential retry from charging again. The idempotency key does: it is derived from the order, not the attempt, so Stripe returns the first PaymentIntent on every retry.
<?php
// app/Jobs/ChargeOrder.php — at-least-once delivery, effectively-once charge.
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Stripe\StripeClient;
#[Tries(3)]
#[UniqueFor(3600)]
class ChargeOrder implements ShouldQueue, ShouldBeUnique
{
use Queueable;
public function __construct(public Order $order) {}
// ShouldBeUnique: a double click cannot DISPATCH two jobs for one order.
// It does nothing about the same job being retried.
public function uniqueId(): string
{
return (string) $this->order->id;
}
// WithoutOverlapping: two copies never RUN at the same time
// (e.g. a retry_after redelivery while the first attempt is still alive).
public function middleware(): array
{
return [(new WithoutOverlapping($this->order->id))->expireAfter(180)];
}
public function handle(StripeClient $stripe): void
{
$order = $this->order->fresh();
// Cheap local guard: a previous attempt already finished.
if ($order->status === 'paid') {
return;
}
// The real guarantee: the idempotency key is derived from the order,
// not from the attempt, so every retry sends the same key and Stripe
// returns the first PaymentIntent instead of creating a second one.
$intent = $stripe->paymentIntents->create([
'amount' => $order->total_cents,
'currency' => 'eur',
'customer' => $order->stripe_customer_id,
'payment_method' => $order->stripe_payment_method_id,
'off_session' => true,
'confirm' => true,
], ['idempotency_key' => "order-{$order->id}-charge"]);
$order->update(['status' => 'paid', 'payment_ref' => $intent->id]);
}
}The Laravel angle
Laravel's built-in drivers are, in the docs' words, "the database, Amazon SQS, Redis, and Beanstalkd drivers", plus a synchronous driver and a null driver that "discards queued jobs". All of the real ones are at-least-once: a reserved job that is neither deleted nor released within retry_after is handed out again (on SQS the queue's visibility timeout plays that role). The framework gives you:
| Tool | Where it acts | What it stops | What it does not stop |
|---|---|---|---|
ShouldBeUnique + uniqueId() | Dispatch | A second dispatch while the lock is held | A retry of the same job |
#[UniqueFor(3600)] or a uniqueFor() method | Dispatch | Bounds the lock so a crashed job does not block forever | Anything after the lock expires |
ShouldBeUniqueUntilProcessing | Dispatch | Same, but unlocks when processing starts | A new dispatch during processing |
WithoutOverlapping middleware | Run time | Two attempts running at once | A sequential retry |
after_commit / afterCommit() | Dispatch | A job for a transaction that rolled back (a loss of consistency) | Duplicates |
#[Tries], backoff, retryUntil | Retry policy | Infinite retries | Duplicate side effects |
| Your idempotency key | Effect | The duplicate effect itself | (this is the real fix) |
In the framework source (Illuminate\Bus\UniqueLock), the lock key is laravel_unique_job: plus the job name and uniqueId, and the lock TTL comes from a uniqueFor() method if the job has one, otherwise from the #[UniqueFor] attribute, otherwise 0 (no expiry). The docs: "This lock is released when the job completes processing or fails all of its retry attempts."
Broker differences
RabbitMQ
The primitives are publisher confirms (confirm.select, then basic.ack/basic.nack from the broker), the mandatory flag with basic.return, persistent messages (delivery_mode=2), quorum queues for replication, and manual consumer acks. Together they give at-least-once; the Reliability Guide says so directly, and adds what is missing: "consumer applications will need to perform deduplication or handle incoming messages in an idempotent manner."
What a confirm means depends on the queue: "For persistent messages routed to durable queues, this means persisting to disk. For quorum queues, this means that a quorum replicas have accepted and confirmed the message to the elected leader." The quorum queue guide states the resulting promise: "A message that was successfully confirmed back to the publisher using the publisher confirms feature should not be lost as long as at least a majority of RabbitMQ nodes hosting the quorum queue are not permanently made unavailable."
AMQP 0-9-1 transactions (tx.select/tx.commit) exist but are not worth using: the confirms guide says they "are unnecessarily heavyweight and decrease throughput by a factor of 250", and a channel cannot be both transactional and in confirm mode. They are also not exactly-once: they make a batch of publishes atomic, not the consumer's effect.
On the consumer side, the redelivered flag is a useful hint: "If the redelivered flag is not set then it is guaranteed that the message has not been seen before", so a consumer can skip its dedup lookup for first deliveries. RabbitMQ has no producer-side dedup.
// Package rabbitafter gets at-least-once end to end: publisher confirms on the
// way in, manual acks after processing on the way out. Duplicates are still
// possible at both ends, so the handler must be idempotent.
package rabbitafter
import (
"context"
"errors"
amqp "github.com/rabbitmq/amqp091-go"
)
// NewPublisherChannel puts a channel into confirm mode once, up front.
func NewPublisherChannel(conn *amqp.Connection) (*amqp.Channel, error) {
ch, err := conn.Channel()
if err != nil {
return nil, err
}
return ch, ch.Confirm(false)
}
// Publish waits for the broker to take responsibility for the message.
// If the confirm is lost in transit the caller retries, and the message may
// be enqueued twice: that is the price of never losing it.
func Publish(ctx context.Context, ch *amqp.Channel, paymentID string, body []byte) error {
dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", "payments", false, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
// A stable id lets consumers recognise a redelivery or a re-publish.
MessageId: paymentID,
Body: body,
})
if err != nil {
return err
}
acked, err := dc.WaitContext(ctx)
if err != nil {
return err
}
if !acked {
return errors.New("broker nacked the publish; retry it")
}
return nil
}
// Consume acks only after the handler has committed its work. A crash between
// the handler and the ack causes a redelivery with Redelivered=true.
func Consume(ch *amqp.Channel, chargeOnce func(id string, body []byte) error) error {
if err := ch.Qos(50, 0, false); err != nil {
return err
}
deliveries, err := ch.Consume("payments", "billing", false, false, false, false, nil)
if err != nil {
return err
}
for d := range deliveries {
// chargeOnce must be idempotent on MessageId (see the inbox pattern).
if err := chargeOnce(d.MessageId, d.Body); err != nil {
_ = d.Nack(false, true) // requeue and try again later
continue
}
if err := d.Ack(false); err != nil {
return err
}
}
return nil
}package rabbitafter
import (
"context"
"fmt"
amqp "github.com/rabbitmq/amqp091-go"
)
// DeclarePayments makes the queue a quorum queue: replicated with Raft, always
// durable. A confirm for a message routed here means a majority of replicas
// accepted it.
func DeclarePayments(ch *amqp.Channel) error {
_, err := ch.QueueDeclare("payments", true, false, false, false, amqp.Table{
"x-queue-type": "quorum",
})
return err
}
// PublishMandatory catches the loss that confirms alone do not report: an
// unroutable message is CONFIRMED (basic.ack) and then dropped. With
// mandatory=true the broker sends basic.return (312 NO_ROUTE) before the ack.
func PublishMandatory(ctx context.Context, ch *amqp.Channel, returns <-chan amqp.Return, key string, msg amqp.Publishing) error {
dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "payments.exchange", key, true, false, msg)
if err != nil {
return err
}
acked, err := dc.WaitContext(ctx)
if err != nil {
return err
}
// basic.return arrives before basic.ack, so check it once the ack is in.
select {
case r := <-returns:
if r.MessageId == msg.MessageId {
return fmt.Errorf("unroutable: %d %s", r.ReplyCode, r.ReplyText)
}
default:
}
if !acked {
return fmt.Errorf("broker nacked message %s", msg.MessageId)
}
return nil
}
// Returns registers the listener once per channel, before publishing.
func Returns(ch *amqp.Channel) <-chan amqp.Return {
return ch.NotifyReturn(make(chan amqp.Return, 16))
}vladimir-yuldashev/laravel-queue-rabbitmq publishes with plain basic_publish and has no confirm option (checked in its README and RabbitMQQueue source), so the Laravel publisher drops down to php-amqplib, which the package depends on:
<?php
// app/Messaging/ConfirmedPublisher.php
// vladimir-yuldashev/laravel-queue-rabbitmq publishes with plain basic_publish
// and has no publisher-confirm option, so this drops down to php-amqplib
// (a dependency of that package) on a channel of the package's connection.
namespace App\Messaging;
use Illuminate\Support\Facades\Queue;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use RuntimeException;
final class ConfirmedPublisher
{
private ?AMQPChannel $channel = null;
public function publish(string $queue, string $messageId, array $payload): void
{
$channel = $this->channel();
$nacked = false;
$channel->set_nack_handler(function (AMQPMessage $message) use (&$nacked): void {
$nacked = true;
});
$channel->basic_publish(new AMQPMessage(json_encode($payload, JSON_THROW_ON_ERROR), [
'content_type' => 'application/json',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'message_id' => $messageId, // lets consumers spot a re-publish
]), '', $queue);
// Blocks until the broker acks or nacks; throws on timeout.
$channel->wait_for_pending_acks(5.0);
if ($nacked) {
// Not taken by the broker: the caller retries, possibly creating a
// duplicate if the first copy was in fact stored. Consumers dedupe.
throw new RuntimeException("Broker nacked message {$messageId}");
}
}
private function channel(): AMQPChannel
{
if ($this->channel === null) {
/** @var \VladimirYuldashev\LaravelQueueRabbitMQ\Queue\RabbitMQQueue $rabbit */
$rabbit = Queue::connection('rabbitmq');
// A dedicated channel: confirm mode is per channel and must not
// leak into the channel the queue driver uses for jobs.
$this->channel = $rabbit->getConnection()->channel();
$this->channel->confirm_select();
}
return $this->channel;
}
}Kafka
Kafka is the only one of the three with a broker-side mechanism beyond at-least-once: the idempotent producer (PID + sequence number per partition) removes producer-retry duplicates, and transactions (transactional.id, the coordinator, epochs, markers, read_committed) make a read-process-write step atomic when input, offsets and output are all Kafka topics. That is the Kafka Streams case.
The limit is in the same documentation, and the defaults matter: "Kafka guarantees at-least-once delivery by default". For a database sink you have two choices: idempotent writes (upsert by key), or store the offset in the same database transaction as the row and start the consumer from it, which is the pattern below.
// Package kafkatx is Kafka's exactly-once read-process-write: consumed offsets
// and produced records commit in one transaction. It only covers effects that
// live inside Kafka; a call to a payment API in the loop is NOT covered.
package kafkatx
import (
"context"
"time"
"github.com/twmb/franz-go/pkg/kgo"
)
// Run must get a transactional.id that is unique per running instance and
// stable across its restarts (for example the pod ordinal). Two live replicas
// sharing one id fence each other with PRODUCER_FENCED (error 90).
func Run(ctx context.Context, brokers []string, instance string, transform func(*kgo.Record) *kgo.Record) error {
sess, err := kgo.NewGroupTransactSession(
kgo.SeedBrokers(brokers...),
// transactional.id: a restarted instance with the same id bumps the
// producer epoch, fences the zombie and aborts its open transaction.
kgo.TransactionalID("payments-enricher-"+instance),
// Keep it below the group's session timeout (franz-go default 40s).
kgo.TransactionTimeout(30*time.Second),
kgo.ConsumerGroup("payments-enricher"),
kgo.ConsumeTopics("payments"),
// isolation.level=read_committed: skip records of aborted transactions.
kgo.FetchIsolationLevel(kgo.ReadCommitted()),
)
if err != nil {
return err
}
defer sess.Close()
for {
fetches := sess.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return ctx.Err()
}
if err := sess.Begin(); err != nil {
return err
}
var out []*kgo.Record
fetches.EachRecord(func(r *kgo.Record) {
o := transform(r)
o.Topic = "payments-enriched"
out = append(out, o)
})
// ProduceSync waits for every record, so the error is known before End.
commit := sess.ProduceSync(ctx, out...).FirstErr() == nil
// Commits the produced records and the group's offsets atomically.
// On a produce failure, or a rebalance mid-transaction, it aborts:
// read_committed readers never see that output, and the group's
// committed offsets stay where they were.
if _, err := sess.End(ctx, kgo.TransactionEndTry(commit)); err != nil {
return err
}
}
}// Package kafkadb is exactly-once EFFECT for a database sink without Kafka
// transactions: the business row and the consumer position are written in one
// database transaction, and on start the consumer resumes from the stored
// position instead of the group's committed offset.
package kafkadb
import (
"context"
"database/sql"
"github.com/twmb/franz-go/pkg/kgo"
)
// Run consumes one partition. Assignment is static (one process per partition
// or an external coordinator); no consumer group offsets are used at all.
func Run(ctx context.Context, db *sql.DB, brokers []string, partition int32) error {
var next int64
err := db.QueryRowContext(ctx,
`SELECT next_offset FROM consumer_offsets WHERE topic = 'payments' AND partition = $1`,
partition).Scan(&next)
if err != nil && err != sql.ErrNoRows {
return err
}
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.ConsumePartitions(map[string]map[int32]kgo.Offset{
"payments": {partition: kgo.NewOffset().At(next)},
}),
kgo.FetchIsolationLevel(kgo.ReadCommitted()),
)
if err != nil {
return err
}
defer cl.Close()
for {
fetches := cl.PollFetches(ctx)
if fetches.IsClientClosed() || ctx.Err() != nil {
return ctx.Err()
}
for _, r := range fetches.Records() {
if err := apply(ctx, db, r); err != nil {
return err // restart resumes from the last stored offset
}
}
}
}
// apply commits the effect and the position together: either both happen or
// neither, so a crash anywhere replays nothing twice and skips nothing.
func apply(ctx context.Context, db *sql.DB, r *kgo.Record) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() //nolint:errcheck // no-op after Commit
if _, err := tx.ExecContext(ctx,
`INSERT INTO payments (payment_id, body) VALUES ($1, $2) ON CONFLICT (payment_id) DO NOTHING`,
string(r.Key), r.Value); err != nil {
return err
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO consumer_offsets (topic, partition, next_offset) VALUES ($1, $2, $3)
ON CONFLICT (topic, partition) DO UPDATE SET next_offset = EXCLUDED.next_offset`,
r.Topic, r.Partition, r.Offset+1); err != nil {
return err
}
return tx.Commit()
}In Laravel, Kafka is not a built-in driver; mateusjunges/laravel-kafka is the usual package. We did not verify its transaction API for this page, so the transactional example stays in Go; a Laravel consumer of Kafka should be written as at-least-once with an idempotent handler like the ChargeOrder job above.
Redis Streams
The consumer-side primitive is the pending entries list (PEL). XREADGROUP records each delivery against the consumer, and XACK removes it. Read your own history with ID 0 after a restart, and claim a dead consumer's entries with XCLAIM/XAUTOCLAIM. That is at-least-once, and the Redis docs say so in their own consumer example: "Note that we might process a message multiple times or one time (at least in the case of consumer failures, but there are also the limits of Redis persistence and replication involved".
Durability is the qualifier. An XADD reply means "in memory". With RDB snapshots only, "you should be prepared to lose the latest minutes of data"; with AOF at the default appendfsync everysec, "you can only lose one second worth of writes"; appendfsync always is "Very very slow, very safe". Replication is asynchronous: "after a failover something can be missing", and while WAIT "makes it very unlikely that data is lost", failover "performs only a best effort check".
Producer dedup did not exist before Redis 8.6. From 8.6, XADD key IDMP <pid> <iid> * ... (or IDMPAUTO <pid>, where Redis derives the iid from the content) makes a resend a no-op, within IDMP-DURATION (1–86400 s, default 100) and IDMP-MAXSIZE (default 100 ids per producer, "stronger than IDMP-DURATION"). The docs call it "at-most-once production". A producer that recovers slower than the window, or sends more than IDMP-MAXSIZE messages before retrying, gets duplicates again. There are no transactions spanning a read and an ack, so consumer-side duplicates remain your job.
// Package redisafter: XADD with an idempotent id (Redis 8.6+) on the way in,
// XREADGROUP then XACK after processing on the way out. Unacked entries stay
// in the pending entries list and are re-read on restart.
package redisafter
import (
"context"
"github.com/redis/go-redis/v9"
)
// Publish retries are safe for as long as Redis remembers (pid, iid):
// IDMP-DURATION seconds, at most IDMP-MAXSIZE ids per producer.
func Publish(ctx context.Context, rdb *redis.Client, paymentID string, fields map[string]any) error {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "payments",
ProducerID: "checkout-api",
IdempotentID: paymentID,
Values: fields,
}).Err()
}
func Consume(ctx context.Context, rdb *redis.Client, consumer string, chargeOnce func(redis.XMessage) error) error {
// First walk our own pending entries from before a crash (an explicit ID
// returns this consumer's PEL after that ID), then switch to ">" for new ones.
history, lastID := true, "0"
for {
id := ">"
if history {
id = lastID
}
streams, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: "billing",
Consumer: consumer,
Streams: []string{"payments", id},
Count: 10,
Block: 0,
}).Result()
if err != nil {
return err
}
n := 0
for _, s := range streams {
for _, msg := range s.Messages {
n++
if history {
lastID = msg.ID
}
if err := chargeOnce(msg); err != nil {
continue // stays in the PEL; reclaim later with XAUTOCLAIM
}
if err := rdb.XAck(ctx, "payments", "billing", msg.ID).Err(); err != nil {
return err
}
}
}
if history && n == 0 {
history = false
}
}
}Laravel's redis queue driver uses lists and sorted sets, not streams, so a Laravel stream consumer uses the Redis facade (phpredis xReadGroup/xAck), with the sequence check from Measuring delivery:
<?php
// app/Console/Commands/ConsumePaymentsStream.php
// Laravel's redis queue driver uses lists and sorted sets, not streams, so a
// Redis Streams consumer talks to the stream through the Redis facade
// (phpredis: xReadGroup / xAck). At-least-once: XACK only after the work.
namespace App\Console\Commands;
use App\Payments\ChargeHandler;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class ConsumePaymentsStream extends Command
{
protected $signature = 'payments:consume {consumer}';
protected $description = 'Read the payments stream in the billing group';
public function handle(ChargeHandler $handler): int
{
$consumer = $this->argument('consumer');
// Start at '0': replay this consumer's own pending entries after a crash.
$history = true;
$cursor = '0';
while (true) {
$batch = Redis::xreadgroup('billing', $consumer, ['payments' => $cursor], 10, 2000) ?: [];
$entries = $batch['payments'] ?? [];
if ($history && $entries === []) {
$history = false;
$cursor = '>'; // history drained, now only new entries
continue;
}
foreach ($entries as $id => $fields) {
if ($history) {
$cursor = $id; // keep walking the PEL past this entry
}
// Measure: producer and seq are stamped by the publisher.
$last = (int) Redis::hget('billing:seq', $fields['producer']);
$seq = (int) $fields['seq'];
if ($seq <= $last) {
Log::info('duplicate delivery', ['id' => $id, 'seq' => $seq]);
} elseif ($seq > $last + 1) {
Log::warning('sequence gap', ['expected' => $last + 1, 'got' => $seq]);
}
// The handler is idempotent on payment_id; a redelivery is a no-op.
$handler->chargeOnce($fields['payment_id'], (int) $fields['amount']);
Redis::hset('billing:seq', $fields['producer'], max($seq, $last));
Redis::xack('payments', 'billing', [$id]);
}
}
}
}Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Producer retry duplicates | Idempotent producer | Kafka default, Redis IDMP, NATS Nats-Msg-Id, SQS FIFO | Free or nearly free | Session- or window-scoped |
| Producer restart duplicates | Stable message id + consumer dedup | Producer assigns message_id once and stores it with the outbox row | Survives restarts | Consumer needs a dedup store |
| Consumer crash duplicates | Idempotent consumer | Inbox table, unique constraint, upsert | Works on every broker | One extra write per message |
| DB sink exactly-once | Offset in the same DB transaction | consumer_offsets table updated with the row | No dedup table; true atomicity | Manual partition assignment; one DB per partition stream |
| Kafka → Kafka | Transactions | transactional.id + read_committed | Exactly-once processing | Latency of commit interval; Kafka only |
| DB write + publish | Transactional outbox | Insert event row in the business transaction; relay publishes | No lost events | At-least-once publish; consumers dedup |
| Third-party side effect | Provider idempotency key | Key derived from the business id, not the attempt | Effect deduped at the source | Provider's key retention (Stripe: keys can be pruned after 24 h) |
| Silent loss | Sequence numbers + reconciliation | Per-producer seq, gap detection, periodic counts | Loss becomes visible | Needs a heartbeat for tail losses |
Producer duplicates
Turn on (or keep) the broker's producer dedup, and still give every message a stable message_id assigned once, at creation, not per send. The id is what downstream dedup uses when the broker's window has expired or the producer restarted. In RabbitMQ the MessageId property in the Go publisher above carries it; in Kafka use the record key or a header; in Redis use the iid and a field.
Consumer replays, database sink
When the effect is a row in your own database, the cleanest exactly-once is to make the offset part of the data:
CREATE TABLE consumer_offsets (
topic text NOT NULL,
partition int NOT NULL,
next_offset bigint NOT NULL,
PRIMARY KEY (topic, partition)
);
-- one transaction per record (or per batch)
BEGIN;
INSERT INTO payments (payment_id, body) VALUES ('p-91', '{...}')
ON CONFLICT (payment_id) DO NOTHING;
INSERT INTO consumer_offsets (topic, partition, next_offset) VALUES ('payments', 3, 44)
ON CONFLICT (topic, partition) DO UPDATE SET next_offset = EXCLUDED.next_offset;
COMMIT;
-- on start: SELECT next_offset FROM consumer_offsets WHERE topic = 'payments' AND partition = 3;The Go version is after/kafkadb/store.go above. In Laravel the same shape is a DB::transaction around the insert and the offset upsert. When the consumer cannot own the offset (RabbitMQ, Laravel jobs), use the inbox table instead: Idempotent Consumers & the Inbox Pattern.
Database write that must emit an event
Publishing to a broker inside a database transaction is wrong in both orders: publish-then-commit can emit an event for a rollback, commit-then-publish can lose the event on a crash. The Transactional Outbox Pattern writes the event to an outbox table in the same transaction and lets a relay publish it at-least-once. In Laravel, after_commit fixes only the first half (no job for a rolled-back transaction), not the crash after commit.
Side effects in other systems
Payment providers, email APIs and webhooks are outside every broker transaction. Use their idempotency key (Stripe "saves the status code and body of the first request made with a given idempotency key" and returns it to retries), derived from the business id. If the provider has no key, keep a "sent" log keyed by business id and check it before calling, accepting a tiny window where a crash between call and log entry causes one duplicate.
Retries and failure handling
| Error or situation | Meaning | Retry? | Duplicate risk |
|---|---|---|---|
| Timeout waiting for a confirm or produce response | Outcome unknown | Yes | Yes, unless the broker dedups |
RabbitMQ basic.nack | Broker could not take responsibility | Yes | Low |
RabbitMQ basic.return 312 | Unroutable with mandatory | No, fix routing | n/a |
Kafka NOT_ENOUGH_REPLICAS (19) | Not written | Yes, with backoff | No |
Kafka PRODUCER_FENCED (90) | You are a zombie | Never | Retrying would duplicate |
Kafka TRANSACTION_ABORTABLE (120) | Transaction must be aborted | Abort, then reprocess the batch | No (aborted output is hidden from read_committed) |
| Consumer handler error, transient | Effect not done | Nack/requeue or let the job retry | Yes, if the effect partially happened |
| Consumer handler error, permanent (poison) | Will never succeed | No; dead-letter it | n/a |
Rules: retry only operations whose second attempt is safe; give each message an id before the first attempt; never retry after a fencing error; cap retries and send the rest to a Dead-Letter Queue; spread retries with backoff and jitter (Retry, Backoff & Delayed Delivery).
Measuring delivery
A guarantee you do not measure is a hope. Three numbers tell you what your pipeline really does:
| Metric | How to compute | What it reveals |
|---|---|---|
| Duplicate rate | Deliveries whose (producer, seq) or message_id was already seen ÷ deliveries | At-least-once at work; spikes during deploys and rebalances |
| Loss (gap) count | Sequence numbers never seen, per producer | Silent loss: unroutable messages, acks=1 failovers, auto-ack crashes |
| Reordering count | Sequence numbers that arrive after a later one | Retries with multiple in-flight requests, multiple partitions |
| Redelivery rate | RabbitMQ redelivered=true, Redis PEL delivery counter, Laravel attempts() > 1 | Consumer crashes and timeouts |
| End-to-end reconciliation | Count of source rows vs count of effects, per hour | Loss anywhere, including before the broker |
The producer stamps each message with its name and a sequence number (1, 2, 3, …) that it persists, so a restart continues the series. The consumer keeps the next expected number per producer: equal is normal, higher is a gap (maybe a loss, maybe reordering), lower is a duplicate unless it fills a gap. A loss at the very end is invisible until the producer sends again, so producers also publish a heartbeat with their current sequence.
// Package seqcheck measures delivery on the consumer side. Every producer
// stamps an application sequence number (1, 2, 3, ...) on each message; the
// consumer compares what arrives with what it expected next.
package seqcheck
// Checker is not safe for concurrent use; keep one per consumer goroutine or
// guard it with a mutex.
type Checker struct {
next map[string]uint64
missing map[string]map[uint64]struct{}
Delivered int // every message seen, duplicates included
Duplicates int // same (producer, seq) seen again
Reordered int // a seq that was counted missing arrived late
}
func New() *Checker {
return &Checker{next: map[string]uint64{}, missing: map[string]map[uint64]struct{}{}}
}
// Observe records one delivery and reports whether it was a duplicate, so the
// caller can skip the side effect as well as count it.
func (c *Checker) Observe(producer string, seq uint64) (duplicate bool) {
c.Delivered++
next, ok := c.next[producer]
if !ok {
next = 1
}
switch {
case seq == next:
c.next[producer] = seq + 1
case seq > next:
// A jump: everything between next and seq is missing for now.
m := c.missing[producer]
if m == nil {
m = map[uint64]struct{}{}
c.missing[producer] = m
}
for s := next; s < seq; s++ {
m[s] = struct{}{}
}
c.next[producer] = seq + 1
default:
if _, late := c.missing[producer][seq]; late {
delete(c.missing[producer], seq)
c.Reordered++
return false
}
c.Duplicates++
return true
}
return false
}
// Missing is the number of sequence numbers never seen. A loss at the very end
// is invisible until the producer sends again (or reports its last seq), so
// producers should publish a periodic heartbeat with their current seq.
func (c *Checker) Missing() int {
n := 0
for _, m := range c.missing {
n += len(m)
}
return n
}
// Expect closes the books for a producer whose last sent seq is known.
func (c *Checker) Expect(producer string, last uint64) {
next, ok := c.next[producer]
if !ok {
next = 1
}
if last >= next {
c.Observe(producer, last+1) // marks next..last missing
c.Delivered--
c.next[producer] = last + 1
}
}The same checks in SQL, over a table of received messages:
-- duplicates per producer
SELECT producer, count(*) - count(DISTINCT seq) AS duplicates
FROM received GROUP BY producer;
-- gaps: first missing sequence number after each run
SELECT producer, seq + 1 AS first_missing, next_seq - seq - 1 AS missing_count
FROM (
SELECT producer, seq, lead(seq) OVER (PARTITION BY producer ORDER BY seq) AS next_seq
FROM (SELECT DISTINCT producer, seq FROM received) d
) t
WHERE next_seq > seq + 1;Lag and DLQ metrics, and trace propagation through headers, are in Messaging Observability & Tracing.
Choosing semantics per use case
| Use case | Semantics to accept | Mechanism | Reason |
|---|---|---|---|
| Payments, wallet credits, ledger entries | Effectively-once | At-least-once + idempotent consumer (inbox or unique key) + provider idempotency key; outbox on the producer side | One duplicate costs money; one loss costs more |
| Inventory reservations | Effectively-once | Idempotent reservation keyed by order line | Double reservation blocks stock |
| Notifications (email, SMS, push) | At-least-once + best-effort dedup | Sent-log keyed by notification id; provider key if offered | A rare duplicate is annoying, a lost password reset is worse |
| Webhooks to customers | At-least-once, documented | Event id in every delivery; tell receivers to dedup | The receiver is outside your boundary |
| Analytics, clickstream | At-least-once (dedup downstream) or at-most-once | Idempotent upserts or dedup on event id in the warehouse | Counts tolerate small error; volume is huge |
| Metrics, presence, cache hints | At-most-once | Fire-and-forget, Redis Pub/Sub, acks=0/acks=1 | The next message supersedes the lost one |
| Audit log, compliance trail | At-least-once with loss detection | Persistent + replicated (quorum queue, acks=all + min.insync.replicas=2), sequence numbers, reconciliation | A gap is a finding; a duplicate is deduped by event id |
| Kafka stream processing (topic → topic) | Exactly-once processing | processing.guarantee=exactly_once_v2 or transactional producer + read_committed | Closed system; cheap at sane commit intervals |
| Search index, read model projection | At-least-once | Upsert by id with a version check | Natural idempotency |
In production systems
- Kafka's own definition of at-most-once is a configuration recipe, not a mode: "disabling retries on the producer and committing offsets in the consumer prior to processing a batch of messages" (Kafka design docs). It exists to make the trade-off explicit.
- Kafka 3.0 changed the producer defaults to
enable.idempotence=trueandacks=all(KIP-679, "Producer config defaults will change in release version 3.0"), so an upgrade silently removed a whole class of producer duplicates for most Java users, and silently disabled it for anyone with a conflictingacks=1override. - Confluent's benchmark of the cost: for 1 KB messages and 100 ms transactions, transactional producer throughput fell 3% against an
acks=allat-least-once producer; Kafka Streams lost 15–30% at a 100 ms commit interval and nothing measurable at 30 s for 1 KB messages. - RabbitMQ's numbers on AMQP transactions: "decrease throughput by a factor of 250", the reason publisher confirms exist.
- Laravel's
retry_after/--timeoutrule is a documented duplicate source, andShouldBeUniqueis a dispatch-time cache lock (laravel_unique_job:<job>:<uniqueId>inIlluminate\Bus\UniqueLock), not a run-once guarantee.
In architecture: from a single process to a distributed system
A delivery guarantee is a property of a boundary. Inside one process with one database, there is often no message to lose. Every boundary you add (a queue, a service, a region) adds a hop from the failure-point table and a place where you must choose loss or duplicate.
Monolith: one process, one database
The simplest correct design is to avoid the hop: do the work in the request inside one ACID transaction. When you do queue work (a Laravel job on the database or redis driver), you are at-least-once immediately: the job can run twice after a worker crash or a retry_after expiry. Concrete example: an e-commerce monolith in Laravel dispatches SendOrderConfirmation and ChargeOrder. ChargeOrder carries an idempotency key derived from the order; SendOrderConfirmation checks a notifications_sent row keyed by order id. after_commit=true on the connection ensures no job exists for an order whose transaction rolled back. An in-process event (Event::dispatch without ShouldQueue) has no delivery semantics at all: it runs in the same call stack and fails with it.
Modular monolith and multiple databases
Modules talk through in-process events or an internal queue. As soon as two modules own different databases (or different schemas with separate transactions), "update mine and tell yours" is the dual-write problem: use an outbox per module, at-least-once delivery between them, and an idempotent handler in the receiving module. Concrete example: the Billing module writes invoice_issued to its outbox in the same transaction as the invoice; the Ledger module consumes it through a Laravel job and inserts a ledger row with a unique (source, event_id) constraint. Both modules stay in one deploy, but the contract between them is already the microservice contract. See Domain Events vs Integration Events.
Microservices: at-least-once everywhere, idempotency at every edge
Across services there is no shared transaction, so every edge is at-least-once and every consumer must be idempotent. Concrete flow for checkout:
1 Order service: BEGIN; INSERT order; INSERT outbox(OrderPlaced, event_id=e1); COMMIT
2 Relay: publish OrderPlaced e1 (confirms / acks=all); crash before marking sent
3 Relay restart: publish OrderPlaced e1 again -> duplicate on the wire
4 Payment service: inbox INSERT e1 -> ok; charge with Idempotency-Key order-42; ack
5 Payment service: inbox INSERT e1 -> unique violation; ack, no charge -> effectively-once
6 Payment service: outbox(PaymentCaptured, e2) ... same pattern downstreamIf a step fails permanently, a compensating action runs, which is the Saga Pattern. The broader catalogue of failure handling between services is in Designing for Failure: Reliable Messaging, and when to use messaging at all versus a synchronous call is in Service Communication. If the services are Kafka-native stream processors, Kafka transactions can replace the inbox for the Kafka → Kafka hops only.
Distributed data: replicas, regions and failover
Replication turns "acknowledged" into a question of how many copies. With Kafka, acks=all and min.insync.replicas=2 on a replication factor of 3 survive one broker loss without losing acknowledged writes; an unclean leader election can still trade that for availability. With RabbitMQ, quorum queues need a majority; a classic queue on the lost node loses its messages. With Redis, replication is asynchronous and failover is best effort, so an acknowledged XADD can vanish; treat Redis Streams as at-least-once only while the primary lives, and use sequence numbers to detect the gap. Across regions (Kafka MirrorMaker 2, RabbitMQ Shovel or Federation), the mirror is itself a consumer plus a producer, so apply the same table to it: unless it is configured for exactly-once, plan for at-least-once and for duplicates on the remote side after a mirror restart. The replica-lag theory is in Replication & Failover and consensus in Distributed SQL, Consensus & 2PC.
Scaling path: 1×, 10×, 100×
| Load | What changes | Delivery consequence |
|---|---|---|
| 1× (hundreds of msg/s) | One queue, a few workers, synchronous confirms | Duplicates are rare; still build idempotent handlers now, it is cheap |
| 10× (thousands of msg/s) | Batched confirms, many partitions, consumer groups, autoscaled workers | Rebalances and scale-downs become the main duplicate source; inbox tables grow, add TTLs |
| 100× (hundreds of thousands of msg/s) | Kafka transactions with longer commit intervals, dedup in stream processors, sharded inbox | Per-message dedup lookups dominate cost; prefer natural idempotency (upserts, versioned writes) and windowed dedup; measure duplicate and gap rates per partition |
Lab
Part 1 (run on the host, no broker). A single Go program simulates a producer sending 10,000 messages to an in-memory broker over a link that loses 5% of requests and 5% of acks. The seed is fixed, so the output is reproducible. The consumer side runs the sequence checker from Measuring delivery.
// Command lab simulates a producer sending to a broker over a link that loses
// requests and acks. It needs no broker: the "broker" is an in-memory log.
// The seed is fixed, so every run prints the same numbers.
package main
import (
"fmt"
"math/rand/v2"
"academy/delivery-guarantees/seqcheck"
)
const (
messages = 10000
lossReq = 0.05 // request lost: broker never sees it
lossAck = 0.05 // ack lost: broker stored it, producer never hears back
maxRetries = 10
)
type entry struct {
producer string
seq uint64 // application sequence number, stamped by the producer
}
// broker is a log. With dedup on it behaves like Kafka's idempotent producer:
// it remembers the last session sequence per producer id and ignores repeats.
type broker struct {
log []entry
dedup bool
last map[string]uint64
}
func (b *broker) append(pid string, sessionSeq uint64, e entry) {
if b.dedup {
if sessionSeq <= b.last[pid] {
return // duplicate retry: acknowledge again, store nothing
}
b.last[pid] = sessionSeq
}
b.log = append(b.log, e)
}
type mode struct {
name string
retry bool
dedup bool
restart int // every N messages the producer crashes and gets a new id
}
func run(m mode) {
rng := rand.New(rand.NewPCG(42, 7))
b := &broker{dedup: m.dedup, last: map[string]uint64{}}
session, pid, sessionSeq := 1, "producer-s1", uint64(0)
for seq := uint64(1); seq <= messages; seq++ {
sessionSeq++ // one session sequence per message, reused on retry
for attempt := 0; ; attempt++ {
reqLost := rng.Float64() < lossReq
ackLost := rng.Float64() < lossAck
if !reqLost {
b.append(pid, sessionSeq, entry{"orders-api", seq})
}
acked := !reqLost && !ackLost
if acked || !m.retry || attempt == maxRetries {
break
}
// Crash on a lost ack: the new process has a new producer id and
// resends the unconfirmed message from its own outbox.
if m.restart > 0 && int(seq)%m.restart == 0 && !reqLost {
session++
pid, sessionSeq = fmt.Sprintf("producer-s%d", session), 1
}
}
}
c := seqcheck.New()
effects := 0
for _, e := range b.log {
if !c.Observe(e.producer, e.seq) {
effects++ // the consumer skips the side effect for a duplicate
}
}
c.Expect("orders-api", messages)
fmt.Printf("%-26s log=%5d duplicates=%4d missing=%4d effects-after-dedup=%5d\n",
m.name, len(b.log), c.Duplicates, c.Missing(), effects)
}
func main() {
fmt.Printf("sent %d messages, request loss %.0f%%, ack loss %.0f%%\n", messages, lossReq*100, lossAck*100)
run(mode{name: "at-most-once (no retry)"})
run(mode{name: "at-least-once (retry)", retry: true})
run(mode{name: "idempotent producer", retry: true, dedup: true})
run(mode{name: "idempotent + restarts", retry: true, dedup: true, restart: 50})
}cd docs/snippets/messaging/delivery-guarantees/go
go run ./lab
go test ./seqcheck/Output (actually run, Go 1.26, macOS):
sent 10000 messages, request loss 5%, ack loss 5%
at-most-once (no retry) log= 9485 duplicates= 0 missing= 515 effects-after-dedup= 9485
at-least-once (retry) log=10514 duplicates= 514 missing= 0 effects-after-dedup=10000
idempotent producer log=10000 duplicates= 0 missing= 0 effects-after-dedup=10000
idempotent + restarts log=10014 duplicates= 14 missing= 0 effects-after-dedup=10000What to read from it:
- At-most-once loses about the request-loss rate (515 of 10,000) and never duplicates.
- At-least-once loses nothing and duplicates about the ack-loss rate (514): every lost ack became a retry of something already stored.
- Idempotent producer (broker remembers the last session sequence per producer id, like Kafka's PID + seq): no loss, no duplicates.
- Idempotent + restarts: each time the producer crashed on a lost ack and came back with a new identity, its resend was a new session to the broker, so 14 duplicates came back. Only the consumer-side check (
effects-after-dedup=10000) removes them. That is why effectively-once needs the consumer.
Part 2 (broker commands, expected, not run). These reproduce the failure points against real brokers; per the lab cost rule they are written out with expected output and were not executed.
# Experiment A (Kafka): duplicates from a non-idempotent producer.
kafka-topics.sh --bootstrap-server localhost:9092 --create --topic dg --partitions 1 --replication-factor 1
kafka-producer-perf-test.sh --topic dg --num-records 100000 --record-size 100 --throughput -1 \
--producer-props bootstrap.servers=localhost:9092 enable.idempotence=false acks=1 retries=5 request.timeout.ms=50
# expected, not run: with a 50 ms request timeout under load, some requests time out after the
# leader appended them; the topic ends with MORE than 100000 records:
kafka-get-offsets.sh --bootstrap-server localhost:9092 --topic dg
# dg:0:100000+N (N > 0); repeat with enable.idempotence=true acks=all -> dg:0:100000
# Experiment B (Kafka): read_committed hides aborted output.
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic payments-enriched \
--isolation-level read_committed --from-beginning
# expected, not run: kill the Go copier (after/kafkatx) between ProduceSync and End;
# a read_uncommitted consumer shows the records, a read_committed one never does.
# Experiment C (RabbitMQ): the confirmed loss.
rabbitmqadmin declare exchange name=payments.exchange type=direct
# publish to routing key "nowhere" with mandatory=false in confirm mode
# expected, not run: basic.ack arrives, no queue has the message. With mandatory=true:
# basic.return reply_code=312 reply_text=NO_ROUTE, then basic.ack.
# Experiment D (RabbitMQ): consumer crash before ack -> redelivered=true.
# consume with manual ack, kill -9 the consumer after the side effect, before Ack.
rabbitmqctl list_queues name messages_ready messages_unacknowledged
# expected, not run: messages_unacknowledged drops to 0, messages_ready +1; the next
# consumer receives the message with redelivered=true.
# Experiment E (Redis Streams): PEL replay and IDMP.
redis-cli XGROUP CREATE payments billing $ MKSTREAM
redis-cli XADD payments IDMP checkout-api p-91 '*' amount 100
redis-cli XADD payments IDMP checkout-api p-91 '*' amount 100
redis-cli XLEN payments
# expected, not run (Redis 8.6+): (integer) 1 -- the second XADD was deduplicated
redis-cli XREADGROUP GROUP billing c1 COUNT 1 STREAMS payments '>'
redis-cli XPENDING payments billing
# expected, not run: 1 pending entry for c1 until XACK; XREADGROUP ... STREAMS payments 0 re-reads it
# Experiment F (Laravel): retry_after shorter than the job.
# config/queue.php: 'retry_after' => 10; job sleeps 15 s then logs; two workers:
php artisan queue:work redis --timeout=30 &
php artisan queue:work redis --timeout=30 &
# expected, not run: the log shows the job's handle() twice for one dispatch.Common misconceptions
| Belief | Reality |
|---|---|
| "Kafka has exactly-once, so my consumer is exactly-once" | Only for Kafka writes inside a transaction plus read_committed readers; DB, HTTP and email effects are at-least-once |
| "The idempotent producer removes all duplicates" | It removes producer retries within one producer session and partition; restarts and consumer crashes still duplicate |
"ShouldBeUnique makes a Laravel job run once" | It prevents a second dispatch while its lock is held; a retry of the same job runs again |
| "Acks mean no duplicates" | Lost acks are what create duplicates |
| "Publisher confirms mean the message is in a queue" | An unroutable non-mandatory message is confirmed and dropped |
| "A persistent message cannot be lost" | Only as durable as the queue and node; quorum queues need a majority to survive |
| "Redis Streams with consumer groups are as durable as Kafka" | Async replication and appendfsync everysec can lose acknowledged entries on failover |
| "Redis has no producer dedup" | Not before 8.6; from 8.6 IDMP dedups within a bounded window |
| "RabbitMQ transactions give exactly-once" | They make publishes atomic at 250× lower throughput; nothing about the consumer's effect |
"read_committed removes duplicates" | It hides aborted records only |
| "Exactly-once is too slow to use" | 3% producer overhead in Confluent's benchmark; cost is mostly commit-interval latency |
| "At-most-once is never acceptable" | It is the right choice for superseded data such as metrics and presence |
| "We have never seen a duplicate, so we do not need idempotency" | Duplicates appear in deploys, rebalances and failovers; measure the duplicate rate |
Cheat sheet
| Topic | Remember |
|---|---|
| The three | At-most-once loses, at-least-once duplicates, exactly-once is a boundary property |
| Two generals | After a timeout the sender cannot tell lost request from lost ack |
| Consumer order | Ack after work = at-least-once; ack before work = at-most-once |
| Producer order | Retry until acked = at-least-once; no retry = at-most-once |
| Effectively-once | At-least-once + idempotent effect keyed by a stable business id |
| Kafka producer | acks=all, enable.idempotence=true (default since 3.0), max.in.flight ≤ 5 |
| Kafka EOS | transactional.id (unique per instance, stable across restarts) + sendOffsetsToTransaction + read_committed |
| Kafka fencing | initTransactions bumps the epoch; zombies get PRODUCER_FENCED |
| RabbitMQ | Confirms + mandatory + persistent + quorum queue + manual ack = at-least-once |
| Redis Streams | PEL + XACK = at-least-once; AOF/replication bound durability; IDMP from 8.6 |
| Laravel | Every driver is at-least-once; --timeout < retry_after; ShouldBeUnique is dispatch-only |
| DB sink | Store the offset in the same transaction as the row |
| DB write + event | Outbox |
| Measure | Per-producer sequence numbers: duplicates, gaps, reorders; reconcile counts |
| Use cases | Payments effectively-once; notifications at-least-once; metrics at-most-once; audit at-least-once + gap detection |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A producer times out waiting for an ack. Why can it not know whether to retry? Must-know
Answer
Answer: A timeout looks the same whether the request was lost (not stored) or the ack was lost (stored). This is the two generals problem: retrying risks a duplicate, not retrying risks a loss.
2 — A Kafka consumer commits offsets, then processes the batch, then crashes. What semantics is that? Must-know
Answer
Answer: At-most-once: the restarted consumer resumes after the committed offsets, so the unprocessed records are skipped.
3 — What exactly does enable.idempotence=true protect against, and what not? Must-know
Answer
Answer: Duplicates from producer retries within one producer session (one PID) per partition. Not: an application that re-sends after a restart (new PID), and not consumer-side duplicates.
4 — Your Kafka Streams app reads payments, writes scores, and also inserts into PostgreSQL in the same loop. Which effects are exactly-once with EOS enabled? Good to know
Answer
Answer: The writes to scores and the consumed offsets. The PostgreSQL insert is outside the transaction and can repeat on abort/retry, so it must be idempotent.
5 — What is a zombie producer and how does Kafka stop it? Important
Answer
Answer: An old instance still running after a new one with the same transactional.id took over. initTransactions bumps the producer epoch; requests from the old epoch fail with PRODUCER_FENCED / INVALID_PRODUCER_EPOCH.
6 — A RabbitMQ publisher in confirm mode gets basic.ack but the message is in no queue. How? Important
Answer
Answer: The message was unroutable and published with mandatory=false. The broker confirms unroutable messages once it knows they route nowhere. Use mandatory=true and handle basic.return (312 NO_ROUTE), or an alternate exchange.
7 — Why can an acknowledged Redis Streams XADD be lost? Important
Answer
Answer: The reply is sent before the write is fsynced (AOF everysec can lose about a second) and before replicas have it; failover is best effort, so a promoted replica may lack it.
8 — A Laravel job implements ShouldBeUnique and still charges twice. Give two ways that can happen. Must-know
Answer
Answer: A retry after an exception that happened after the charge (the unique lock only blocks new dispatches), or a retry_after expiry while the first attempt is still running (--timeout longer than retry_after).
9 — How do you get exactly-once effect into a database from Kafka without Kafka transactions? Must-know
Answer
Answer: Write the row and the next offset in the same database transaction, and start the consumer from the stored offset (or make the write idempotent by key).
10 — How do sequence numbers detect loss, and what loss can they miss? Good to know
Answer
Answer: The consumer expects seq n+1 after n; a jump reveals missing numbers. A loss of the last messages is invisible until the producer sends again, so producers send heartbeats with their current seq.
11 — Which semantics would you choose for an audit trail, and why? Must-know
Answer
Answer: At-least-once on replicated, persistent storage with sequence numbers and reconciliation: a gap is a compliance finding, duplicates are removed by event id.
Glossary
| Term | Meaning |
|---|---|
| At-most-once | Each message is processed zero or one time; loss possible, no duplicates |
| At-least-once | Each message is processed one or more times; no loss, duplicates possible |
| Exactly-once delivery | Receiver gets it once and sender knows; impossible over a lossy network |
| Exactly-once processing | The effect equals one processing, inside a boundary that commits atomically |
| Effectively-once | At-least-once delivery plus an idempotent effect |
| Two generals problem | No finite protocol over a lossy channel guarantees agreement (Gray 1978) |
| Guaranteed Delivery | EIP pattern: store-and-forward so a sent message is always on disk somewhere |
| Idempotent Receiver | EIP pattern: a receiver for which a duplicate has no extra effect |
| Idempotency key | Stable id (business id or message id) used to detect repeats |
| Idempotent producer | Broker dedup of producer retries (Kafka PID + sequence) |
| Producer id (PID) | Id the Kafka broker assigns to a producer session |
| Sequence number | Per-partition batch counter (Kafka) or per-producer message counter (application) |
enable.idempotence | Kafka producer setting for the idempotent producer; default true since 3.0 |
acks | Kafka producer setting: 0, 1, or all replicas before the ack |
min.insync.replicas | Minimum in-sync replicas for an acks=all write to succeed |
max.in.flight.requests.per.connection | Unacked requests per connection; ≤ 5 for idempotence |
transactional.id | Stable id of a transactional producer across restarts |
| Transaction coordinator | Broker owning a transactional.id in __transaction_state |
| Producer epoch | Counter bumped on initTransactions; fences older instances |
| Zombie | Old instance still running after its replacement started |
| Fencing | Rejecting requests from a zombie (PRODUCER_FENCED) |
sendOffsetsToTransaction | Adds consumer offsets to the producer's transaction |
| Control record / marker | COMMIT or ABORT record written into partitions at transaction end |
| Last stable offset (LSO) | Highest offset a read_committed consumer may read |
isolation.level | Kafka consumer setting: read_uncommitted (default) or read_committed |
transaction.timeout.ms | Time after which the coordinator aborts an open transaction |
| Publisher confirms | RabbitMQ: broker acks/nacks published messages (confirm.select) |
mandatory flag | RabbitMQ: return unroutable messages with basic.return |
basic.return | RabbitMQ method returning an unroutable mandatory message (312 NO_ROUTE) |
| Persistent message | RabbitMQ delivery_mode=2: written to disk on durable queues |
| Quorum queue | RabbitMQ Raft-replicated durable queue; confirms need a majority |
redelivered flag | RabbitMQ hint that a message may have been seen before |
| Pending entries list (PEL) | Redis Streams per-group list of delivered, unacked entries |
XACK / XAUTOCLAIM | Redis: acknowledge an entry / claim idle entries of another consumer |
IDMP / IDMPAUTO | Redis 8.6+ XADD options for producer dedup within a window |
AOF / appendfsync | Redis append-only file and its fsync policy (always, everysec, no) |
WAIT | Redis command waiting for replicas to acknowledge writes (best effort) |
retry_after | Laravel: seconds before a reserved job is handed out again |
ShouldBeUnique | Laravel: dispatch-time lock so only one job per uniqueId is queued |
uniqueFor / #[UniqueFor] | Laravel: TTL of the unique lock |
ShouldBeUniqueUntilProcessing | Laravel: unique lock released when processing starts |
Nats-Msg-Id | NATS JetStream header for dedup within the stream's duplicate window |
| SQS FIFO dedup id | Amazon SQS id deduplicating sends within 5 minutes |
| Outbox | Event row written in the business transaction, published later |
| Duplicate rate | Share of deliveries that repeat an already-seen message |
References
- Apache Kafka documentation, Design: Message Delivery Semantics, Replication, Using Transactions. kafka.apache.org
- Apache Kafka, Producer Configs (
acks,enable.idempotence,max.in.flight.requests.per.connection,transactional.id,transaction.timeout.ms). kafka.apache.org - Apache Kafka, Protocol: error codes. kafka.apache.org
- KIP-98, Exactly Once Delivery and Transactional Messaging. cwiki.apache.org
- KIP-447, Producer scalability for exactly once semantics. cwiki.apache.org
- KIP-679, Producer will enable the strongest delivery guarantee by default. cwiki.apache.org
- KIP-890, Transactions Server-Side Defense. cwiki.apache.org
- Neha Narkhede and Guozhang Wang, "Exactly-Once Semantics Are Possible: Here's How Kafka Does It", Confluent blog, 30 June 2017. confluent.io
- Jim Gray, Notes on Data Base Operating Systems, 1978, §5.8.3.3.1 "The Generals Paradox". PDF
- "Two Generals' Problem" (secondary source, for the 1975 attribution). Wikipedia
- Hohpe and Woolf, Enterprise Integration Patterns: Guaranteed Delivery, Idempotent Receiver
- RabbitMQ documentation (rabbitmq-website sources): Reliability Guide, Consumer Acknowledgements and Publisher Confirms, Publishers, Quorum Queues
- Redis: Streams, Idempotent message processing, Persistence
- NATS: JetStream streams
- Amazon SQS: Exactly-once processing
- Apache Pulsar: Why transactions
- Laravel 13 documentation: Queues; framework source
Illuminate/Bus/UniqueLock.php - vladimir-yuldashev/laravel-queue-rabbitmq, php-amqplib publisher confirms demo, phpredis README
- Stripe API, Idempotent requests
- Go packages:
amqp091-go,franz-go/pkg/kgo,go-redis/v9