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.
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:
Shipment.OrderId (or an inbox row).ShipmentBooked.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.
"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.OrderIdas the last line of defence, and let the outbox relay publishShipmentBooked. 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:
.Resulton the HTTP call blocks a thread, the cancellation token isn't passed, there's anew 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."
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
}
}
}
| # | 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 |
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.
MessageId and a documented risk), status check on the HTTP response, scope per message.HttpClient with AddStandardResilienceHandler, structured logging scope, splitting booking from persistence.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.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.
Checks the candidate can spot correctness bugs in message handlers, rank them by business impact, and propose a sound rewrite.
Green flags
Red flags
var, naming) over correctnessA 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
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.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.
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.
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.
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.
HttpRequestException and assert the handler throws (message redelivered); invalid address 422 and assert dead-letter.SaveChanges and publish in the original; then with the outbox; compare.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
TransactionScope. Why it is wrong: there is no distributed transaction across Azure SQL and Service Bus in .NET on Azure. Instead: use the outbox.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).
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.
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 host a ServiceBusProcessor in a BackgroundService, with ServiceBusClient as a singleton using DefaultAzureCredential. I set AutoCompleteMessages = false and settle explicitly:
DeliveryCount rises and the broker redelivers; after MaxDeliveryCount it dead-letters automatically.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.
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.
Last updated 23 Nov 2026.