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.
These are two bugs with different causes, so I quantify each with reconciliation queries first.
Task.Run killed on deploy, or a swallowed ServiceBusException).MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.
Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.
"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 aServerBusyexception 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 theServiceBusMessageinside the retry loop with a new GUIDMessageIdeach 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
InboxMessagestable keyed onMessageIdand 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 aSaveChangesinterceptor writes toOutboxMessagesin the same transaction], plus a relay that publishes with the outbox id as theMessageId, 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], [republishedOrderPlacedfor 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."
| 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 |
| 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 |
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.
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
MessageId per retry, lock expiry).MessageId.Red flags
Reconciliation is both diagnosis and proof:
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.
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.
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.
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.
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.
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.
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.
MessageIds.SaveChangesInterceptor and test that an aggregate's events become outbox rows only when the save commits.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;
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.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.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.
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.
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.
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].
Last updated 18 Nov 2026.