الانتقال إلى المحتوى
Software ArchitectureMicroservices· 7 دقائق للقراءة

Exactly-Once Delivery Is a Myth: Designing Idempotent Consumers

Brokers deliver at least once, and their exactly-once features are narrower than their names. Record each message id in the same transaction as its effect.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The Loyalty service adds points when it receives OrderPaid. After a Tuesday deploy, a few customers have double points for the same order, and finance's monthly report doesn't reconcile. The team is puzzled: months ago they turned on the broker's duplicate detection. The logs show the same message id handled twice, by two consumer instances a few seconds apart, right as the old instance was shutting down.

The common misconception

The belief: a good message broker guarantees that each message is processed exactly once, so consumer code never has to think about duplicates.

It's an easy belief to pick up. Brokers advertise exactly-once features and settings with reassuring names, such as idempotent producers and duplicate detection. In development nothing crashes mid-message, so duplicates never show up. Even Kafka's documentation, which supports exactly-once processing in specific setups, warns about the phrase: "Many systems claim to provide “exactly-once” delivery semantics, but it is important to read the fine print, because sometimes these claims are misleading (i.e. they don’t translate to the case where consumers or producers can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost)."

What actually happens

Processing and acknowledging are two steps

A consumer does its work and then tells the broker it's done. Nothing makes those two steps one. Kafka's docs walk through both orders. Save the position first and crash before processing, and messages are lost: at-most-once. Process first and crash before saving the position, and "the first few messages it receives will already have been processed": at-least-once.

RabbitMQ's reliability guide gives the same rule from the other side: a consumer "should not acknowledge messages until it has done whatever it needs to do with them", and "Use of acknowledgements guarantees at least once delivery." For anything you can't afford to lose, is the real option, and duplicates come with it.

Duplicates come from both ends

On the publishing side, a producer that recovers from a failure resends messages the broker never confirmed. RabbitMQ: "There is a possibility of message duplication here, because the broker might have sent a confirmation that never reached the producer". An outbox relay, covered in the next article, publishes at least once for the same reason. On the consuming side, crashes, deploys, rebalances and lock timeouts all lead to redelivery, so "consumers must be prepared to handle deliveries they have seen in the past."

What the "exactly-once" features cover

They're real, and each one is narrower than its name suggests:

  • Kafka's idempotent producer deduplicates producer resends with a producer id and sequence numbers, so "resending will not result in duplicate entries in the log." It says nothing about your consumer.
  • Kafka transactions give exactly-once results when you read from Kafka and write back to Kafka. For anything else, "Exactly-once delivery for other destination systems generally requires cooperation with such systems". Otherwise, "Kafka guarantees at-least-once delivery by default".
  • Azure Service Bus duplicate detection drops a message sent again with the same application-set MessageId within a time window, 10 minutes by default and up to 7 days. It protects the queue from the sender, not your handler from redelivery.
  • RabbitMQ's redelivered flag is a hint that a consumer "may have seen this message before". It tracks the broker's own redeliveries, so a message the publisher sent twice arrives as two fresh messages.

Kafka's docs point at the general answer for external systems: let "the consumer store its offset in the same place as its output." In application code, that means storing the message id where the effect is stored.

Idempotent consumers

Chris Richardson's pattern defines the goal: "the outcome of processing the same message repeatedly must be the same as processing the message once." Some effects have that by nature. Setting an order's status to Paid twice is harmless, and Kafka's docs note that with a primary key, "receiving the same message twice just overwrites a record with another copy of itself." Adding points isn't like that. For those effects, the pattern's answer is to "record the IDs of processed messages in the database" and skip the ones already there.

The fix: the dedupe row and the effect in one transaction

C# OrderPaidHandler.cs
using Microsoft.EntityFrameworkCore;public sealed class OrderPaidHandler(LoyaltyDb db){    public async Task HandleAsync(OrderPaid msg, CancellationToken ct)    {        var account = await db.Accounts.SingleAsync(            a => a.CustomerId == msg.CustomerId, ct);        account.Points += msg.Points; // runs again on every redelivery        await db.SaveChangesAsync(ct);        // A crash here, before the ack, delivers the message again    }}

EF Core's docs state the property this relies on: "all changes in a single call to SaveChanges are applied in a transaction", so the balance never changes without the id being recorded, or the other way round. The AnyAsync check is only the fast path. The primary key on ProcessedMessages is the real guard: when two instances receive the same message at the same moment, one save fails, its points roll back, and the redelivered copy finds the id and is acknowledged.

The trade-off is real. You store a row per message and need a retention period longer than any redelivery can be late. Every message costs an extra lookup. And the guarantee covers only effects in that same database.

MechanismProtects againstDoesn't cover
Kafka idempotent producerProducer resends duplicating log entriesConsumers reprocessing after a crash
Kafka transactionsDuplicates when reading and writing Kafka topicsWrites to databases, emails, other APIs
Service Bus duplicate detectionThe same MessageId sent again within the windowRedelivery to your handler
RabbitMQ redelivered flagA hint about broker redeliveriesMessages the publisher sent twice
Idempotent consumerAny duplicate, for effects in its own databaseSide effects outside that transaction

How to apply it in your project

  1. List the non-idempotent handlersFind consumers whose effects add up when repeated: increments, inserts, emails, payments and calls to other services.
  2. Give every message a stable idSet the id where the message is created, such as the outbox row's id or a business key, never per delivery.
  3. Store processed ids with the effectAdd a processed-messages table with a primary key, write to it in the same transaction as the change, and delete old rows on a schedule.
  4. Test with duplicatesIn integration tests, deliver the same message twice, and twice at once, and assert the result is the same as delivering it once.

Key takeaways

  • Brokers deliver at least once; a crash between processing and acknowledging always allows a duplicate.
  • Exactly-once features are narrower than their names: producer dedup, Kafka-to-Kafka transactions, send-side windows.
  • An idempotent consumer gives the same result for a message processed once or many times.
  • Record the message id in the same transaction as the effect, with a primary key as the guard.
  • Effects outside your database need an idempotency key downstream or an outbox.

📚 المصادر

  1. Design: Message Delivery Semantics — Apache Kafka documentation (4.4)
  2. Reliability Guide — RabbitMQ documentation
  3. Pattern: Idempotent Consumer — Chris Richardson, microservices.io
  4. Duplicate message detection — Azure Service Bus, Microsoft Learn
  5. Transactions — EF Core, Microsoft Learn

التعليقات (0)