Inbox / idempotent consumer in .NET 10: why at-least-once delivery (outbox resends, peek-lock redelivery, lock expiry) causes duplicates, an InboxMessages table with a composite primary key (MessageId, Consumer), inserting the inbox row first and applying the business change in the same EF Core transaction inside an execution strategy, treating SQL errors 2627/2601 as 'already processed', how the key lock serialises concurrent duplicates, completing vs abandoning Service Bus messages, retention-based cleanup with ExecuteDeleteAsync, natural idempotency as an alternative, and tests.
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.
"I start from the fact that the broker will give me the same message more than once. Service Bus peek-lock redelivers if my process crashes after processing but before
CompleteMessageAsync, or if the lock expires during a slow handler; an outbox relay resends if it dies before marking a row. So 'exactly once' has to be built by the consumer: at-least-once delivery plus idempotent processing.Some handlers are naturally idempotent: 'set order status to Shipped' or an upsert by business key can run twice harmlessly. Anything that adds, like crediting a ledger, sending an email or decrementing stock, isn't, and that's where the inbox comes in. I keep an
InboxMessagestable with a composite primary key onMessageIdandConsumer, so two different consumers of the same event each process it once. For each message I open a scope, start a transaction inside the execution strategy, insert the inbox row first, apply the business change,SaveChangesAsync, commit, and only then complete the message. Doing it in one transaction is the important part: if the business change fails, the inbox row rolls back too, and the redelivered message is processed properly. Inserting first matters for concurrency. If two copies arrive at the same moment on two instances, the second insert blocks on the key lock until the first transaction commits, then fails with SQL error 2627. I catchDbUpdateExceptionwith that innerSqlExceptionnumber and treat it as 'already done', so I complete the message rather than let it go to the dead-letter queue. If the first transaction rolled back instead, the second insert succeeds and processes normally. That works at the default isolation level; I don't need SERIALIZABLE.For example, at [company] we [had a payment-received consumer that credited a ledger], and [lock expiries during slow database calls doubled about [n] credits a week]. I [added the inbox table and moved the credit into the same transaction], and [duplicate credits went to zero]. The mistake I see is checking 'have I seen this id?' with a
SELECTand then processing: two concurrent copies both see 'no'. The unique key does the deduplication; everything else is just making sure the inbox row and the business change commit together."
| Source | Mechanism |
|---|---|
| Outbox relay | Crash after publish, before marking ProcessedAt |
| Peek-lock redelivery | Crash or exception after processing, before CompleteMessageAsync |
| Lock expiry | Handler runs longer than the lock duration (default 1 minute; renewable) |
| Publisher retry | Timeout on send that actually succeeded |
| Approach | Concurrent duplicate | Correct? |
|---|---|---|
SELECT inbox, then process, then insert |
Both see "not processed" | No |
| Process, then insert inbox (same tx) | Both process; one fails at commit and rolls back | Yes, but wasted work and possible deadlocks |
| Insert inbox first (same tx) | Second blocks, then gets 2627 | Yes, recommended |
| Separate transactions for inbox and work | Crash between them loses or duplicates work | No |
A ledger consumer averaging about 30 payment messages a second (200 a second at month-end peaks) saw roughly 40 duplicate credits a week, caused by lock expiry during slow database calls. After adding the inbox (one extra insert, about 1 ms per message) and lock auto-renewal, duplicate credits dropped to zero. With 14-day retention the inbox held about 36 million narrow rows, purged nightly in batches of 5,000 in a few minutes.
Checks whether the candidate can implement exactly-once processing correctly under concurrency and failure, not just describe deduplication.
Green flags
Red flags
HashSet of seen ids.Distributed systems give you at-least-once or at-most-once delivery. Exactly-once effect comes from at-least-once delivery plus idempotent processing. The inbox (also called idempotent receiver, Hohpe and Woolf's Enterprise Integration Patterns) is the general mechanism.
Service Bus (peek-lock) --> Consumer instance A --\
\--> Consumer instance B ---+--> BEGIN TRAN
INSERT InboxMessages(MessageId, Consumer) <-- key lock
apply business change
COMMIT
--> CompleteMessageAsync
SQL Server takes an exclusive key lock on the inserted primary key value, and uniqueness checks take locks even under READ COMMITTED SNAPSHOT. A second transaction inserting the same key waits for that lock:
This turns the database's uniqueness guarantee into a distributed lock scoped to one message, with no separate lock service and no need for SERIALIZABLE.
The inbox row, the business change and (if the handler publishes events) outbox rows must be in one transaction. Then:
| Crash point | Result on redelivery |
|---|---|
| Before commit | Nothing committed; processed normally |
After commit, before Complete |
Insert fails with 2627; message completed |
After Complete |
No redelivery |
Keep the transaction short: claim, change, commit. Long transactions holding the inbox key lock make duplicates wait and raise deadlock risk with other writers.
AutoCompleteMessages = false and complete after commit.AbandonMessageAsync) makes the message available again after the lock is released; after MaxDeliveryCount (default 10) it is dead-lettered.MaxAutoLockRenewalDuration so the lock is renewed, but keep handlers short.MessageId is set by the publisher; with the outbox it's the outbox id, which is stable across resends. Don't use SequenceNumber, which changes per enqueue.The inbox only needs rows as long as a duplicate could still arrive: the outbox retry period plus Service Bus TTL and redelivery time. Purge older rows from a scheduled job in small batches (for example DELETE TOP (5000) ... WHERE ProcessedAt < @cutoff in a loop) so each delete holds locks briefly and doesn't bloat the transaction log; log and retry failed batches rather than letting the job crash the service.
If the business change can be expressed as an upsert or state transition by business key (UPDATE Orders SET Status = 'Shipped' WHERE Id = @id AND Status = 'Packed'), you may not need an inbox. It's cheaper but only works for operations that are idempotent by nature; side effects like emails and ledger credits aren't.
An email or HTTP call can't join the database transaction. Options: record the intent in the outbox and send from a relay; pass an idempotency key to the external API (many payment APIs accept one); or accept rare duplicates for low-stakes side effects.
Task.WhenAll against Testcontainers SQL Server; check one succeeds and the other hits 2627.SaveChangesAsync but before completing; confirm redelivery is absorbed.The inbox table, a Service Bus processor that completes only after commit, and tests for sequential and concurrent duplicates.
CREATE TABLE dbo.InboxMessages (
MessageId nvarchar(128) NOT NULL,
Consumer nvarchar(200) NOT NULL,
ProcessedAt datetimeoffset NOT NULL,
CONSTRAINT PK_InboxMessages PRIMARY KEY (MessageId, Consumer) -- the key does the deduplication
);
CREATE INDEX IX_InboxMessages_ProcessedAt ON dbo.InboxMessages (ProcessedAt); -- for the purge job
namespace Billing.Infrastructure;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public sealed class InboxMessage
{
public required string MessageId { get; init; }
public required string Consumer { get; init; }
public DateTimeOffset ProcessedAt { get; init; }
}
public sealed class LedgerEntry
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public Guid AccountId { get; init; }
public decimal Amount { get; init; }
public required string Reference { get; init; }
}
public sealed record PaymentReceived(Guid AccountId, decimal Amount, string PaymentReference);
public sealed class BillingDbContext(DbContextOptions<BillingDbContext> options) : DbContext(options)
{
public DbSet<InboxMessage> Inbox => Set<InboxMessage>();
public DbSet<LedgerEntry> Ledger => Set<LedgerEntry>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<InboxMessage>(e => { e.ToTable("InboxMessages"); e.HasKey(x => new { x.MessageId, x.Consumer }); });
b.Entity<LedgerEntry>().Property(x => x.Amount).HasPrecision(18, 2);
}
}
public enum InboxResult { Processed, Duplicate }
// Not naturally idempotent (it adds money), so it needs the inbox
public sealed class PaymentReceivedHandler(BillingDbContext db, TimeProvider clock)
{
public const string ConsumerName = "billing.payment-received";
public async Task<InboxResult> HandleAsync(string messageId, PaymentReceived message, CancellationToken ct)
{
var strategy = db.Database.CreateExecutionStrategy();
try
{
await strategy.ExecuteAsync(async () =>
{
db.ChangeTracker.Clear(); // the block may re-run
await using var tx = await db.Database.BeginTransactionAsync(ct);
// 1. Claim the message first: a concurrent duplicate now blocks on this key
db.Inbox.Add(new InboxMessage { MessageId = messageId, Consumer = ConsumerName, ProcessedAt = clock.GetUtcNow() });
await db.SaveChangesAsync(ct);
// 2. The business change, in the same transaction
db.Ledger.Add(new LedgerEntry { AccountId = message.AccountId, Amount = message.Amount, Reference = message.PaymentReference });
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
});
return InboxResult.Processed;
}
catch (DbUpdateException ex) when (ex.InnerException is SqlException { Number: 2627 or 2601 })
{
return InboxResult.Duplicate; // already processed: safe to complete
}
}
}
namespace Billing.Infrastructure;
using Azure.Messaging.ServiceBus;
public sealed class PaymentReceivedConsumer(ServiceBusClient client, IServiceScopeFactory scopeFactory, ILogger<PaymentReceivedConsumer> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await using var processor = client.CreateProcessor("payments", "billing", new ServiceBusProcessorOptions
{
AutoCompleteMessages = false, // complete only after commit
MaxConcurrentCalls = 16,
MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(5)
});
processor.ProcessMessageAsync += async args =>
{
await using var scope = scopeFactory.CreateAsyncScope(); // fresh DbContext per message
var handler = scope.ServiceProvider.GetRequiredService<PaymentReceivedHandler>();
var payload = args.Message.Body.ToObjectFromJson<PaymentReceived>()!;
var result = await handler.HandleAsync(args.Message.MessageId, payload, args.CancellationToken);
if (result == InboxResult.Duplicate) logger.LogInformation("Duplicate message {MessageId} skipped", args.Message.MessageId);
await args.CompleteMessageAsync(args.Message, args.CancellationToken);
// Any exception before this line leaves the message to be redelivered (dead-lettered after MaxDeliveryCount)
};
processor.ProcessErrorAsync += args =>
{
logger.LogError(args.Exception, "Service Bus error on {Entity}", args.EntityPath);
return Task.CompletedTask;
};
await processor.StartProcessingAsync(stoppingToken);
try { await Task.Delay(Timeout.Infinite, stoppingToken); }
catch (OperationCanceledException) { }
await processor.StopProcessingAsync(CancellationToken.None);
}
}
// Cleanup: keep rows only as long as a duplicate could still arrive
public sealed class InboxPurgeJob(BillingDbContext db, TimeProvider clock)
{
public Task<int> PurgeAsync(TimeSpan retention, CancellationToken ct)
{
var cutoff = clock.GetUtcNow() - retention;
return db.Inbox.Where(m => m.ProcessedAt < cutoff).ExecuteDeleteAsync(ct); // run nightly; batch in SQL for very large tables
}
}
namespace Billing.Tests;
using Billing.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Testcontainers.MsSql;
public class InboxTests
{
[Fact]
public async Task Same_message_processed_twice_concurrently_credits_once()
{
var ct = CancellationToken.None;
await using var sql = new MsSqlBuilder().WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build();
await sql.StartAsync(ct);
var options = new DbContextOptionsBuilder<BillingDbContext>().UseSqlServer(sql.GetConnectionString()).Options;
await using (var setup = new BillingDbContext(options)) await setup.Database.EnsureCreatedAsync(ct);
var message = new PaymentReceived(Guid.NewGuid(), 125.50m, "PAY-1001");
async Task<InboxResult> RunAsync()
{
await using var db = new BillingDbContext(options); // separate context = separate consumer instance
return await new PaymentReceivedHandler(db, TimeProvider.System).HandleAsync("msg-1", message, ct);
}
var results = await Task.WhenAll(RunAsync(), RunAsync());
Assert.Contains(InboxResult.Processed, results);
Assert.Contains(InboxResult.Duplicate, results);
await using var check = new BillingDbContext(options);
Assert.Equal(1, await check.Ledger.CountAsync(ct));
}
}
SELECT before processing. Why it is wrong: Two concurrent copies both see "not processed" and both apply the change. Instead: Insert the inbox row and rely on the primary key to reject the duplicate.AutoCompleteMessages = false; complete after commit.MessageId alone when several consumers share a database. Why it is wrong: The first consumer's row makes the second consumer skip the message. Instead: Key on (MessageId, Consumer).SequenceNumber or a new GUID as the dedup key. Why it is wrong: They differ between resends of the same logical message. Instead: Use a publisher-assigned stable MessageId (the outbox id).DbContext across messages in the processor. Why it is wrong: DbContext isn't thread-safe, and the change tracker grows and goes stale. Instead: A new scope per message.I treat idempotency as a property of every consumer, decided per handler: if the operation is naturally idempotent (state transition or upsert by business key) I skip the table; if it accumulates or has side effects, it gets an inbox. The non-negotiables are a stable message id from the publisher, the inbox row and the business change in one transaction, and completing the message only after commit.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Natural idempotency (upsert/state transition) | Set-style updates | None | Credits, counters, emails |
| Inbox table, insert first | Accumulating changes | One insert per message, cleanup | Very high volume where natural idempotency works |
| Broker duplicate detection only | Bonus layer | Time-window limited | As the only guarantee |
| Library inbox (NServiceBus, MassTransit v9, Wolverine) | Many consumers, standardised | Licence/dependency | One or two consumers |
| Idempotency key to external API | Payments, third-party calls | Depends on the provider | Providers that don't support it |
I measure duplicates detected per hour (a useful health signal: a spike means something upstream is retrying), dead-letter counts, inbox table size, and a reconciliation of ledger entries against payment references.
Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.
The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.
The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.
Three implementations, from lightest:
(state, trigger): a compact, readable transition table; anything not listed is rejected.IOrderState per state): worth it when each state has substantial behaviour of its own.Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.
These are two bugs with different causes, so I quantify each with reconciliation queries first.
Task.Run killed on deploy, or a swallowed ServiceBusException).MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.
Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.
How to tell it (STAR)
**S:** At [company], our billing consumer was crediting about [40] payments a week twice, and customers were noticing. **T:** I owned billing and had to stop the duplicates and make the consumer safe regardless of redelivery. **A:** Application Insights and Query Store showed slow handlers outliving their Service Bus locks, so messages were redelivered mid-processing. I added an inbox table with a composite key, inserted first in the same transaction as the ledger credit, treated duplicate-key errors as success, completed messages only after commit, and fixed the slow query. **R:** Duplicate credits went to zero, handler p95 fell from [80 s] to [2 s], and the duplicate-detected metric now shows about [n] absorbed redeliveries a day that would each have been a support ticket.
Last updated 18 Nov 2026.