📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Implement an idempotent consumer (the inbox pattern) for Azure Service Bus messages in .NET 10: a dedup table with a unique key on message id and consumer, recording the message and applying the business change in one EF Core transaction, handling two copies of the same message arriving concurrently, and cleaning up old rows.

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.

Senior Coding Advanced azure-service-bus design-patterns ef-core idempotency inbox messaging

🎯 Key points

  • Duplicates are normal with at-least-once delivery: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries
  • Inbox table InboxMessages with primary key (MessageId, Consumer) so each consumer records each message once
  • Insert the inbox row and apply the business change in one transaction: both commit or neither, so a failure leaves the message retryable
  • Insert the inbox row first: a concurrent duplicate blocks on the key lock and then fails with SQL error 2627/2601 once the first commits; this works under the default READ COMMITTED (and RCSI) because uniqueness checks always take locks, so no SERIALIZABLE is needed
  • Catch DbUpdateException with SqlException Number 2627 or 2601 and treat it as 'already processed': complete the message, don't dead-letter it
  • With EnableRetryOnFailure, run the transaction in CreateExecutionStrategy().ExecuteAsync and use a fresh scope/DbContext per message
  • Complete the Service Bus message only after commit (AutoCompleteMessages = false); throw or abandon on real failures so it is redelivered
  • Purge inbox rows older than the maximum redelivery window (e.g. 7-14 days) in small batches from a job that logs and retries failures; natural idempotency (upsert by business key) can replace the table for simple cases

⏱ 30-second answer

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:

  1. Insert the inbox row first.
  2. Apply the business change.
  3. Commit, then complete the Service Bus message.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 InboxMessages table with a composite primary key on MessageId and Consumer, 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 catch DbUpdateException with that inner SqlException number 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 SELECT and 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."


Why duplicates happen

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

Check-then-act vs unique key

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can implement exactly-once processing correctly under concurrency and failure, not just describe deduplication.

Green flags

  • Explains where duplicates come from with Service Bus.
  • Uses a unique key, inserted first, in the same transaction as the business change.
  • Handles 2627/2601 as success and completes the message.
  • Completes after commit; scope per message; execution strategy.
  • Plans cleanup and knows when natural idempotency is enough.

Red flags

  • Check-then-insert without a unique constraint.
  • Separate transactions for dedup and work.
  • Relies only on broker duplicate detection.
  • Uses an in-memory HashSet of seen ids.

📚 Learn in depth

1. Exactly-once processing

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

2. Why insert first

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:

  • If the first commits, the second gets error 2627 (primary key violation) or 2601 (unique index violation) and knows the message was processed.
  • If the first rolls back, the key disappears and the second insert succeeds, so the message is processed once.

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.

3. Transaction boundaries

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.

4. Service Bus specifics

  • Use AutoCompleteMessages = false and complete after commit.
  • Throwing from the handler (or AbandonMessageAsync) makes the message available again after the lock is released; after MaxDeliveryCount (default 10) it is dead-lettered.
  • Long handlers: set 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.
  • Broker duplicate detection (per entity, time-window based) complements but doesn't replace the inbox.

5. Cleanup

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.

6. Natural idempotency

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.

7. External side effects

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.

Try it yourself

  1. Process the same message twice sequentially and assert one ledger row.
  2. Process two copies concurrently with Task.WhenAll against Testcontainers SQL Server; check one succeeds and the other hits 2627.
  3. Throw after SaveChangesAsync but before completing; confirm redelivery is absorbed.
  4. Set a 5-second lock duration and a 10-second handler; watch duplicates without the inbox.
  5. Write the purge job and measure it with Query Store on a million-row table.

💻 Code

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));
    }
}

⚠ Common mistakes

  • Mistake: Checking the inbox with a 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.
  • Mistake: Recording the inbox row in a different transaction from the business change. Why it is wrong: A crash between them either loses the change or processes it twice. Instead: One transaction for inbox row, business change and any outbox rows.
  • Mistake: Letting a duplicate-key exception bubble up. Why it is wrong: The message is retried until it's dead-lettered, raising false alarms. Instead: Catch 2627/2601 and complete the message as already processed.
  • Mistake: Completing the message before committing. Why it is wrong: A crash after completion but before commit loses the message. Instead: AutoCompleteMessages = false; complete after commit.
  • Mistake: Keying the inbox on 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).
  • Mistake: Using 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).
  • Mistake: Reusing one 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.
  • Mistake: Never purging the inbox. Why it is wrong: It grows forever and slows inserts and backups. Instead: Purge rows older than the maximum redelivery window.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says commands and messages must be safe to retry Why: Checks idempotency as a property of command handling
    How to answer

    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.

    • GoF style: the command has Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.
    • Modern style: an immutable record (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.

  2. When: Candidate discusses two instances processing related messages at once Why: Checks optimistic concurrency with rowversion as another way to resolve concurrent changes
    How to answer

    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:

    • A switch expression on (state, trigger): a compact, readable transition table; anything not listed is rejected.
    • State classes (IOrderState per state): worth it when each state has substantial behaviour of its own.
    • The Stateless library (5.20.1): 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.

  3. When: Candidate mentions duplicate charges caused by redelivery Why: Checks applying inbox and outbox in a real incident, including rollout order and data repair
    How to answer

    These are two bugs with different causes, so I quantify each with reconciliation queries first.

    • Lost messages: usually a dual write. The order is saved, then the publish fails or is never awaited (a fire-and-forget Task.Run killed on deploy, or a swallowed ServiceBusException).
    • Duplicates: usually publisher retries that create a new 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.

🛠 Real-world problems: how you handle them

Lock expiry during slow database calls doubled ledger credits
Situation
Billing service at [company] consuming `PaymentReceived` from a Service Bus subscription, about [200] messages a second at month-end peaks, crediting customer ledgers in Azure SQL. Handler had no deduplication.
Signals
Customers reported double credits; a reconciliation query found [~40] duplicate ledger entries a week with the same payment reference; Service Bus metrics showed messages with DeliveryCount > 1 and lock-lost exceptions in Application Insights during peaks.
Investigation
Application Insights showed handler durations of [70–90 s] during peaks (slow SQL from lock contention, confirmed in Query Store), longer than the 60-second lock with no auto-renewal. The lock expired, the message was redelivered to another instance, and both credited the ledger. Logs correlated duplicate entries to `MessageLockLostException`.
Resolution
Immediate: reversed the duplicate credits using payment references and set `MaxAutoLockRenewalDuration`. Real fix: an `InboxMessages` table keyed on `(MessageId, Consumer)`, inserted first in the same transaction as the ledger entry, duplicate-key errors treated as processed, completion only after commit, plus fixing the slow query with an index found in Query Store.
Prevention
Concurrency test with two handlers on Testcontainers SQL Server in CI; metric for duplicates detected per hour; alert on lock-lost exceptions and dead letters; nightly reconciliation of ledger entries vs payment references; inbox purge with [7]-day retention.

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.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me