Covers at-most-once and at-least-once delivery, where duplicates come from, why end-to-end exactly-once delivery is impossible over an unreliable network, what broker features (Kafka idempotent producer and transactions, Service Bus duplicate detection, SQS FIFO dedup) actually guarantee, and how idempotent consumers deliver effectively-once processing.
At-most-once means settle first, then process: a crash loses the message. At-least-once means process first, then settle: a crash or lock expiry redelivers, so you get duplicates. Almost every real system chooses at-least-once.
Exactly-once delivery is a myth because the acknowledgement itself can be lost after the work is done; the broker can't tell "not processed" from "processed but ack lost".
What you build is effectively-once processing: at-least-once delivery plus an idempotent consumer, using a natural idempotent write or an inbox row committed in the same transaction. The trade-off is extra storage and a unique-key check per message.
"The guarantee depends on when the consumer acknowledges relative to doing the work. If I acknowledge first and then process, which is receive-and-delete in Service Bus or auto-commit before processing in Kafka, a crash in the middle loses the message: that is at-most-once, fine for metrics, wrong for payments. If I process first and then acknowledge, a crash after the database commit but before the complete means the broker redelivers: that is at-least-once, and it is what I use for anything that matters. Duplicates also come from producers retrying a send after a timeout, from lock expiry when a handler is slow, and from Kafka rebalances.
Exactly-once delivery is a myth in the sense that no broker can promise your handler runs once, because the acknowledgement travels over the same unreliable network; it is the Two Generals problem. Vendors use the phrase for narrower things. Kafka's idempotent producer and transactions give exactly-once for a consume-transform-produce loop where input offsets and output records commit atomically inside Kafka; the moment you write to SQL Server or call Stripe, you are back to at-least-once. Service Bus duplicate detection remembers
MessageIds for a window, default ten minutes and up to seven days, and silently drops a resend; that protects against producer retries, not against your handler running twice.So what I build is effectively-once processing. For example, at [company] our [invoice consumer] used an inbox table with a unique key on (MessageId, Consumer), inserted in the same EF Core transaction as the invoice, and a duplicate simply hit the unique constraint and was completed as a no-op; [duplicate invoices went from a handful a week to zero]. For external side effects I pass an idempotency key, such as Stripe's
Idempotency-Key, so the provider dedups too."
| Guarantee | How you get it | Failure behaviour | Use for |
|---|---|---|---|
| At-most-once | Ack before processing; receive-and-delete; fire-and-forget send | Loss on crash | Telemetry, cache invalidation hints |
| At-least-once | Ack after processing; producer retries | Duplicates on crash, timeout, lock expiry | Everything business-critical |
| Exactly-once (end to end) | Not achievable across independent systems | n/a | Use effectively-once instead |
Producer Broker Consumer DB
|--send m1---->| | |
| (ack lost) | | |
|--retry m1--->| (duplicate #1: producer retry) |
| |--m1 (lock 30s)----->| |
| | |--INSERT-------->| commit
| | X crash before Complete
| |--m1 again---------->| (duplicate #2: redelivery)
| Feature | Guarantees | Does not guarantee |
|---|---|---|
Kafka idempotent producer (EnableIdempotence) |
No duplicate writes from producer retries to a partition | Consumer-side duplicates |
Kafka transactions + read_committed |
Atomic consume-process-produce within Kafka | Writes to external databases or APIs |
| Service Bus duplicate detection | Drops a resend with the same MessageId inside the window |
Handler running twice after lock loss |
| SQS FIFO dedup | Drops a duplicate within 5 minutes by dedup id or content hash | Redelivery after visibility timeout |
| Technique | How | When |
|---|---|---|
| Natural idempotency | UPDATE ... SET Status = 'Paid' WHERE Id = @id; upsert by business key |
State-setting operations |
| Inbox / dedup table | Insert (MessageId, Consumer) with a unique key in the same transaction as the change | Increments, inserts, anything not naturally idempotent |
| Version check | Apply only if event.Version == current + 1 |
Ordered entity updates |
| Provider idempotency key | Pass a stable key to Stripe, email provider | External side effects |
A loyalty service credited points on OrderPaid. During a Service Bus throttling incident, handlers exceeded the 30-second lock, and about 0.4% of messages were processed twice, over-crediting roughly 3,100 customers. Adding an inbox table checked in the same transaction, plus lock renewal, brought duplicates to zero at a cost of one extra indexed insert (about 2 ms) per message.
Checks the candidate understands why duplicates are unavoidable and can design consumers that produce correct results anyway.
Green flags
Red flags
A consumer does two things: the work and the acknowledgement. They can't be atomic across two systems (your DB and the broker) without a distributed transaction. So one of them must happen first:
Ack first: [ack] ---- crash ---- [work] -> message lost (at-most-once)
Work first: [work] ---- crash ---- [ack] -> message redelivered (at-least-once)
There is no third ordering. That is the root of the "myth".
Two parties communicating over a lossy channel can't reach certain agreement that a message was received: every confirmation needs its own confirmation. A broker that hasn't heard "complete" can't know whether you processed the message. It must choose: redeliver (risking duplicates) or not (risking loss).
LockDuration (default 30 s, max 5 min). CompleteMessageAsync removes it; AbandonMessageAsync releases it and increments DeliveryCount; when DeliveryCount exceeds MaxDeliveryCount (default 10) it goes to the dead-letter queue.ServiceBusProcessor renews locks automatically up to MaxAutoLockRenewalDuration (default 5 min). A handler that runs longer than that loses the lock and the message is redelivered while the first run continues: a guaranteed duplicate.MessageIds; a send with a seen id inside the window is accepted and dropped. It must be enabled at creation time.SendOffsetsToTransaction), then commits. Consumers with IsolationLevel.ReadCommitted see only committed data.BEGIN TRAN
INSERT InboxMessages (MessageId, Consumer, ProcessedAt) -- unique key
UPDATE Accounts SET Points = Points + 50 WHERE Id = @id
COMMIT
Complete message
If the message is redelivered, the insert violates the unique key (SQL error 2627/2601), you roll back and complete the message. Two concurrent copies: one commits, the other blocks on the key and then fails. Clean up rows older than the maximum redelivery horizon (for example 14 days).
An email or a card charge can't join your SQL transaction. Options: pass a provider idempotency key derived from the message id; or write the intent to an outbox and let a single sender with its own dedup do the call. Accept that some providers only offer at-least-once and design the user experience around it ("you may receive this email twice").
LockDuration 30 s and MaxAutoLockRenewalDuration 0; watch the message arrive twice.ReceiveAndDelete, throw in the handler, and confirm the message is gone.MessageId 5 times, and count deliveries.Parallel.ForEachAsync and check the balance changed once.ReadCommitted consumer sees no duplicates in the output topic.An effectively-once Service Bus handler: the inbox row and the business change commit together, and a duplicate is completed as a no-op.
// LoyaltyHandler.cs
using Azure.Messaging.ServiceBus;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
namespace Loyalty;
public sealed record OrderPaid(Guid OrderId, Guid CustomerId, decimal Total);
public sealed class InboxMessage
{
public required string MessageId { get; init; }
public required string Consumer { get; init; }
public DateTimeOffset ProcessedAt { get; init; }
}
public sealed class LoyaltyHandler(LoyaltyDbContext db, ILogger<LoyaltyHandler> logger)
{
private const string ConsumerName = "loyalty-points";
public async Task HandleAsync(ProcessMessageEventArgs args)
{
var evt = args.Message.Body.ToObjectFromJson<OrderPaid>()!;
await using var tx = await db.Database.BeginTransactionAsync(args.CancellationToken);
try
{
db.Inbox.Add(new InboxMessage
{
MessageId = args.Message.MessageId,
Consumer = ConsumerName,
ProcessedAt = DateTimeOffset.UtcNow
});
// Not naturally idempotent (an increment), hence the inbox row.
await db.Customers.Where(c => c.Id == evt.CustomerId)
.ExecuteUpdateAsync(s => s.SetProperty(c => c.Points, c => c.Points + (int)evt.Total),
args.CancellationToken);
await db.SaveChangesAsync(args.CancellationToken);
await tx.CommitAsync(args.CancellationToken);
}
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
{
// Unique key on (MessageId, Consumer): we already processed this message.
await tx.RollbackAsync(args.CancellationToken);
logger.LogInformation("Duplicate {MessageId} ignored", args.Message.MessageId);
}
// Complete only after the commit (at-least-once). A crash before this line means redelivery,
// which the inbox turns into a no-op.
await args.CompleteMessageAsync(args.Message, args.CancellationToken);
}
}
// LoyaltyDbContext.cs (relevant mapping)
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<InboxMessage>(e =>
{
e.ToTable("InboxMessages");
e.HasKey(x => new { x.MessageId, x.Consumer }); // the dedup guarantee lives in the database
});
}
MessageId per send. Why it is wrong: producer retries get new ids, so neither duplicate detection nor an inbox can spot them. Instead: derive the id from the business event (order id plus event type).MaxAutoLockRenewalDuration, or move long work elsewhere.MessageId (the SDK's ServiceBusRetryOptions do this with backoff) and let dedup absorb the duplicate.MaxDeliveryCount as the backstop.I treat "exactly-once" as a property of the business outcome, not of delivery. The network will drop acks, brokers will fail over and pods will be killed mid-handler; the question is never "will the broker deliver once?" but "what happens if this handler runs twice?" For each consumer I want a one-line answer: naturally idempotent, inbox table, version check, or provider idempotency key.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Natural idempotency (set state, upsert) | Final-state updates | Design effort only | Increments, appends |
| Inbox table | Any DB-backed handler | One indexed insert per message (~1-3 ms), cleanup job | Side effects outside the DB |
| Broker dedup (Service Bus, SQS FIFO) | Cheap guard against producer retries | Throughput cost for long windows | As the only protection |
| Kafka transactions | Kafka-to-Kafka stream processing | Latency, complexity | Handler writes to SQL or APIs |
How I evaluate a strategy: (1) a test that delivers the same message twice concurrently and asserts one outcome; (2) a chaos run (kill pods, fail over the database with Azure Chaos Studio) followed by a reconciliation query that compares source and target counts; (3) production metrics: dedup hits per consumer, lock-lost errors and DLQ rate. A sudden rise in dedup hits usually points at lock expiry or a struggling dependency, long before anyone sees wrong data.
With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.
The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:
If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.
Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.
How to tell it (STAR)
**S:** Our loyalty service [at company] was crediting some customers twice after a database slowdown. **T:** I was asked to stop the duplicates and repair the balances. **A:** I grouped Application Insights traces by message id and found handlers running twice on different pods; lock renewal had been disabled, so slow handlers lost their lock. I re-enabled renewal as a stop-gap, then added an inbox table keyed on message id and consumer in the same transaction as the update, and scripted the corrections from the traces. **R:** Duplicate credits dropped to zero, [about 3,100] balances were corrected within a day, and the 'runs twice' test became part of our consumer template.
Last updated 23 Nov 2026.