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

📚 Interview question

What is the transactional outbox pattern? Explain the dual-write problem when an order is saved to SQL Server and an event published to Azure Service Bus, how to write the outbox row in the same EF Core transaction, how a relay publishes and marks messages, why delivery is at-least-once, and what the pattern costs to operate.

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.

Senior Theory Advanced azure-service-bus design-patterns distributed-systems ef-core messaging outbox

🎯 Key points

  • Dual-write problem: saving to the database and publishing to a broker are two systems; either can fail after the other succeeds (lost events or ghost events)
  • Outbox: write the event as a row in an OutboxMessages table in the same transaction as the business change, so both commit or neither does
  • A relay (BackgroundService, Azure Function or CDC) reads unprocessed rows, publishes them, then marks ProcessedAt
  • The outbox turns 'sometimes lost' into guaranteed at-least-once: a crash after publish but before marking resends, so consumers must be idempotent (inbox); set MessageId = outbox id for Service Bus duplicate detection
  • Concurrent relays use SELECT TOP (n) ... WITH (UPDLOCK, READPAST, ROWLOCK) or a lease column so they don't publish the same rows
  • Ordering: process in OccurredAt order per aggregate; use Service Bus sessions (SessionId = aggregate id) if consumers need order
  • Costs: an extra write per event, polling load/latency, table growth and cleanup, metrics for publish delay and oldest unprocessed row age, poison-row handling, and versioned payload schemas (Type + version) so stored rows stay readable after contract changes
  • Alternatives: CDC/Debezium reading the outbox table; libraries such as NServiceBus, MassTransit (v9 is commercial), Wolverine and CAP provide outboxes

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

🗣 Full answer (senior)

How I would answer this in an interview

"The problem is the dual write. A checkout handler saves the order with SaveChangesAsync, then calls sender.SendMessageAsync for OrderPlaced. 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 OutboxMessage row (id, type, serialised payload, OccurredAt) to the same DbContext, and one SaveChangesAsync commits both. Now 'order saved' and 'event recorded' are atomic. A separate relay, usually a BackgroundService, polls for rows where ProcessedAt IS NULL, publishes each one with the outbox id as the Service Bus MessageId, and marks it processed. If I run more than one instance, the relay selects with UPDLOCK, READPAST, ROWLOCK so 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 the MessageId catches 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 modes without and with an outbox

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 options

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains both failure orders of the dual write.
  • Writes the outbox row in the same transaction.
  • Says at-least-once and pairs it with idempotent consumers.
  • Handles concurrent relays (READPAST/leases) and ordering.
  • Talks about cleanup, monitoring and poison rows.

Red flags

  • "Wrap it in a TransactionScope" for SQL plus Service Bus.
  • Claims exactly-once delivery.
  • Publishes inside the transaction.
  • No idea how the relay is monitored.

📚 Learn in depth

1. The dual-write problem

  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.

2. Structure

  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) <----+

3. Writing the outbox row

Options:

  • Explicit: the handler adds OutboxMessage alongside the aggregate.
  • Domain events + 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.

4. The relay

  • Select a batch: 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.
  • Publish each message; set MessageId to the outbox id so Service Bus duplicate detection (enabled per queue/topic, window up to 7 days) drops resends within the window.
  • Mark ProcessedAt; on failure increment Attempts, store the error, and stop the batch if ordering matters.
  • Holding a database transaction while calling the broker keeps locks for the duration of the publish; keep batches small, or use a lease column (LockedUntil) instead of a long transaction.

5. Delivery semantics

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).

6. Ordering

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.

7. Operating it

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

8. Libraries (checked November 2026)

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.

Try it yourself

  1. Publish straight after SaveChangesAsync and kill the process between the two with a breakpoint; observe the lost event.
  2. Add an OutboxMessages table and write it in the same SaveChangesAsync; repeat the experiment.
  3. Run two relay instances with and without READPAST and look for duplicates and blocking in Extended Events.
  4. Enable duplicate detection on a Service Bus queue and resend a message with the same MessageId.
  5. Add a metric for the oldest unprocessed row age and watch it with dotnet-counters while the broker is unreachable.

💻 Code

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);
        });
    }
}

⚠ Common mistakes

  • Mistake: Publishing to the broker right after 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.
  • Mistake: Publishing inside the database transaction before commit. Why it is wrong: If the commit fails, consumers act on data that doesn't exist. Instead: Only the relay publishes, after commit, from committed rows.
  • Mistake: Claiming the outbox gives exactly-once delivery. Why it is wrong: A crash after publish but before marking resends the message. Instead: State at-least-once and make consumers idempotent with an inbox.
  • Mistake: Running several relay instances without row locking. Why it is wrong: Each publishes the same rows, multiplying duplicates. Instead: UPDLOCK, READPAST, ROWLOCK in a transaction, or a lease column.
  • Mistake: Writing the outbox row with a different DbContext or connection. Why it is wrong: It's a separate transaction, so the dual-write problem returns. Instead: Same context, same SaveChangesAsync.
  • Mistake: Never cleaning up the outbox table. Why it is wrong: It grows by millions of rows, slowing polling and backups. Instead: Batched deletes of processed rows older than a retention period, with a filtered index for unprocessed rows.
  • Mistake: No monitoring of the relay. Why it is wrong: A stopped relay silently delays every event. Instead: Alert on the age of the oldest unprocessed row and on rows over the max attempts.
  • Mistake: Relying on Service Bus duplicate detection as the idempotency guarantee. Why it is wrong: It only covers its time window and the same entity. Instead: Use it as a bonus on top of consumer-side deduplication.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes publishing straight after SaveChanges as a bug Why: Checks spotting a missing outbox during a code review
    How to answer

    Ranked by severity:

    • Memory leak: a scoped OrderProcessor subscribes to a static event with a lambda, so every instance and its DbContext stay alive forever.
    • Captive dependencies and lost errors: the home-made mediator resolves scoped handlers from the root provider and calls them with MethodInfo.Invoke, so async handlers run fire-and-forget and their exceptions vanish.
    • Wrong data: Status strings are set directly, so cancelled orders get processed; the event is published after SaveChanges with no outbox, so it can be lost.
    • Design: pricing is a growing 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.

  2. When: Candidate mentions the relay as a BackgroundService Why: Checks why fire-and-forget publishing loses work and how background services run safely
    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.

  3. When: Candidate says the outbox row is written in the same SaveChanges Why: Checks that the outbox row must share the unit of work's transaction
    How to answer

    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.

  4. When: Candidate says outbox delivery is at-least-once so consumers must dedupe Why: Checks building the idempotent consumer that at-least-once delivery requires
    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.

🛠 Real-world problems: how you handle them

Paid orders with no fulfilment after Service Bus throttling
Situation
Checkout service at [company] on Azure (Australia East), about [30] orders a second at peak, saving orders to Azure SQL then publishing `OrderPlaced` to a Service Bus topic consumed by payments and fulfilment.
Signals
Monthly finance reconciliation found [20–40] paid orders with no fulfilment record; Application Insights showed occasional `ServiceBusException` (ServerBusy) and a few pod restarts during deployments, but checkout requests mostly returned 200.
Investigation
Correlated the missing orders' timestamps with Application Insights: each matched a `ServiceBusException` or a pod termination straight after the SQL commit dependency. Code review confirmed `SaveChangesAsync` followed by `SendMessageAsync`, with the publish exception caught and logged. Service Bus metrics showed throttled requests at the same times.
Resolution
Immediate: a script republished `OrderPlaced` for the [n] affected orders after checking downstream state. Real fix: an `OutboxMessages` table written in the same `SaveChangesAsync`, a relay `BackgroundService` using `UPDLOCK, READPAST`, `MessageId` = outbox id with duplicate detection on the topic, and an inbox on the payment and fulfilment consumers to absorb resends.
Prevention
Metrics and alerts on oldest unprocessed outbox row (> [60 s]) and on rows over [10] attempts; nightly purge of processed rows older than [7] days; an architecture test banning `ServiceBusSender` usage outside the relay; the monthly reconciliation kept as a backstop.

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].

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me