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

📚 Interview question

Code review: a colleague's Service Bus message handler for OrderPaid calls a third-party shipping API to book a courier, saves a Shipment row with EF Core, and publishes a ShipmentBooked event, with no idempotency and auto-complete turned on. What problems do you find, how do you rank them, and how would you rewrite it?

Covers reviewing a message handler with side effects: duplicate courier bookings from at-least-once delivery, swallowed exceptions with auto-complete, the dual write between the database and the broker, missing idempotency keys, lost cancellation, blocking calls, logging gaps, and a rewrite using an inbox, outbox and provider idempotency key.

Senior CodeReview Advanced azure-service-bus code-review distributed-systems idempotency messaging outbox-pattern

🎯 Key points

  • Delivery is at-least-once: a redelivered OrderPaid books a second courier (real money)
  • Catch-all with auto-complete completes failed messages: silent loss
  • Dual write: SaveChanges then publish; a crash between them loses ShipmentBooked; there is no distributed transaction across Azure SQL and Service Bus, so use an outbox
  • Fix duplicates: local existence check, unique key on Shipment.OrderId, and a provider idempotency key derived from the order
  • Classify failures: transient throws for redelivery, permanent (400/422, bad body) dead-letters with a reason
  • Resilience: typed HttpClient from IHttpClientFactory with AddStandardResilienceHandler (timeouts, retries, circuit breaker); no new HttpClient or .Result
  • Throughput: the slow external call holds the message lock, so set lock renewal and concurrency against the courier's rate limits; outbox adds a few ms per message
  • Structured logging with MessageId and OrderId; tests that deliver the same message twice

⏱ 30-second answer

The worst problem is duplicates with real-world side effects. Service Bus is at-least-once, so a redelivered OrderPaid books a second courier. Next, a catch-all with auto-complete completes failed messages, so orders are silently never shipped. Then the dual write: SaveChanges followed by a publish loses ShipmentBooked if the process dies in between.

I rank by severity: money and customer harm, then lost data, then reliability, then diagnostics. The rewrite:

  • An idempotency key for the shipping API derived from the order id, plus a unique constraint on Shipment.OrderId (or an inbox row).
  • A transactional outbox for ShipmentBooked.
  • Explicit settlement: throw on transient errors, dead-letter permanent ones.
  • Cancellation tokens, a resilient typed HttpClient, structured logs, and a test that delivers the message twice.

The trade-off is more moving parts (outbox relay, cleanup) in exchange for correctness.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd rank the findings by what they cost the business. Number one: this handler isn't idempotent, and Service Bus delivery is at-least-once. If the courier booking succeeds but the pod dies before the message is completed, or the lock expires because the shipping API is slow, the message comes back and we book a second courier: real money and a confused customer. Number two: the try/catch logs and swallows every exception, and auto-complete is on, so when the shipping API returns a 503 the processor sees a normal return and completes the message; that order is never shipped and nobody knows until the customer complains. Number three: it saves the shipment and then publishes the event as two separate operations, so a crash between them leaves a shipment that nothing downstream ever hears about.

For example, at [company] I reviewed [a very similar handler] and [we found it had already booked about 40 duplicate couriers in a month during API slowdowns]. The rewrite I proposed: first check whether a shipment already exists for this order, and pass the order id as the shipping provider's idempotency key so a retry returns the original booking rather than creating another. Then save the shipment and an outbox row in one EF Core transaction, with a unique index on Shipment.OrderId as the last line of defence, and let the outbox relay publish ShipmentBooked. Then settle explicitly: transient failures throw so the broker redelivers, and permanent ones such as an invalid address dead-letter with a reason.

Lower down: .Result on the HTTP call blocks a thread, the cancellation token isn't passed, there's a new HttpClient() per message, and the logs don't carry the message id. The mistake I see in reviews is fixing only the try/catch; the duplicate booking is the expensive bug."


Code under review

public class OrderPaidHandler
{
    private readonly ShippingDbContext _db;           // // 1 scoped DbContext held by a singleton consumer
    private readonly ServiceBusSender _sender;
    public OrderPaidHandler(ShippingDbContext db, ServiceBusSender sender) { _db = db; _sender = sender; }

    // processor created with AutoCompleteMessages = true (default)    // // 2
    public async Task Handle(ProcessMessageEventArgs args)
    {
        try
        {
            var evt = JsonSerializer.Deserialize<OrderPaid>(args.Message.Body.ToString());
            var http = new HttpClient();                                   // // 3
            var resp = http.PostAsJsonAsync("https://api.courier.example/bookings",
                new { evt.OrderId, evt.Address }).Result;                  // // 4 blocking, no token, no idempotency key
            var booking = await resp.Content.ReadFromJsonAsync<Booking>(); // // 5 no status check

            _db.Shipments.Add(new Shipment { OrderId = evt.OrderId, TrackingNo = booking.TrackingNo });
            await _db.SaveChangesAsync();                                  // // 6 no dedup, no unique key

            await _sender.SendMessageAsync(new ServiceBusMessage(
                JsonSerializer.Serialize(new ShipmentBooked(evt.OrderId, booking.TrackingNo)))); // // 7 dual write, random MessageId
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);                                 // // 8 swallowed: auto-complete loses it
        }
    }
}

Findings, ranked by severity

# Severity Finding Consequence
6, 4 Critical (money) No idempotency: redelivery books another courier; no provider idempotency key Duplicate bookings, double charges from courier
8, 2 Critical (lost work) Catch-all + auto-complete completes failed messages Orders silently never shipped
7 High (data consistency) DB save and publish are separate; random MessageId Lost or phantom ShipmentBooked; consumers can't dedup
5 High No EnsureSuccessStatusCode; null booking on 4xx/5xx NullReferenceException, swallowed by 8
1 High Scoped DbContext captured by a long-lived handler; shared across concurrent calls Threading exceptions, stale tracking
3, 4 Medium (reliability) new HttpClient() per message, .Result, no timeout or token Socket exhaustion, thread starvation, hung shutdown
8 Medium (diagnostics) Console.WriteLine, no message id, no stack Can't trace failures
- Low (design) Handler mixes HTTP, persistence and publishing; no tests Hard to test duplicates

The rewrite

See the code example: inbox check plus unique key, provider idempotency key, outbox in the same transaction, explicit settlement, typed resilient HttpClient, scope per message, cancellation throughout.

How I'd close the review

  • Blocking: idempotency (key plus unique index), exception handling with explicit settlement, outbox (or at least a stable MessageId and a documented risk), status check on the HTTP response, scope per message.
  • Suggested: typed HttpClient with AddStandardResilienceHandler, structured logging scope, splitting booking from persistence.
  • Guard rails: enable analysers (CA2000, CA2016 for forwarding CancellationToken, VSTHRD002 for .Result), add a consumer template with these defaults, and a test that delivers the same message twice concurrently and asserts one booking.

Production example

In a handler like this, a shipping API slowdown (p95 from 300 ms to 28 s) caused lock expiry on about 3% of messages over one afternoon: 412 duplicate courier bookings at roughly $14 each, plus 97 orders silently completed after 503s. The rewrite brought both to zero; the outbox added about 4 ms per message.

🔍 What the interviewer is checking

Checks the candidate can spot correctness bugs in message handlers, rank them by business impact, and propose a sound rewrite.

Green flags

  • Leads with duplicate side effects from at-least-once delivery
  • Spots that auto-complete plus swallowed exceptions loses messages
  • Identifies the dual write and proposes an outbox
  • Uses a stable idempotency key and a unique constraint
  • Separates blocking from suggested review comments

Red flags

  • Focuses on style (var, naming) over correctness
  • Suggests a distributed transaction across SQL and Service Bus
  • Thinks retries alone fix the problem

📚 Learn in depth

1. Why side effects make idempotency non-negotiable

A database write can be deduplicated after the fact; a courier turning up twice can't. Any handler that calls an external system must assume it will run more than once for the same message.

Broker        Handler                 Courier API          DB
  |--m------->|--POST booking-------->| booked #1          |
  |           |   (28 s, lock expires)|                    |
  |--m again->| (other pod)--POST---->| booked #2 (dup!)   |
  |           |--SaveChanges---------------------------------> row

2. Idempotency at three layers

  1. Provider idempotency key: most payment and logistics APIs accept an Idempotency-Key header; the provider returns the original result for a repeated key within a window (often 24 hours). Derive it from the message (order-{OrderId}-booking), never a new GUID per attempt.
  2. Local check: "is there already a Shipment for this OrderId?" before calling out, to avoid unnecessary calls.
  3. Unique constraint: Shipment.OrderId unique, so even a race between two pods can't create two rows.

If the provider has no idempotency support, you need a reservation step: insert a Pending shipment row (unique on OrderId) before calling the API; a duplicate fails the insert and stops. Then update to Booked. A crash after the call but before the update leaves Pending rows that a reconciliation job checks against the provider.

3. The dual-write problem

SaveChanges OK  ->  crash  ->  SendMessage never happens   => downstream never hears
SendMessage OK  ->  crash  ->  SaveChanges never happens   => event for a shipment that doesn't exist

The transactional outbox writes the event as a row in the same transaction as the shipment; a relay (background service, or a library such as MassTransit's or Wolverine's outbox) publishes and marks it sent. Delivery from the outbox is at-least-once, so the event needs a stable MessageId (for example ShipmentBooked:{OrderId}) for downstream dedup and Service Bus duplicate detection.

4. Settlement with auto-complete

With AutoCompleteMessages = true, the processor completes after your handler returns, and abandons if it throws. Swallowing exceptions turns every failure into a completion. Either let exceptions propagate (keeping auto-complete), or turn it off and settle explicitly; both are fine if consistent.

5. Threading and lifetimes

A ServiceBusProcessor handler can run concurrently (MaxConcurrentCalls > 1). A DbContext isn't thread-safe and is designed to be short-lived; create a scope per message. HttpClient should come from IHttpClientFactory (typed client) to pool handlers and respect DNS changes, with AddStandardResilienceHandler() for timeouts, retries and a circuit breaker.

6. Testing the handler

  • Unit: fake shipping client; deliver the same message twice and assert one call with the same idempotency key and one shipment.
  • Integration: Testcontainers SQL Server, two concurrent handler invocations, assert unique-key protection.
  • Failure: shipping client throws HttpRequestException and assert the handler throws (message redelivered); invalid address 422 and assert dead-letter.

Try it yourself

  1. Run the original handler against a fake courier API that sleeps 40 s; with a 30 s lock, count bookings.
  2. Make the fake API return 503; confirm the original handler completes the message and loses the order.
  3. Apply the rewrite and repeat both experiments.
  4. Kill the process between SaveChanges and publish in the original; then with the outbox; compare.
  5. Turn on CA2016 and VSTHRD002 analysers on the original and see what they flag.

💻 Code

The rewrite: scope per message, idempotency at three layers, outbox for the event, explicit settlement.

// OrderPaidHandler.cs
using System.Net;
using System.Text.Json;
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;

namespace Shipping;

public sealed record OrderPaid(Guid OrderId, string Address);
public sealed record ShipmentBooked(Guid OrderId, string TrackingNo);

public sealed class OrderPaidHandler(
    ShippingDbContext db,                 // resolved from a per-message scope by the consumer
    ICourierClient courier,               // typed HttpClient with AddStandardResilienceHandler()
    ILogger<OrderPaidHandler> logger)
{
    public async Task HandleAsync(ProcessMessageEventArgs args)
    {
        var ct = args.CancellationToken;
        var evt = args.Message.Body.ToObjectFromJson<OrderPaid>();
        if (evt is null || string.IsNullOrWhiteSpace(evt.Address))
        {
            await args.DeadLetterMessageAsync(args.Message, "Invalid", "Missing order or address", ct);
            return;
        }

        using var _ = logger.BeginScope(new Dictionary<string, object>
        {
            ["MessageId"] = args.Message.MessageId, ["OrderId"] = evt.OrderId
        });

        // 1. Local check: already shipped? Then this is a duplicate; complete as a no-op.
        if (await db.Shipments.AnyAsync(s => s.OrderId == evt.OrderId, ct))
        {
            await args.CompleteMessageAsync(args.Message, ct);
            return;
        }

        // 2. Provider idempotency key: a retry returns the original booking, not a new one.
        Booking booking;
        try
        {
            booking = await courier.BookAsync(evt.OrderId, evt.Address,
                idempotencyKey: $"order-{evt.OrderId}-booking", ct);
        }
        catch (HttpRequestException ex) when (ex.StatusCode is HttpStatusCode.UnprocessableEntity)
        {
            await args.DeadLetterMessageAsync(args.Message, "CourierRejected", ex.Message, ct);
            return;
        }
        // Other exceptions (timeouts, 5xx after resilience retries) propagate: abandon and redeliver.

        // 3. Shipment and outbox row in one transaction; unique index on Shipment.OrderId backs it up.
        db.Shipments.Add(new Shipment { OrderId = evt.OrderId, TrackingNo = booking.TrackingNo });
        db.Outbox.Add(OutboxMessage.Create(
            messageId: $"ShipmentBooked:{evt.OrderId}",          // stable id for downstream dedup
            payload: new ShipmentBooked(evt.OrderId, booking.TrackingNo)));
        try
        {
            await db.SaveChangesAsync(ct);
        }
        catch (DbUpdateException ex) when (ex.IsUniqueViolation())
        {
            logger.LogInformation("Concurrent duplicate for order already stored");
        }

        await args.CompleteMessageAsync(args.Message, ct);       // after the commit
    }
}

public sealed record Booking(string TrackingNo);

public interface ICourierClient
{
    Task<Booking> BookAsync(Guid orderId, string address, string idempotencyKey, CancellationToken ct);
}

public sealed class OutboxMessage
{
    public required string MessageId { get; init; }
    public required string Type { get; init; }
    public required string Payload { get; init; }
    public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
    public DateTimeOffset? SentAt { get; set; }

    public static OutboxMessage Create<T>(string messageId, T payload) => new()
    {
        MessageId = messageId, Type = typeof(T).Name, Payload = JsonSerializer.Serialize(payload)
    };
}
// Program.cs (relevant registrations)
builder.Services.AddDbContext<ShippingDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Shipping")));
builder.Services.AddHttpClient<ICourierClient, CourierClient>(c =>
        c.BaseAddress = new Uri("https://api.courier.example/"))
    .AddStandardResilienceHandler();        // timeouts, retries with jitter, circuit breaker
builder.Services.AddScoped<OrderPaidHandler>();
builder.Services.AddHostedService<OutboxRelay>();      // publishes unsent outbox rows with their MessageId

⚠ Common mistakes

  • Mistake: Fixing the try/catch but leaving the handler non-idempotent. Why it is wrong: redelivery still books duplicate couriers. Instead: add a provider idempotency key and a unique constraint.
  • Mistake: Generating a new idempotency key per attempt. Why it is wrong: the provider sees each retry as a new request. Instead: derive the key from the message or order id.
  • Mistake: Publishing the event before saving. Why it is wrong: a crash announces a shipment that doesn't exist. Instead: use an outbox written in the same transaction.
  • Mistake: Wrapping the DB save and the Service Bus send in a TransactionScope. Why it is wrong: there is no distributed transaction across Azure SQL and Service Bus in .NET on Azure. Instead: use the outbox.
  • Mistake: Catch-all exception handling with auto-complete. Why it is wrong: failures are completed and lost. Instead: throw on transient, dead-letter on permanent.
  • Mistake: Treating every HTTP failure as permanent. Why it is wrong: a 503 dead-letters a valid order. Instead: only dead-letter on clearly permanent responses such as 400 or 422.
  • Mistake: Approving without a test for duplicate delivery. Why it is wrong: the bug reappears in the next change. Instead: require a twice-delivered-message test.

🏛 Senior insight: trade-offs

In a review like this, the senior skill is ranking and persuading. Seven findings presented flat get the easy ones fixed (new HttpClient) and the expensive one (duplicate bookings) argued away. I lead with business impact in the author's and product owner's terms ("this can book two couriers per order when the API is slow; last month that would have been about N bookings"), make two or three items blocking, and bring the fix, not just the complaint. Minor items go in as suggestions or a follow-up ticket so they don't hold up the critical fix.

Option When it fits Cost When not to
Provider idempotency key Provider supports it Nothing, just discipline Provider lacks it (use reservation row)
Reservation row before external call No provider idempotency Pending rows need reconciliation Cheap, harmless side effects
Transactional outbox Must publish after a DB change Relay, cleanup, at-least-once out, ~2-5 ms per message No event needed
Library outbox and inbox (MassTransit, Wolverine, NServiceBus) Many handlers Licence and abstraction One handler, simple needs

Resilience and throughput belong in the review too: the external call dominates handler time, so concurrency should respect the courier's rate limit, and the circuit breaker should stop the consumer hammering a failing API. Measure after the fix: duplicate-prevented counts (local check hits, unique violations, provider replays), DLQ reasons, handler p95 and outbox lag (oldest unsent row age).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes a transactional outbox for ShipmentBooked Why: Checks depth on the outbox relay, delivery guarantees and operating cost
    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 an inbox or dedup check Why: Checks they can implement the idempotent consumer correctly 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 discusses settlement and auto-complete Why: Checks they can write the consumer host correctly: concurrency, prefetch, lock renewal and shutdown
    How to answer

    I host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:

    • Complete after the database commit, which gives at-least-once delivery.
    • Abandon (or just throw) on transient errors so DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.
    • Dead-letter immediately on permanent errors such as an unparseable body, with a reason.

    MaxConcurrentCalls is sized to the downstream, PrefetchCount is kept small, and MaxAutoLockRenewalDuration is longer than the slowest handler. On shutdown I call StopProcessingAsync and honour args.CancellationToken. Because duplicates still happen, the handler is idempotent on MessageId. The trade-off: more concurrency means more throughput but more pressure on the database.

🛠 Real-world problems: how you handle them

Duplicate courier bookings during a shipping API slowdown
Situation
A fulfilment service for an [Australian online retailer] books couriers when `OrderPaid` arrives on a Service Bus subscription, about [15,000] orders a day across [3] pods. The courier API is a third party with per-booking fees.
Signals
Courier invoice [about $5,800] higher than expected; warehouse reports two couriers arriving for one parcel; customers asking why their order shows two tracking numbers; separately, [97] paid orders with no shipment at all.
Investigation
Joined courier booking records to orders: [412] orders with two bookings, all during a 3-hour window when the courier API p95 rose from 300 ms to 28 s; Application Insights showed the same `MessageId` handled on two pods after lock expiry; the missing shipments matched 503 responses swallowed by the catch-all with auto-complete on.
Resolution
Immediate: cancelled duplicate bookings with the courier, replayed the 97 orders. Then reviewed and rewrote the handler: provider idempotency key from the order id, local existence check, unique index on `Shipment.OrderId`, outbox for `ShipmentBooked`, explicit settlement, typed `HttpClient` with the standard resilience handler.
Prevention
Consumer template with explicit settlement and an idempotency checklist; tests delivering the same message twice and simulating 503s; analysers CA2016 and VSTHRD002 as errors; dashboards for duplicate-prevented counts and outbox lag.

How to tell it (STAR)

**S:** Our fulfilment service [at company] booked [412] duplicate couriers in one afternoon and silently dropped [97] orders. **T:** I was asked to review the handler and lead the fix. **A:** I showed that a slow courier API caused lock expiry and redelivery, so the non-idempotent handler booked twice, and that a catch-all with auto-complete was completing failed messages. I rewrote it with a provider idempotency key from the order id, a unique index on order id, an outbox for the event and explicit settlement, and added a twice-delivered test to the template. **R:** Duplicate bookings and lost orders both dropped to zero, we recovered [most of the $5,800] from the courier, and the template has been used for [six] consumers since.

More in Messaging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me