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

📚 Interview question

Orders are saved in SQL Server, but finance reports that some OrderPlaced messages on Azure Service Bus never arrive, and others are processed twice, charging customers twice. How do you find the causes, and how do you fix them with the outbox and inbox patterns without losing or duplicating anything during the rollout?

Real-world messaging incident: finding lost events (publish after SaveChanges, fire-and-forget Task.Run, swallowed ServiceBusException) and duplicates (publisher retries with a new MessageId each time, peek-lock redelivery after lock expiry) with reconciliation queries, Application Insights correlation and Service Bus metrics; fixing with domain events written to an OutboxMessages table by a SaveChanges interceptor, a relay with UPDLOCK/READPAST and stable MessageId, duplicate detection, an InboxMessages table keyed on (MessageId, Consumer); rollout order (inbox first), backfill and refunds, and ongoing reconciliation.

Senior RealWorldScenario Advanced azure-service-bus design-patterns idempotency inbox incident-response outbox

🎯 Key points

  • Treat lost and duplicated messages as two separate bugs with different causes; quantify each with reconciliation queries first
  • Lost: publishing after SaveChanges (dual write), fire-and-forget Task.Run publishes killed on shutdown, or ServiceBusException caught and logged
  • Duplicates: publisher retries that generate a new MessageId per attempt (defeating duplicate detection), and peek-lock redelivery after lock expiry or a crash before CompleteMessageAsync on a non-idempotent consumer
  • Fix lost: domain events converted to OutboxMessages rows in the same SaveChanges (interceptor), relay with UPDLOCK/READPAST publishing MessageId = outbox id
  • Fix duplicates: InboxMessages with PK (MessageId, Consumer) inserted first in the consumer's transaction, 2627/2601 treated as processed, complete after commit; Service Bus duplicate detection as a bonus
  • Roll out the inbox on consumers before the outbox on publishers, because the outbox makes delivery at-least-once and introduces resends
  • Repair data: republish missing events from the outbox/orders (idempotent consumers absorb overlaps) and refund double charges by payment reference
  • Keep a daily reconciliation (orders vs downstream records, duplicate payment references) and alerts on outbox age and dead letters as the safety net

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd split it into two problems straight away, because 'lost' and 'duplicated' have different causes and I don't want one fix to hide the other. First I'd measure both. For lost messages: orders created in the last 30 days with no matching record in fulfilment or payments. For duplicates: payment references with more than one ledger entry. That gives me numbers, dates and specific order ids to trace. Then I'd take a few of each through Application Insights by operation id.

For example, at [company] the lost orders [lined up with deployments and Service Bus throttling]. The code saved the order, then published inside a Task.Run 'so checkout is faster', with exceptions logged and swallowed. A pod shutting down during a deploy killed those tasks, and a ServerBusy exception just logged. That's the dual-write problem with a fire-and-forget on top. The duplicates had two sources. The publisher retried sends on timeout, but it created the ServiceBusMessage inside the retry loop with a new GUID MessageId each time, so Service Bus duplicate detection couldn't recognise the resend. And the payment consumer sometimes ran longer than its 60-second lock during database contention, so the message was redelivered to another instance while the first was still charging. Neither side was idempotent.

The fix was an outbox and an inbox, rolled out in the right order. I [added an InboxMessages table keyed on MessageId and consumer to the payment and fulfilment consumers first], inserting the inbox row first in the same transaction as the charge and treating duplicate-key errors as already processed. That had to go first, because the outbox guarantees at-least-once delivery, so it introduces resends by design. Then I [replaced the publish with domain events that a SaveChanges interceptor writes to OutboxMessages in the same transaction], plus a relay that publishes with the outbox id as the MessageId, with duplicate detection on the topic. Then the clean-up, which I planned with finance and support: I [shared the exact list of affected orders and payment references], [republished OrderPlaced for the [n] missing orders from the outbox, which the inboxes made safe], and finance [refunded [n] double charges by payment reference] while support contacted the customers. [Over the next quarter, reconciliation found zero missing orders and zero double charges.] The order matters: make consumers idempotent before you make publishing reliable, and keep the reconciliation running as your proof."


Two problems, two sets of causes

Symptom Likely causes Evidence
Lost messages Publish after commit fails; fire-and-forget killed on shutdown; exception swallowed Missing orders cluster around deploys/throttling; ServiceBusException logs; no send dependency in the trace
Duplicates (publisher) Retry creates new MessageId; send timed out but succeeded Two messages, same payload, different MessageIds, seconds apart
Duplicates (consumer) Lock expiry or crash before Complete; no idempotency DeliveryCount > 1; MessageLockLostException; same MessageId processed twice

Rollout plan

Step Why this order
1. Reconciliation queries + dashboards Baseline and proof
2. Inbox on every consumer Makes resends harmless
3. Stable MessageId + duplicate detection Cheap extra protection
4. Outbox + relay on the publisher Stops losses (adds at-least-once resends, now absorbed)
5. Backfill missing events, refund duplicates (with finance and support) Repair historical data safely
6. Remove the old publish path; keep reconciliation Prevent regressions

Production example

Before the fix, monthly reconciliation found about 30 orders with no fulfilment and about 12 double charges. After rolling out inboxes and then the outbox, the inboxes absorbed roughly 150 redeliveries a week that would otherwise have been processed twice, and reconciliation found zero discrepancies for two consecutive quarters.

🔍 What the interviewer is checking

Checks whether the candidate can diagnose a real messaging incident with data, identify distinct causes, and apply outbox and inbox in a safe rollout order with data repair.

Green flags

  • Separates lost and duplicated messages and quantifies both.
  • Finds concrete causes (fire-and-forget, swallowed exceptions, new MessageId per retry, lock expiry).
  • Uses outbox and inbox correctly, with a stable MessageId.
  • Rolls out the inbox before the outbox and backfills safely.
  • Keeps reconciliation and alerts afterwards.

Red flags

  • "Turn on duplicate detection" as the whole fix.
  • Claims exactly-once delivery.
  • Backfills before consumers are idempotent.
  • No measurement before or after.

📚 Learn in depth

1. Measure before fixing

Reconciliation is both diagnosis and proof:

  • Missing: orders in the orders database with no corresponding fulfilment or payment record after N minutes.
  • Duplicated: ledger entries grouped by payment reference with COUNT(*) > 1; fulfilment jobs per order > 1.

Dates and ids from these queries let you trace specific messages through Application Insights (operation id), Service Bus metrics and logs.

2. Why messages go missing

 SaveChangesAsync()  --commit-->  SQL Server    (order exists)
 Task.Run(() => sender.SendMessageAsync(...))   <- not awaited; killed on pod shutdown,
                                                   or ServiceBusException logged and dropped

The dual-write problem plus fire-and-forget. ASP.NET Core doesn't track Task.Run work, so graceful shutdown doesn't wait for it.

3. Why messages are duplicated

Publisher side. If the ServiceBusMessage (and its MessageId) is created inside the retry loop, each attempt has a new id. A send that timed out on the client but succeeded on the broker is then resent as a "different" message, and duplicate detection can't help.

Consumer side. Peek-lock gives at-least-once delivery. Redelivery happens when the lock expires (default 60 s, renewable), when the handler throws after doing the work, or when the process dies before CompleteMessageAsync. A non-idempotent handler repeats its side effect.

4. The outbox, with domain events

Instead of handlers adding outbox rows by hand, aggregates raise domain events and a SaveChangesInterceptor converts them to OutboxMessages rows before the save. Every change that raises an event gets an outbox row automatically, in the same transaction. The relay (as in the outbox question) selects TOP (50) ... WITH (UPDLOCK, READPAST, ROWLOCK), publishes with MessageId = outbox.Id, and marks ProcessedAt.

5. The inbox

InboxMessages(MessageId, Consumer, ProcessedAt) with a composite primary key. Insert first, then apply the change, in one transaction; catch SQL errors 2627/2601 as "already processed" and complete the message; complete only after commit.

6. Why the inbox goes first

The outbox converts "sometimes lost" into "at least once". Turning it on before consumers are idempotent would trade lost orders for more double charges. Rolling out inboxes first makes every later step safe, including the backfill.

7. Repairing history

  • Missing events: generate outbox rows for affected orders (or republish via a one-off tool); idempotent consumers absorb any that were actually delivered.
  • Double charges: refund by payment reference after confirming with the payment provider; record refunds as their own events.
  • Communicate with finance and support with exact counts.

8. Keeping it fixed

Daily reconciliation jobs with alerts; metrics for outbox oldest-unprocessed age, rows over max attempts, inbox duplicates detected per hour (a spike signals upstream retries), dead-letter counts; an architecture test that bans ServiceBusSender outside the relay.

Try it yourself

  1. Write the two reconciliation queries against a test database seeded with missing and duplicate cases.
  2. Reproduce the publisher bug: create the message inside a Polly retry and simulate a timeout after a successful send; observe two MessageIds.
  3. Move message creation outside the retry and enable duplicate detection; repeat.
  4. Implement the SaveChangesInterceptor and test that an aggregate's events become outbox rows only when the save commits.
  5. Run the backfill twice against inbox-protected consumers and verify no duplicates.

💻 Code

The bugs, then domain events written to the outbox by an interceptor, and the reconciliation queries. The relay and inbox handler are the same as in the outbox and inbox questions.

// BEFORE: lost and duplicated messages
// await db.SaveChangesAsync(ct);
// _ = Task.Run(async () =>                                    // fire-and-forget: killed on shutdown
// {
//     try
//     {
//         await retryPipeline.ExecuteAsync(async token =>
//         {
//             var msg = new ServiceBusMessage(BinaryData.FromObjectAsJson(evt)) { MessageId = Guid.NewGuid().ToString() };
//             await sender.SendMessageAsync(msg, token);      // new MessageId per retry: duplicate detection can't help
//         });
//     }
//     catch (Exception ex) { logger.LogError(ex, "Publish failed"); }   // swallowed: event lost
// });
namespace Orders.Infrastructure;

using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public interface IDomainEvent;
public sealed record OrderPlaced(Guid OrderId, Guid CustomerId, decimal Total) : IDomainEvent;

public abstract class AggregateRoot
{
    private readonly List<IDomainEvent> _events = [];
    public IReadOnlyList<IDomainEvent> DomainEvents => _events;
    protected void Raise(IDomainEvent e) => _events.Add(e);
    public void ClearEvents() => _events.Clear();
}

// Same OutboxMessages table as the outbox question: Id, Type, Payload, OccurredAt, ProcessedAt, Attempts, Error
public sealed class OutboxMessage
{
    public Guid Id { get; init; } = Guid.CreateVersion7();     // becomes the Service Bus MessageId: stable across resends
    public required string Type { get; init; }
    public required string Payload { get; init; }
    public DateTimeOffset OccurredAt { get; init; }
    public DateTimeOffset? ProcessedAt { get; set; }
    public int Attempts { get; set; }
    public string? Error { get; set; }
}

// Every raised event becomes an outbox row in the same SaveChanges, so nothing can be forgotten or lost
public sealed class DomainEventsToOutboxInterceptor(TimeProvider clock) : SaveChangesInterceptor
{
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
    {
        if (eventData.Context is { } db)
        {
            var aggregates = db.ChangeTracker.Entries<AggregateRoot>()
                .Select(e => e.Entity)
                .Where(a => a.DomainEvents.Count > 0)
                .ToList();

            foreach (var aggregate in aggregates)
            {
                foreach (var e in aggregate.DomainEvents)
                {
                    db.Set<OutboxMessage>().Add(new OutboxMessage
                    {
                        Type = e.GetType().Name,
                        Payload = JsonSerializer.Serialize(e, e.GetType()),
                        OccurredAt = clock.GetUtcNow()
                    });
                }
                aggregate.ClearEvents();
            }
        }
        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }
}

// Program.cs
// builder.Services.AddSingleton(TimeProvider.System);
// builder.Services.AddSingleton<DomainEventsToOutboxInterceptor>();
// builder.Services.AddDbContext<OrdersDbContext>((sp, o) => o
//     .UseSqlServer(builder.Configuration.GetConnectionString("Orders"), sql => sql.EnableRetryOnFailure())
//     .AddInterceptors(sp.GetRequiredService<DomainEventsToOutboxInterceptor>()));
// builder.Services.AddHostedService<OutboxRelay>();          // UPDLOCK/READPAST batch, MessageId = outbox Id
-- Lost: orders older than 15 minutes with no outbox row for OrderPlaced (publisher side)
SELECT o.Id, o.CreatedAt
FROM dbo.Orders o
LEFT JOIN dbo.OutboxMessages m
       ON m.Type = 'OrderPlaced'
      AND JSON_VALUE(m.Payload, '$.OrderId') = CONVERT(nvarchar(36), o.Id)
WHERE o.CreatedAt < DATEADD(minute, -15, SYSDATETIMEOFFSET())
  AND m.Id IS NULL;

-- Stuck: outbox rows not published within 5 minutes
SELECT COUNT(*) AS Stuck, MIN(OccurredAt) AS Oldest
FROM dbo.OutboxMessages
WHERE ProcessedAt IS NULL AND OccurredAt < DATEADD(minute, -5, SYSDATETIMEOFFSET());

-- Duplicated: more than one ledger entry per payment reference (billing database)
SELECT Reference, COUNT(*) AS Entries, SUM(Amount) AS Total
FROM dbo.LedgerEntries
GROUP BY Reference
HAVING COUNT(*) > 1;

⚠ Common mistakes

  • Mistake: Treating lost and duplicated messages as one problem. Why it is wrong: They have different causes; one fix can make the other worse. Instead: Quantify and trace each separately.
  • Mistake: Publishing in a fire-and-forget Task.Run after saving. Why it is wrong: The task isn't tracked, so shutdown kills it and exceptions disappear. Instead: Write to an outbox in the same transaction.
  • Mistake: Creating the ServiceBusMessage inside the retry loop. Why it is wrong: Each attempt gets a new MessageId, so a successful-but-timed-out send is duplicated and duplicate detection can't help. Instead: Use a stable id (the outbox id) created once.
  • Mistake: Rolling out the outbox before consumers are idempotent. Why it is wrong: At-least-once delivery adds resends, increasing double charges. Instead: Inbox on consumers first, then the outbox.
  • Mistake: Relying on Service Bus duplicate detection alone. Why it is wrong: It's per entity and time-window limited, and doesn't help with consumer redelivery. Instead: Inbox deduplication on every consumer.
  • Mistake: Backfilling missing events into consumers that aren't idempotent. Why it is wrong: Some "missing" events were actually delivered; the backfill duplicates them. Instead: Backfill only after inboxes are live.
  • Mistake: Stopping reconciliation once the fix ships. Why it is wrong: Regressions (a new publish path, a schema change) return silently. Instead: Keep daily reconciliation with alerts.

🏛 Senior insight: trade-offs

The technical patterns are well known; what makes this senior is sequencing and proof. I measure both failure types first, fix consumers before publishers so every intermediate state is safe, repair historical data deliberately with finance, and leave reconciliation running permanently as the evidence that the system keeps its promises.

Option When it fits Cost When not to
Outbox via interceptor + domain events Rich aggregates raising events Interceptor, event plumbing Simple services where explicit outbox rows are clearer
Explicit outbox rows in handlers Few events, simple code Easy to forget in a new handler Many event-raising paths
Inbox per consumer Non-idempotent consumers (money, stock) One insert per message, cleanup Naturally idempotent handlers
Library (NServiceBus, MassTransit v9, Wolverine) Many services needing both Licence/dependency One or two services
Reconciliation jobs Always, for money and orders Queries and alerting Never skipped for financial flows

I measure missing and duplicated counts from reconciliation, outbox oldest-unprocessed age, inbox duplicates detected per hour, dead letters, and refunds issued; the incident is closed when reconciliation stays at zero for a full business cycle.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate introduces an outbox and relay Why: Checks the outbox relay design: locking, ordering, cleanup and monitoring
    How to answer

    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.

  2. When: Candidate adds deduplication to the payment consumer Why: Checks the inbox implementation under concurrency
    How to 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.

  3. When: Candidate finds the publish running in Task.Run Why: Checks the risks of fire-and-forget work in ASP.NET Core
    How to answer

    Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.

🛠 Real-world problems: how you handle them

Fire-and-forget publishes lost orders and retries double-charged customers
Situation
Order and payment services at [company] on AKS and Azure Service Bus, about [8,000] orders a day. The orders API saved orders and published `OrderPlaced` in a `Task.Run`; the payment consumer charged cards via the provider and wrote ledger entries.
Signals
Monthly finance reconciliation found [~30] orders with no fulfilment and [~12] customers charged twice; customer complaints about double charges; Application Insights showed `ServiceBusException` (ServerBusy) and `MessageLockLostException` entries, mostly logged at Warning and ignored.
Investigation
Reconciliation queries gave exact order ids and payment references. Missing orders clustered around deployments and throttling; their traces showed the SQL commit but no Service Bus send dependency. Duplicates had two patterns: pairs of messages with identical payloads and different `MessageId`s seconds apart (retry loop creating new messages), and same-`MessageId` messages with `DeliveryCount` 2 after handlers exceeded the 60 s lock during SQL contention (Query Store showed the slow query).
Resolution
Immediate: refunded double charges by payment reference and republished missing orders after checking downstream state. Real fix in order: inbox tables on payment and fulfilment consumers (insert first, 2627/2601 as processed, complete after commit, lock auto-renewal); stable `MessageId` and duplicate detection on the topic; domain events written to `OutboxMessages` by a `SaveChanges` interceptor with a relay using `UPDLOCK, READPAST`; removed the `Task.Run` publish; fixed the slow query.
Prevention
Daily reconciliation jobs with alerts on any discrepancy; metrics for outbox age, inbox duplicates per hour and dead letters; an architecture test banning `ServiceBusSender` outside the relay; Testcontainers tests for concurrent duplicates; a runbook for safe backfills.

How to tell it (STAR)

**S:** At [company], finance found about [30] orders a month never fulfilled and [12] customers charged twice. **T:** I was asked to find both causes and fix them without making either worse. **A:** Reconciliation queries and traces showed lost events from a fire-and-forget publish after save, and duplicates from a retry loop that generated new message ids plus consumer lock expiries. I rolled out inbox deduplication on consumers first, then stable message ids and an outbox written by a `SaveChanges` interceptor, then backfilled missing events and refunded duplicates with finance. **R:** The inboxes now absorb about [150] redeliveries a week, and reconciliation has shown zero missing or double-charged orders for [two quarters].

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me