An architecture walkthrough of a cross-service order flow in .NET: outbox publishing, inbox deduplication, a persisted saga orchestrator with compensations and timeouts, and a failure-point analysis covering crashes, duplicates, lost replies and poison messages.
Each service changes its own data and writes outgoing messages in one transaction (outbox), and dedups incoming messages (inbox). A saga orchestrator persists the order's progress: on OrderPlaced it sends ReserveStock; on StockReserved it sends CapturePayment; on PaymentCaptured it completes. If payment fails it sends the compensation ReleaseStock.
At every step a crash either committed nothing (the message is redelivered) or committed everything (the outbox resends). Duplicates hit the inbox. Missing replies trigger scheduled timeouts, and late replies after a timeout get their own handling, such as refunding a late capture. Poison messages dead-letter with alerts.
The trade-off: reliability without distributed transactions, paid for with eventual consistency, more states and more operational tooling.
"I'll walk the happy path first, then break it. The customer submits an order. Ordering saves the
Orderas Pending and anOrderPlacedoutbox row in one transaction, and returns 202 with the order id. The relay publishes to Service Bus. The saga orchestrator, which could live in Ordering or be its own service, consumes it, creates a saga instance keyed by order id in stateAwaitingStock, and in the same transaction writes aReserveStockcommand to its outbox plus a scheduled timeout. Inventory consumesReserveStock, records the message id in its inbox, reserves stock and writesStockReservedto its outbox, all in one transaction. The saga moves toAwaitingPaymentand sendsCapturePaymentwith an idempotency key of the order id. Payment calls the gateway, records the result and publishesPaymentCaptured; the saga marks the order Confirmed.Now the failures. If any service crashes before committing, nothing happened, the message wasn't completed, and Service Bus redelivers it. If it crashes after committing but before the relay sends, the outbox sends on restart. If the relay sends twice, the receiver's inbox drops the duplicate. If Payment declines, the saga sends
ReleaseStock, a compensation that is itself idempotent, and marks the order Rejected. If Payment never answers, the timeout fires and the saga moves to aPaymentUnknownstate and queries the gateway by idempotency key rather than guessing; if the capture turns up late, it either completes or refunds, depending on whether stock has already been released. For example, at [company] we [had exactly this late-capture case], and [adding an explicit state for it took unreconciled payments from N a month to zero].The mistake I see is designing only the happy path and calling it a saga. The value is in the state machine for the unhappy paths: every state needs an answer for duplicate, late and missing messages."
| Step | Failure | Outcome | Mechanism |
|---|---|---|---|
| Ordering saves order | Crash before commit | Nothing saved; client gets 5xx and retries with idempotency key | DB transaction, HTTP idempotency key |
Relay publishes OrderPlaced |
Crash after send, before marking | Sent twice | Saga inbox dedups by message id |
| Saga starts | Crash before commit | Message redelivered, saga created once | Unique saga key per order id, inbox |
| Inventory reserves | Out of stock | StockUnavailable -> order Rejected |
Saga transition |
| Inventory reserves | Crash after commit | StockReserved sent from outbox on restart |
Outbox |
| Payment capture | Declined | ReleaseStock compensation, order Rejected |
Compensation |
| Payment capture | No reply within timeout | Saga queries gateway by idempotency key | Scheduled message, idempotent gateway |
| Payment capture | Late success after compensation | Refund issued | Explicit late-reply handling |
| Any consumer | Throws repeatedly | Dead-lettered after MaxDeliveryCount |
DLQ alert, replay runbook |
| Orchestration (saga) | Choreography | |
|---|---|---|
| Flow visibility | One state machine | Spread across services |
| Coupling | Orchestrator knows participants | Services know each other's events |
| Timeouts and compensation | Centralised | Each service handles its own |
| Fits | 3+ steps, compensations, deadlines | 2-step, simple reactions |
A [ticketing] platform processing 25 orders per second at peak ran this flow on Azure Service Bus with MassTransit sagas persisted in Azure SQL. The end-to-end p95 from submit to confirmed was 1.4 s. During a 20-minute payment gateway outage, 3,100 sagas sat in PaymentUnknown, all resolved automatically by gateway queries once it recovered, with 42 refunds for captures that arrived after stock release and no manual data fixes.
Checks that the candidate can combine outbox, inbox and sagas into a coherent design and reason precisely about each failure point.
Green flags
Red flags
Client Ordering Saga (orchestrator) Inventory Payment
| POST /orders | | | |
|------------->| tx: Order(Pending) | | |
| 202 | + outbox OrderPlaced | |
|<-------------|---------------------->| tx: Saga(AwaitingStock) |
| | | + outbox ReserveStock + timeout |
| | |---------------------->| tx: inbox + |
| | | | reserve + outbox|
| | |<----- StockReserved --| |
| | | tx: AwaitingPayment + outbox CapturePayment
| | |----------------------------------------->|
| | |<--------------------- PaymentCaptured ---|
| |<-- OrderConfirmed ----| tx: Completed |
[AwaitingStock] --StockReserved--> [AwaitingPayment] --PaymentCaptured--> [Confirmed]
| | |
|--StockUnavailable--> [Rejected] | |--PaymentDeclined--> [Compensating] --StockReleased--> [Rejected]
|--Timeout--> [Rejected] |
|--Timeout--> [PaymentUnknown] --query gateway--> Captured? [Confirmed]
| NotFound? [Compensating]
|-- late PaymentCaptured after release --> [Refunding]
Every state defines what to do with every message, including ones that "shouldn't" arrive (ignore, log, or compensate).
ReserveStock(orderId) twice reserves once; payment uses the order id as the gateway idempotency key.ScheduleMessageAsync, or the saga library's scheduler.Other services saw the intermediate state: stock showed as reserved, a payment may have been authorised. Compensations are new business actions (ReleaseStock, RefundPayment) that must be idempotent and may themselves fail and retry. Some actions can't be compensated (an email sent), so order steps to put irreversible ones last.
Sagas table with state, version and data, plus the outbox and inbox. Viable for one or two flows.Propagate a correlation id (W3C trace context through Service Bus diagnostic properties) so Application Insights shows the whole flow as one transaction. Expose saga state via an admin query ("orders stuck in AwaitingPayment > 5 min") and alert on it.
StockReserved is still sent once.A hand-rolled saga state record and the transition handler, showing the transaction that updates saga state and writes the next command to the outbox.
namespace Ordering.Saga;
public enum OrderSagaState { AwaitingStock, AwaitingPayment, PaymentUnknown, Compensating, Confirmed, Rejected, Refunding }
public sealed class OrderSaga
{
public Guid OrderId { get; init; } // saga key, unique
public OrderSagaState State { get; set; }
public byte[] RowVersion { get; set; } = []; // optimistic concurrency on transitions
public DateTimeOffset UpdatedAt { get; set; }
}
public sealed record StockReserved(Guid OrderId);
public sealed record PaymentDeclined(Guid OrderId, string Reason);
public sealed record PaymentCaptured(Guid OrderId, string GatewayReference);
public sealed record CapturePayment(Guid OrderId, decimal Amount, string IdempotencyKey);
public sealed record ReleaseStock(Guid OrderId);
public sealed record RefundPayment(Guid OrderId, string GatewayReference);
namespace Ordering.Saga;
using Microsoft.EntityFrameworkCore;
public sealed class OrderSagaHandler(SagaDbContext db, IOutbox outbox, TimeProvider clock)
{
// Called by the consumer after the inbox check, inside one transaction (SaveChanges at the end).
public async Task HandleAsync(StockReserved msg, decimal amount, CancellationToken ct)
{
var saga = await db.Sagas.SingleAsync(s => s.OrderId == msg.OrderId, ct);
if (saga.State != OrderSagaState.AwaitingStock) return; // duplicate or late: already moved on
saga.State = OrderSagaState.AwaitingPayment;
saga.UpdatedAt = clock.GetUtcNow();
outbox.Enqueue(new CapturePayment(msg.OrderId, amount, IdempotencyKey: msg.OrderId.ToString()));
outbox.Schedule(new PaymentTimeout(msg.OrderId), clock.GetUtcNow().AddMinutes(2));
await db.SaveChangesAsync(ct); // state + outbox rows commit together; RowVersion guards races
}
public async Task HandleAsync(PaymentDeclined msg, CancellationToken ct)
{
var saga = await db.Sagas.SingleAsync(s => s.OrderId == msg.OrderId, ct);
if (saga.State is not (OrderSagaState.AwaitingPayment or OrderSagaState.PaymentUnknown)) return;
saga.State = OrderSagaState.Compensating;
outbox.Enqueue(new ReleaseStock(msg.OrderId)); // compensation: idempotent in Inventory
await db.SaveChangesAsync(ct);
}
public async Task HandleAsync(PaymentCaptured msg, CancellationToken ct)
{
var saga = await db.Sagas.SingleAsync(s => s.OrderId == msg.OrderId, ct);
switch (saga.State)
{
case OrderSagaState.AwaitingPayment or OrderSagaState.PaymentUnknown:
saga.State = OrderSagaState.Confirmed;
outbox.Enqueue(new OrderConfirmed(msg.OrderId));
break;
case OrderSagaState.Compensating or OrderSagaState.Rejected:
saga.State = OrderSagaState.Refunding; // late capture after we gave up: refund it
outbox.Enqueue(new RefundPayment(msg.OrderId, msg.GatewayReference));
break;
default:
return; // duplicate
}
await db.SaveChangesAsync(ct);
}
}
public sealed record PaymentTimeout(Guid OrderId);
public sealed record OrderConfirmed(Guid OrderId);
public interface IOutbox
{
void Enqueue<T>(T message) where T : notnull;
void Schedule<T>(T message, DateTimeOffset deliverAt) where T : notnull;
}
PaymentUnknown state that queries by idempotency key, plus refund on late success.The senior point is that reliability comes from the combination, not any one pattern: outbox for publishing, inbox for consuming, idempotent operations, a persisted state machine with explicit unhappy states, and observability. Leave out one and you get either lost messages, duplicates or stuck orders.
I also question whether the flow must be distributed at all. If Ordering and Inventory share a database inside a modular monolith, a local transaction covers that step and the saga shrinks to the genuinely remote step: payment. Fewer remote steps means fewer states.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Orchestrated saga (MassTransit/Wolverine/hand-rolled) | 3+ steps, compensations, deadlines | State machine, persistence, tooling | Two-step flows |
| Choreography with events | Simple reactions, few steps | Flow hard to see, scattered timeouts | Complex compensations |
| Durable Functions orchestration | Workflow-style processes on Azure | Platform coupling, replay semantics | Very high throughput, low latency |
| Local transaction (modular monolith) | Steps share a database | None | Steps genuinely in different services |
I'd measure end-to-end latency, the count of sagas per state over time, time-in-state p99, DLQ depth and compensation rate.
A saga replaces a distributed transaction with a sequence of local transactions, one per service, coordinated by messages. Each step has a compensating action that semantically undoes it: release the stock, refund the payment. Compensation isn't a rollback, because other parties may already have seen or acted on the intermediate state.
Design points: put the irreversible step last, make every step idempotent, add scheduled timeouts, and handle late replies (payment succeeds after a timeout cancelled the order, so refund it). The trade-off is availability and autonomy against eventual consistency and more complex failure handling.
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.
How to tell it (STAR)
**S:** During an on-sale at [company], our payment gateway degraded for [20 minutes] and [3,000+] order sagas stalled, with some customers charged but not ticketed. **T:** As [tech lead for ordering], I owned the recovery and the fix. **A:** I paused timeouts, replayed the DLQ once the gateway recovered, and reconciled settlements to issue refunds. Then I redesigned the timeout path with a `PaymentUnknown` state and a late-capture refund, documented in [an ADR], and added chaos tests. **R:** At the next outage [two months later], [all] stalled sagas resolved automatically with zero manual refunds and no customer complaints.
Last updated 23 Nov 2026.