Transactional outbox: the dual-write problem (DB commit and broker publish can't be atomic; distributed transactions aren't an option with Azure SQL and Service Bus), writing an OutboxMessages row in the same EF Core SaveChanges/transaction, a relay BackgroundService polling with UPDLOCK/READPAST, publishing with MessageId = outbox id, marking ProcessedAt, at-least-once delivery and consumer idempotency, ordering, CDC as an alternative, library options (MassTransit v9 commercial, NServiceBus, Wolverine, CAP), and operational costs.
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.
"The problem is the dual write. A checkout handler saves the order with
SaveChangesAsync, then callssender.SendMessageAsyncforOrderPlaced. If the process dies, the network blips or Service Bus throttles between those two calls, the order exists but nobody downstream hears about it: no payment, no fulfilment. Flip the order and you get the opposite: an event for an order that rolled back. You can't fix this with a distributed transaction: Azure SQL and Service Bus don't take part in one together, and you wouldn't want the coupling anyway.The outbox moves the publish into the database transaction. The handler adds the order and an
OutboxMessagerow (id, type, serialised payload,OccurredAt) to the sameDbContext, and oneSaveChangesAsynccommits both. Now 'order saved' and 'event recorded' are atomic. A separate relay, usually aBackgroundService, polls for rows whereProcessedAt IS NULL, publishes each one with the outbox id as the Service BusMessageId, and marks it processed. If I run more than one instance, the relay selects withUPDLOCK, READPAST, ROWLOCKso instances skip each other's rows. The honest bit is the guarantee: if the relay publishes and then crashes before marking the row, it publishes again. So it's at-least-once, never exactly-once, and every consumer needs to be idempotent with an inbox table. Service Bus duplicate detection on theMessageIdcatches resends within its window, but I treat that as a bonus, not the guarantee. For example, at [company] we [published events straight after SaveChanges], and [finance found [n] paid orders a month with no fulfilment]. I [introduced an outbox and an inbox on the consumers], and [the reconciliation gap went to zero].The mistake I see is underestimating the operational side: the table grows, so you need cleanup; a poison row can block ordered publishing, so you need attempt counts and alerts; and you need a metric for the age of the oldest unprocessed row. The outbox swaps 'sometimes lost' for 'occasionally duplicated', and that trade only works if consumers are idempotent."
| Failure point | Publish after commit | Publish before commit | Outbox |
|---|---|---|---|
| Crash between the two steps | Event lost | Ghost event | Relay publishes later |
| Broker unavailable | Request fails or event lost | Request fails | Rows wait; relay retries |
| DB commit fails | Nothing published (fine) | Ghost event | Nothing recorded (fine) |
| Relay crash after publish | n/a | n/a | Duplicate: consumers dedupe |
| Relay | Pros | Cons |
|---|---|---|
Polling BackgroundService |
Simple, all in .NET | Polling latency and load |
| Azure Function timer | Separate scaling | Another deployable |
| CDC (Debezium, SQL Server CDC) | Low latency, no polling queries | Extra infrastructure |
| Library (NServiceBus, MassTransit v9, Wolverine, CAP) | Built-in inbox/outbox, retries | Licence/dependency, less control |
After introducing an outbox in a checkout service handling about 30 orders a second, the relay polled every 500 ms in batches of 50; median publish delay was about 300 ms and p99 under 2 seconds. Over a quarter, monthly reconciliation found zero orders without a downstream OrderPlaced, compared with 20 to 40 a month before. The outbox table was purged of rows older than 7 days nightly, keeping it under 2 million rows.
Checks whether the candidate understands the dual-write problem, can implement an outbox correctly, and is precise about at-least-once delivery and operational costs.
Green flags
READPAST/leases) and ordering.Red flags
Handler SQL Server Service Bus
|-- SaveChanges() ------>| COMMIT
| |
X crash / timeout / throttling
|-- SendMessage() ------------------------------> (never sent)
=> order exists, OrderPlaced never published
There is no atomic commit across two independent resources without two-phase commit. Azure SQL Database doesn't support MSDTC-style distributed transactions with Service Bus, and Service Bus transactions only cover operations within Service Bus. So you make one system the source of truth (the database) and derive the publish from it.
Handler --SaveChanges (one tx)--> Orders row + OutboxMessages row
|
Relay (BackgroundService) <--- poll unprocessed rows (UPDLOCK, READPAST)
|-- SendMessageAsync(MessageId = outbox.Id) --> Service Bus topic
|-- set ProcessedAt, SaveChanges
|
Consumers (inbox: dedupe on MessageId) <----+
Options:
OutboxMessage alongside the aggregate.SaveChanges override or interceptor: aggregates raise events into a list; before saving, the context converts them to outbox rows. Keeps handlers clean and guarantees nothing is forgotten.Either way, it must be the same DbContext and transaction as the business change.
SELECT TOP (50) ... WITH (UPDLOCK, READPAST, ROWLOCK) WHERE ProcessedAt IS NULL ORDER BY OccurredAt inside a transaction, so concurrent relays skip locked rows rather than block.MessageId to the outbox id so Service Bus duplicate detection (enabled per queue/topic, window up to 7 days) drops resends within the window.ProcessedAt; on failure increment Attempts, store the error, and stop the batch if ordering matters.LockedUntil) instead of a long transaction.At-least-once: any crash between publish and mark causes a resend. Exactly-once delivery isn't achievable across these systems; what you get is exactly-once processing by combining at-least-once delivery with idempotent consumers (inbox).
Global ordering is expensive. Usually you need order per aggregate: publish in OccurredAt order, and use Service Bus sessions with SessionId = aggregate id so a consumer processes one order's events in sequence. A poison message then blocks only its session.
| Concern | Practice |
|---|---|
| Backlog | Metric: age of oldest unprocessed row; alert on threshold |
| Poison rows | Attempts column, max attempts, alert, manual replay tool |
| Growth | Nightly batched delete of processed rows older than N days |
| Indexing | Filtered index on OccurredAt WHERE ProcessedAt IS NULL |
| Latency | Polling interval vs load; or CDC; or signal the relay after commit |
NServiceBus (commercial) and MassTransit include outboxes; MassTransit v9 (current 9.2.x) is a commercial product licensed through Massient, while v8 remains Apache 2.0 with security patches committed through the end of 2026. Wolverine and DotNetCore.CAP are open-source alternatives with EF Core outbox support. A hand-written outbox is a few hundred lines and fine for one service; a library is worth it when many services need inbox, outbox, retries and sagas together.
SaveChangesAsync and kill the process between the two with a breakpoint; observe the lost event.OutboxMessages table and write it in the same SaveChangesAsync; repeat the experiment.READPAST and look for duplicates and blocking in Extended Events.MessageId.dotnet-counters while the broker is unreachable.Writing the outbox row in the same transaction, and a relay that publishes with MessageId = outbox id.
CREATE TABLE dbo.OutboxMessages (
Id uniqueidentifier NOT NULL PRIMARY KEY,
Type nvarchar(200) NOT NULL,
Payload nvarchar(max) NOT NULL,
OccurredAt datetimeoffset NOT NULL,
ProcessedAt datetimeoffset NULL,
Attempts int NOT NULL DEFAULT 0,
Error nvarchar(2000) NULL
);
-- Only unprocessed rows are polled, so keep that index tiny
CREATE INDEX IX_OutboxMessages_Unprocessed ON dbo.OutboxMessages (OccurredAt) WHERE ProcessedAt IS NULL;
namespace Orders.Infrastructure;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
public sealed class OutboxMessage
{
public Guid Id { get; init; } = Guid.CreateVersion7();
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; }
public static OutboxMessage From<T>(T @event, DateTimeOffset now) where T : notnull => new()
{
Type = typeof(T).Name,
Payload = JsonSerializer.Serialize(@event),
OccurredAt = now
};
}
public sealed record OrderPlaced(Guid OrderId, Guid CustomerId, decimal Total);
public sealed class PlaceOrderHandler(OrdersDbContext db, TimeProvider clock)
{
public async Task<Guid> HandleAsync(Guid customerId, decimal total, CancellationToken ct)
{
var order = new Order(customerId, total);
db.Orders.Add(order);
db.OutboxMessages.Add(OutboxMessage.From(new OrderPlaced(order.Id, customerId, total), clock.GetUtcNow()));
await db.SaveChangesAsync(ct); // order and event commit together, or neither does
return order.Id; // no broker call here: the relay publishes
}
}
namespace Orders.Infrastructure;
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;
public sealed class OutboxRelay(IServiceScopeFactory scopeFactory, ServiceBusSender sender, TimeProvider clock, ILogger<OutboxRelay> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(500));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try { await PublishBatchAsync(stoppingToken); }
catch (Exception ex) when (ex is not OperationCanceledException) { logger.LogError(ex, "Outbox relay batch failed"); }
}
}
private async Task PublishBatchAsync(CancellationToken ct)
{
await using var scope = scopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();
var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
db.ChangeTracker.Clear();
await using var tx = await db.Database.BeginTransactionAsync(ct);
// UPDLOCK + READPAST: another relay instance skips these rows instead of publishing them too
var batch = await db.OutboxMessages
.FromSql($"SELECT TOP (50) * FROM dbo.OutboxMessages WITH (UPDLOCK, READPAST, ROWLOCK) WHERE ProcessedAt IS NULL ORDER BY OccurredAt")
.ToListAsync(ct);
foreach (var message in batch)
{
try
{
await sender.SendMessageAsync(new ServiceBusMessage(BinaryData.FromString(message.Payload))
{
MessageId = message.Id.ToString(), // enables broker duplicate detection on resend
Subject = message.Type,
ContentType = "application/json"
}, ct);
message.ProcessedAt = clock.GetUtcNow();
}
catch (ServiceBusException ex)
{
message.Attempts++;
message.Error = ex.Message;
break; // keep ordering: stop at the first failure
}
}
await db.SaveChangesAsync(ct); // a crash before this line re-publishes the batch: at-least-once
await tx.CommitAsync(ct);
});
}
}
SaveChangesAsync. Why it is wrong: A crash or broker error between the two loses the event while the order exists. Instead: Write an outbox row in the same transaction and let a relay publish.UPDLOCK, READPAST, ROWLOCK in a transaction, or a lease column.DbContext or connection. Why it is wrong: It's a separate transaction, so the dual-write problem returns. Instead: Same context, same SaveChangesAsync.The outbox is the standard answer to dual writes, but the senior part is being precise about the guarantee and owning the operations. It converts "sometimes lost" into "occasionally duplicated", which is only a win if every consumer is idempotent, and it adds a component (the relay) that needs metrics, alerts and a replay tool like any other.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Publish after commit | Events that can be lost (cache hints) | Lost events | Money, orders, anything audited |
| Hand-written outbox + polling relay | One or a few services | Relay, cleanup, monitoring | Many services needing sagas too |
| Library outbox (NServiceBus, MassTransit v9, Wolverine, CAP) | Many services, inbox + sagas | Licence or dependency | Teams that need full control |
| CDC on the outbox table | Low latency, high volume | Debezium/CDC infrastructure | Small teams without that platform |
| Distributed transaction | Almost never in Azure | Not supported for Azure SQL + Service Bus | Cloud services |
I measure publish delay (commit to broker), oldest unprocessed age, rows over max attempts, and the monthly reconciliation between orders and downstream records, which is the real proof it works.
Ranked by severity:
OrderProcessor subscribes to a static event with a lambda, so every instance and its DbContext stay alive forever.MethodInfo.Invoke, so async handlers run fire-and-forget and their exceptions vanish.Status strings are set directly, so cancelled orders get processed; the event is published after SaveChanges with no outbox, so it can be lost.if/else on type × region.Patterns that help: Strategy (pricing by type, tax by region), a switch-table State for the lifecycle, an outbox instead of the mediator, and a singleton cache instead of the event. Overkill: MediatR, Chain of Responsibility, Visitor, and Stateless for five states.
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.
Unit of Work records every change made during one business operation and commits them together or not at all.
In EF Core, DbContext is the unit of work. The change tracker records added, modified and deleted entities. One SaveChangesAsync sends them all in a single implicit transaction. That's why every repository in a request must share the same scoped DbContext: separate contexts mean separate commits.
You need an explicit transaction (Database.BeginTransactionAsync) when one operation spans several SaveChanges calls, ExecuteUpdate/ExecuteDelete (which run immediately and skip the change tracker) or raw SQL. With EnableRetryOnFailure, wrap that transaction in CreateExecutionStrategy().ExecuteAsync, and make the block safe to re-run.
The trade-off: one context per request gives you atomic commits, but a long-lived context grows its change tracker and holds stale data.
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.
How to tell it (STAR)
**S:** At [company], finance kept finding [20–40] paid orders a month that were never fulfilled. **T:** I was asked to find the cause and make sure no order could be silently dropped. **A:** I matched the missing orders to Service Bus throttling and pod restarts between our database commit and the publish, a classic dual write. I introduced a transactional outbox written in the same `SaveChangesAsync`, a relay with row locking and `MessageId` set to the outbox id, and inbox deduplication on the consumers, plus alerts on outbox age. **R:** Reconciliation found zero unfulfilled paid orders for [the next two quarters], median publish delay was about [300 ms], and the backlog alert caught a Service Bus outage within [a minute].
Last updated 18 Nov 2026.