Saga pattern for a distributed order-payment flow: why there's no distributed transaction, orchestration (central state machine) vs choreography (services react to events), compensating actions as semantic undo (release stock, refund) rather than rollback, pivot transactions, MassTransit state machine with EF Core saga repository and optimistic concurrency (v9 commercial, v8 Apache 2.0), scheduled timeouts, idempotent steps, late replies after cancellation, observability, and alternatives (NServiceBus, Wolverine, Durable Functions).
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 starting point is that orders, stock and payments each own their own database, so there's no transaction spanning them, and two-phase commit isn't on the table in Azure. A saga gives up atomicity for a sequence of local transactions: create the order as Pending, reserve stock, charge payment, confirm the order. If a step fails, I run compensations for the steps already done: payment declined means release the stock and cancel the order. Compensations are new business operations, not rollbacks. Between steps the system is visibly inconsistent: the stock was reserved for a minute, and a customer may have got a 'we're processing your order' email. So I order the steps so the irreversible one, the pivot, comes last. Capturing payment is the pivot here, and everything after it, like confirming the order, must be retried until it succeeds.
For coordination I choose between choreography and orchestration. With choreography, stock listens for
OrderPlaced, payments listens forStockReserved, and so on. That's fine for two or three steps, but nobody owns the flow, so answering 'where is order 123 stuck?' means reading three services' logs. For anything with compensation and timeouts I prefer orchestration: a state machine with states like AwaitingStock and AwaitingPayment, persisted per order id. In .NET that's often a MassTransit saga state machine with an EF Core repository using optimistic concurrency, so two messages for the same order can't both update the state. MassTransit v9 is now a commercial product, so for a new service I'd check the licence budget against v8, which stays Apache 2.0 with patches through 2026, or alternatives like Wolverine, NServiceBus or Durable Functions. For example, at [company] we [had a choreographed checkout across [n] services], and [orders got stuck in Pending with no owner when the payment service timed out]. I [moved it to an orchestrated saga with a 10-minute payment timeout and explicit compensations], and [stuck orders dropped from about [n] a week to zero].The mistakes I see are around the edges: steps that aren't idempotent, so a redelivered
ChargePaymentcharges twice; no timeout, so a lost reply leaves the saga waiting forever; and no plan for the late reply, where payment succeeds just after the timeout cancelled the order, which needs an automatic refund. A saga is mostly a design for failure: every state needs an answer to 'what if the reply never comes, or comes twice, or comes late?'"
| Choreography | Orchestration | |
|---|---|---|
| Coordination | Services react to events | Central state machine sends commands |
| Flow visibility | Implicit, spread across services | Explicit in one place |
| Coupling | Services know each other's events | Services know only their commands; orchestrator knows the flow |
| Timeouts/compensation | Each service must handle its part | Orchestrator owns them |
| Testing | End-to-end only | State machine unit-testable |
| Fits | 2–3 steps, simple notifications | Multi-step flows with compensation |
| Step | Local transaction | Compensation |
|---|---|---|
| 1 | Orders: create order as Pending | Cancel order |
| 2 | Stock: reserve items | Release reservation |
| 3 (pivot) | Payments: capture payment | Refund (only if a later step can fail) |
| 4 | Orders: confirm order | None: retry until it succeeds |
| Case | Handling |
|---|---|
| Stock unavailable | Cancel order; nothing to compensate |
| Payment declined | Release stock, cancel order |
| No payment reply in 10 min | Scheduled timeout: release stock, cancel order |
| Payment succeeds after timeout cancelled | Late-reply handler issues a refund |
| Duplicate message | Idempotent steps + saga state ignores events in the wrong state |
| Two messages at once for one order | Optimistic concurrency on saga state; retry the loser |
Moving a choreographed checkout to an orchestrated saga cut orders stuck in Pending from around 60 a week to zero, because every state had a timeout. A late-reply rule refunded about 15 payments a month that succeeded after the 10-minute timeout, which previously had become manual finance tickets.
Checks whether the candidate can design a distributed workflow without distributed transactions, including compensation, coordination style and the awkward failure cases.
Green flags
Red flags
TransactionScope or 2PC across services.Garcia-Molina and Salem (1987) defined a saga as a long-lived transaction split into a sequence T1..Tn of sub-transactions, each with a compensating transaction C1..Cn. If Tk fails, run Ck-1..C1. In microservices each Ti is a local transaction in one service, and messages carry the flow.
ORCHESTRATION
+-------------------+
OrderPlaced -------> | Order saga (SM) | --ReserveStock--> Stock service
| state per OrderId| <-StockReserved--
| AwaitingStock | --ChargePayment-> Payment service
| AwaitingPayment | <-PaymentFailed--
| Cancelled | --ReleaseStock--> Stock service (compensation)
+-------------------+ --CancelOrder---> Orders service
CHOREOGRAPHY
Orders --OrderPlaced--> Stock --StockReserved--> Payments --PaymentFailed--> Stock (release)
\--> Orders (cancel)
A database rollback makes it as if the change never happened. A compensation is a new, visible business operation. Consequences:
Chris Richardson's classification: compensatable steps (before the pivot), the pivot (go/no-go point), and retryable steps after it, which must eventually succeed. Choosing the order is the main design decision.
The orchestrator stores per correlation id: current state, data needed for later steps (amount, items), timeout tokens, and a concurrency token. Two messages for the same saga arriving together must not both apply, so use optimistic concurrency (rowversion) and retry, or pessimistic row locks. MassTransit's EF Core saga repository supports both; store state transitions and outgoing messages atomically with the transactional outbox so a crash can't apply a transition without sending its commands.
Every waiting state gets a scheduled message (MassTransit Schedule, Service Bus scheduled messages, Durable Functions timers). When it fires, compensate. Then handle the reply arriving afterwards: in Cancelled, a PaymentSucceeded triggers RefundPayment.
Commands are delivered at least once. Each participant deduplicates (inbox, or idempotency keys passed to the payment provider), and the state machine ignores events that don't apply in the current state.
Correlate everything with the order id (OpenTelemetry trace context propagates through MassTransit and Service Bus). Query saga state for "orders in AwaitingPayment older than 15 minutes". Dashboards of counts per state reveal stuck flows.
| Option | Notes |
|---|---|
| MassTransit state machines | v9 commercial (Massient), 9.2.x current; v8 Apache 2.0, patched through end of 2026 |
| NServiceBus sagas | Commercial |
| Wolverine sagas | Open source, part of the Critter Stack |
| Azure Durable Functions / Durable Task | Code-as-orchestration, replay-based |
| Hand-rolled | A state table + consumer; fine for one flow, costly for many |
StockReserved twice and confirm only one ChargePayment is published.PaymentSucceeded after the timeout fires and assert a RefundPayment.An orchestrated order saga as a MassTransit state machine (the API is the same in v8 and v9; check the licence for v9), with compensation, a timeout and a late-reply refund.
namespace Orders.Saga;
using MassTransit;
// Messages (commands and events), correlated by OrderId
public sealed record OrderPlaced(Guid OrderId, decimal Total);
public sealed record ReserveStock(Guid OrderId);
public sealed record StockReserved(Guid OrderId);
public sealed record StockReservationFailed(Guid OrderId, string Reason);
public sealed record ChargePayment(Guid OrderId, decimal Amount);
public sealed record PaymentSucceeded(Guid OrderId, string PaymentReference);
public sealed record PaymentFailed(Guid OrderId, string Reason);
public sealed record PaymentTimedOut(Guid OrderId);
public sealed record ReleaseStock(Guid OrderId); // compensation
public sealed record RefundPayment(Guid OrderId, string PaymentReference);
public sealed record ConfirmOrder(Guid OrderId);
public sealed record CancelOrder(Guid OrderId, string Reason);
public sealed class OrderSagaState : SagaStateMachineInstance
{
public Guid CorrelationId { get; set; } // = OrderId
public string CurrentState { get; set; } = "";
public decimal Total { get; set; }
public Guid? PaymentTimeoutTokenId { get; set; }
public byte[]? RowVersion { get; set; } // optimistic concurrency
}
public sealed class OrderSaga : MassTransitStateMachine<OrderSagaState>
{
public State AwaitingStock { get; private set; } = null!;
public State AwaitingPayment { get; private set; } = null!;
public State Completed { get; private set; } = null!;
public State Cancelled { get; private set; } = null!;
public Event<OrderPlaced> Placed { get; private set; } = null!;
public Event<StockReserved> Reserved { get; private set; } = null!;
public Event<StockReservationFailed> ReservationFailed { get; private set; } = null!;
public Event<PaymentSucceeded> Paid { get; private set; } = null!;
public Event<PaymentFailed> PaymentDeclined { get; private set; } = null!;
public Schedule<OrderSagaState, PaymentTimedOut> PaymentTimeout { get; private set; } = null!;
public OrderSaga()
{
InstanceState(x => x.CurrentState);
Event(() => Placed, e => e.CorrelateById(m => m.Message.OrderId));
Event(() => Reserved, e => e.CorrelateById(m => m.Message.OrderId));
Event(() => ReservationFailed, e => e.CorrelateById(m => m.Message.OrderId));
Event(() => Paid, e => e.CorrelateById(m => m.Message.OrderId));
Event(() => PaymentDeclined, e => e.CorrelateById(m => m.Message.OrderId));
Schedule(() => PaymentTimeout, x => x.PaymentTimeoutTokenId, s =>
{
s.Delay = TimeSpan.FromMinutes(10);
s.Received = r => r.CorrelateById(m => m.Message.OrderId);
});
Initially(
When(Placed)
.Then(ctx => ctx.Saga.Total = ctx.Message.Total)
.Publish(ctx => new ReserveStock(ctx.Saga.CorrelationId))
.TransitionTo(AwaitingStock));
During(AwaitingStock,
When(Reserved)
.Publish(ctx => new ChargePayment(ctx.Saga.CorrelationId, ctx.Saga.Total)) // pivot step comes last
.Schedule(PaymentTimeout, ctx => new PaymentTimedOut(ctx.Saga.CorrelationId))
.TransitionTo(AwaitingPayment),
When(ReservationFailed)
.Publish(ctx => new CancelOrder(ctx.Saga.CorrelationId, ctx.Message.Reason))
.TransitionTo(Cancelled));
During(AwaitingPayment,
When(Paid)
.Unschedule(PaymentTimeout)
.Publish(ctx => new ConfirmOrder(ctx.Saga.CorrelationId)) // retryable step after the pivot
.TransitionTo(Completed),
When(PaymentDeclined)
.Unschedule(PaymentTimeout)
.Publish(ctx => new ReleaseStock(ctx.Saga.CorrelationId)) // compensate step 2
.Publish(ctx => new CancelOrder(ctx.Saga.CorrelationId, ctx.Message.Reason))
.TransitionTo(Cancelled),
When(PaymentTimeout.Received)
.Publish(ctx => new ReleaseStock(ctx.Saga.CorrelationId))
.Publish(ctx => new CancelOrder(ctx.Saga.CorrelationId, "Payment timed out"))
.TransitionTo(Cancelled));
// Late reply: payment captured after we gave up, so give the money back
During(Cancelled,
When(Paid).Publish(ctx => new RefundPayment(ctx.Saga.CorrelationId, ctx.Message.PaymentReference)),
Ignore(Reserved),
Ignore(PaymentDeclined));
// Duplicates in final states are no-ops
During(Completed, Ignore(Placed), Ignore(Reserved), Ignore(Paid));
}
}
namespace Orders.Saga;
using MassTransit;
using MassTransit.EntityFrameworkCoreIntegration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public sealed class OrderSagaStateMap : SagaClassMap<OrderSagaState>
{
protected override void Configure(EntityTypeBuilder<OrderSagaState> entity, ModelBuilder model)
{
entity.Property(x => x.CurrentState).HasMaxLength(64);
entity.Property(x => x.Total).HasPrecision(18, 2);
entity.Property(x => x.RowVersion).IsRowVersion();
}
}
public sealed class OrderSagaDbContext(DbContextOptions<OrderSagaDbContext> options) : SagaDbContext(options)
{
protected override IEnumerable<ISagaClassMap> Configurations => [new OrderSagaStateMap()];
}
// Program.cs
// builder.Services.AddDbContext<OrderSagaDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
// builder.Services.AddMassTransit(x =>
// {
// x.AddServiceBusMessageScheduler();
// x.AddSagaStateMachine<OrderSaga, OrderSagaState>()
// .EntityFrameworkRepository(r =>
// {
// r.ConcurrencyMode = ConcurrencyMode.Optimistic; // rowversion: concurrent messages for one order retry
// r.ExistingDbContext<OrderSagaDbContext>();
// r.UseSqlServer();
// });
// x.AddEntityFrameworkOutbox<OrderSagaDbContext>(o => { o.UseSqlServer(); o.UseBusOutbox(); }); // state + outgoing messages atomic
// x.UsingAzureServiceBus((context, cfg) =>
// {
// cfg.Host(builder.Configuration.GetConnectionString("ServiceBus"));
// cfg.UseServiceBusMessageScheduler();
// cfg.ConfigureEndpoints(context);
// });
// });
In production I'd Send commands to the owning service's queue rather than Publish them; Publish keeps the example short.
ChargePayment and charges twice. Instead: Inbox deduplication and idempotency keys with the payment provider.rowversion) or pessimistic locking, with retry.Sagas are the price of service autonomy. Before designing one I check whether the steps really need to be in different services; if the data can live in one database, a local transaction is simpler and stronger. When a saga is warranted, I design the state diagram first, with a timeout and late-reply rule for every waiting state, and only then pick the tool.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Single local transaction | Data in one service/database | None | Data genuinely owned by separate services |
| Choreography | 2–3 steps, no complex compensation | Implicit flow, hard tracing | Long flows with timeouts |
| Orchestration (MassTransit/NServiceBus/Wolverine) | Multi-step with compensation | Coordinator, licence (MassTransit v9, NServiceBus) | Trivial flows |
| Durable Functions/workflow engine | Long-running, human steps, timers | Platform coupling, replay rules | Low-latency request paths |
I measure sagas by count per state, age of the oldest instance in each waiting state, compensation rate and late-reply refunds. A rising compensation rate is often the first sign that a downstream service is degrading.
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.
The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.
Three implementations, from lightest:
(state, trigger): a compact, readable transition table; anything not listed is rejected.IOrderState per state): worth it when each state has substantial behaviour of its own.Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.
Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.
The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.
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.
How to tell it (STAR)
**S:** At [company], our choreographed checkout left about [60] orders a week stuck in Pending, with stock held and some customers charged. **T:** I led the redesign so every order reached a final state without manual work. **A:** Tracing stuck orders showed the payment service swallowing provider timeouts, and no service owned the wait. I moved the flow to an orchestrated MassTransit saga with an outbox, a 10-minute payment timeout, compensations for stock and the order, a refund rule for late payment replies, and idempotency keys on provider calls, plus a dashboard of instances per state. **R:** Stuck orders went to zero, about [15] late payments a month are refunded automatically instead of via finance tickets, and the dashboard flagged a payment provider degradation [20 minutes] before customers complained.
Last updated 18 Nov 2026.