
Exactly-Once Delivery Is a Myth: Designing Idempotent Consumers
- كاتب موثّق
محتويات المقال
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
What actually happens
Processing and acknowledging are two steps
Duplicates come from both ends
What the "exactly-once" features cover
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 MessageIdwithin 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.
Idempotent consumers
The fix: the dedupe row and the effect in one transaction
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 }}using Microsoft.EntityFrameworkCore;public sealed class OrderPaidHandler(LoyaltyDb db){ public async Task HandleAsync(OrderPaid msg, CancellationToken ct) { var id = msg.MessageId; // set by the producer, the same on every copy if (await db.ProcessedMessages.AnyAsync(p => p.Id == id, ct)) return; // already applied: just acknowledge it var account = await db.Accounts.SingleAsync( a => a.CustomerId == msg.CustomerId, ct); account.Points += msg.Points; db.ProcessedMessages.Add(new ProcessedMessage(id, DateTime.UtcNow)); // One SaveChanges is one transaction: points and id commit together. // A concurrent copy fails on the primary key and rolls back its points await db.SaveChangesAsync(ct); }}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.
MessageId sent again within the window | ||
How to apply it in your project
List the non-idempotent handlers Find consumers whose effects add up when repeated: increments, inserts, emails, payments and calls to other services. Give every message a stable id Set the id where the message is created, such as the outbox row's id or a business key, never per delivery. Store processed ids with the effect Add 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. Test with duplicates In 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.
التعليقات (0)