Choosing a consistency mechanism for a multi-step process: when to keep data in one service and one transaction, when an outbox with idempotent consumers and eventual consistency is enough, and when a saga (orchestrated or choreographed) with compensations and timeouts is needed, plus reservations, the UX of pending states and the operating cost.
I start with the invariants. If something must be true at every instant (a balance never negative, a seat never double-booked), that data belongs in one aggregate, one service and one local transaction. Often the right answer is to redraw the boundary.
If other services only need to react and their effects never need undoing (send a receipt, update search), I use the transactional outbox with idempotent consumers: simple, at-least-once and eventually consistent.
If a later step can fail for business reasons and earlier steps must be undone (payment declined after stock was reserved), I build a saga, usually orchestrated, with compensations, timeouts and persisted state.
The trade-off: each step up buys flexibility across team and service boundaries, but costs complexity, latency and operating effort, so I pick the lowest one that meets the business rules.
"I go from cheapest to most expensive and stop at the first option that meets the business rules. Step one is: which rules must hold at every instant? If the rule is 'you can't transfer more than your balance', the balance and the debit must change in one transaction, so they belong in one aggregate in one service. A surprising number of 'we need a saga' conversations end here, because the boundary was drawn around technical layers, not business invariants.
Step two: if the other services only react, and nothing they do ever needs undoing, the outbox is enough. The order is saved with an
OrderPlacedoutbox row in one EF Core transaction; a relay publishes it at-least-once; email, analytics and search consumers dedupe by message id. Users see the order straight away and the rest catches up in seconds.Step three is the saga, when a later step can fail for a business reason and earlier steps must be compensated. For example, at [company] we [built checkout as reserve stock, take payment, book delivery]. Payment can be declined, so the stock reservation must be released; delivery can be unavailable, so the payment must be refunded. I chose an orchestrated saga ([MassTransit state machine / a hand-rolled orchestrator with state in SQL]) because we needed timeouts and one place to see where each order was stuck. The non-compensatable step, sending to the warehouse, went last. Stuck sagas dropped to [a handful a week], each visible on a dashboard.
The mistake I see is building a saga because it's the 'microservices way' for something one service could do in one transaction. Distribution has to earn its place; a saga is the price you pay for an earlier boundary decision, not a goal."
Does an invariant span the data at every instant?
yes -> one aggregate, one service, one local transaction (redraw the boundary)
no
↓
Do downstream effects ever need undoing if a later step fails?
no -> outbox + idempotent consumers (eventual consistency)
yes
↓
How many steps, and do you need timeouts and visibility?
2-3 steps, loose coupling -> choreographed saga (events)
more steps, timeouts, audit -> orchestrated saga (state machine)
↓
Scarce resource involved? -> reservation with expiry inside the saga
| One transaction | Outbox + eventual | Saga | |
|---|---|---|---|
| Consistency | Immediate, atomic | Eventual; no undo | Eventual; compensations |
| Failure handling | Rollback | Retry until it succeeds | Compensate or escalate |
| Latency for the user | One round trip | One round trip; others lag seconds | Pending state for seconds to minutes |
| Coupling | Data in one service | Loose | Loose data, coupled process |
| Operating cost | Low | Relay, outbox cleanup, dedup | State store, timeouts, dashboards, manual recovery |
| Example | Bank transfer between two accounts in one ledger | Order placed → receipt email, search index | Checkout: stock → payment → delivery |
| Orchestration | Choreography | |
|---|---|---|
| Control | Central orchestrator sends commands | Each service reacts to events |
| Visibility | One place to see state | Reconstruct from traces |
| Timeouts | Natural (scheduled messages) | Hard; each service must own its own |
| Best for | 4+ steps, compensations, SLAs | 2-3 steps, independent reactions |
| Risk | Orchestrator becomes a god service | Cyclic event chains nobody understands |
A checkout saga handling [20,000 orders a day] completed [99.6%] of orders in under 3 seconds. 0.3% compensated automatically (declined payments released stock within 1 second), and about 0.1% hit the 15-minute timeout and went to a support queue. Before, with a choreographed chain and no timeouts, [about 40 orders a day] were silently stuck with reserved stock.
Checks whether the candidate can choose the simplest consistency mechanism that satisfies the business rules, rather than defaulting to sagas or to distributed transactions.
Green flags
Red flags
An invariant is a rule that must hold whenever anyone looks. Transactions protect invariants; nothing else does. If two pieces of data share an invariant, splitting them across services turns a cheap local transaction into a distributed coordination problem. DDD's aggregate is exactly the unit of transactional consistency, so the first design step is finding aggregates, not services.
| Rule | Kind | Where it lives |
|---|---|---|
| Account balance ≥ 0 | True invariant | One aggregate, one transaction |
| Order total = sum of lines | True invariant | One aggregate |
| Customer gets a receipt after ordering | Eventual policy | Outbox → email consumer |
| Stock reserved for every paid order | Process rule | Saga with reservation |
How to find them: ask domain experts "what must never be seen, even for a second?" versus "what must be true by the end of the day?". Pitfalls: treating every business rule as an instant invariant (most tolerate seconds of lag), drawing services around teams or tables instead of rules, and missing invariants that span a collection ("no two bookings overlap"), which need one aggregate per resource or a unique constraint.
Orders service (one local transaction) Relay (separate loop) Consumers
BEGIN TRAN
INSERT Order
INSERT Outbox(OrderPlaced, MessageId)
COMMIT ---> polls unpublished rows ---> publish to broker
marks PublishedAt (at-least-once)
-> Email (dedupe by MessageId)
-> Search (upsert by OrderId, version)
The transaction boundary covers only the order and the outbox row. The relay runs afterwards: it reads unpublished rows, publishes them, then marks them published. If it crashes between publishing and marking, the message is published again, which is why delivery is at-least-once and consumers deduplicate. The effects downstream are retried until they succeed. If one can fail permanently for a business reason, the outbox alone isn't enough.
Orchestrator Stock Payment Delivery
|-- Reserve -------->|
|<- Reserved --------|
|-- Charge ------------------------->|
|<- Declined ------------------------|
|-- Release -------->| (compensation)
| state = Cancelled, notify customer
Timeout path: no reply in 15 min -> compensate completed steps -> escalate to support
Saga state (current step, ids, deadlines) is persisted after every transition, ideally together with the outbox rows for the next commands, so a crash resumes correctly. Every handler is idempotent because commands and replies are delivered at-least-once.
| Step type | Example | Place it |
|---|---|---|
| Easily compensated | Reserve stock (release), hold credit (release) | Early |
| Compensated with cost | Charge card (refund, fees, customer sees it) | Middle |
| Not compensatable (pivot) | Ship parcel, send to external partner | Last |
The pivot step is the point of no return; after it, the saga only moves forward with retries.
A saga introduces states the UI must show honestly: "Order received, confirming payment." The API returns 202 Accepted with a status URL or pushes updates via SignalR. Timeouts and escalation paths are business decisions: how long may a payment be pending before we cancel and tell the customer?
| Tool | Saga support | Licence |
|---|---|---|
| MassTransit v9 | State machine sagas with EF Core, Redis and other persistence | Commercial licence required (v9 onwards) |
| MassTransit v8 | Same features | Apache 2.0, official maintenance announced through the end of 2026; plan the upgrade or an alternative now |
| NServiceBus | Sagas, outbox, timeouts | Commercial |
| Durable Functions / Dapr Workflow | Code-first orchestration | Open source (Azure hosting costs for Functions) |
| Hand-rolled orchestrator | State table + outbox + Service Bus scheduled messages | Your code |
For one or two flows, a hand-rolled orchestrator like the code example is reasonable; for many flows, a framework's persistence, retries and tooling usually pay for the licence. Community forks of MassTransit v8 exist, but evaluate their maintenance before relying on one.
A minimal orchestrated saga: persisted state, idempotent transitions, compensation and a timeout. The bus and outbox are abstracted.
namespace Checkout.Saga;
using Microsoft.EntityFrameworkCore;
public enum CheckoutStep { Started, StockReserved, Paid, Completed, Compensating, Cancelled }
public sealed class CheckoutSaga
{
public Guid OrderId { get; init; }
public CheckoutStep Step { get; set; } = CheckoutStep.Started;
public DateTimeOffset Deadline { get; set; }
public byte[] RowVersion { get; set; } = []; // optimistic concurrency between replicas
}
public sealed record StockReserved(Guid OrderId);
public sealed record PaymentDeclined(Guid OrderId, string Reason);
public sealed record PaymentCaptured(Guid OrderId);
public sealed record SagaTimedOut(Guid OrderId);
public interface IOutbox { void Send(object command); } // written in the same SaveChanges
public sealed record ChargePayment(Guid OrderId);
public sealed record ReleaseStock(Guid OrderId);
public sealed record BookDelivery(Guid OrderId);
public sealed class CheckoutOrchestrator(SagaDb db, IOutbox outbox, TimeProvider clock)
{
public Task Handle(StockReserved m, CancellationToken ct) =>
Transition(m.OrderId, from: CheckoutStep.Started, ct, saga =>
{
saga.Step = CheckoutStep.StockReserved;
saga.Deadline = clock.GetUtcNow().AddMinutes(15);
outbox.Send(new ChargePayment(m.OrderId));
});
public Task Handle(PaymentDeclined m, CancellationToken ct) =>
Transition(m.OrderId, from: CheckoutStep.StockReserved, ct, saga =>
{
saga.Step = CheckoutStep.Cancelled; // compensation is a new action, not a rollback
outbox.Send(new ReleaseStock(m.OrderId));
});
public Task Handle(PaymentCaptured m, CancellationToken ct) =>
Transition(m.OrderId, from: CheckoutStep.StockReserved, ct, saga =>
{
saga.Step = CheckoutStep.Paid;
outbox.Send(new BookDelivery(m.OrderId)); // pivot step goes last
});
public Task Handle(SagaTimedOut m, CancellationToken ct) =>
Transition(m.OrderId, from: CheckoutStep.StockReserved, ct, saga =>
{
saga.Step = CheckoutStep.Compensating;
outbox.Send(new ReleaseStock(m.OrderId)); // and alert support in a real system
});
// Idempotent: a duplicate or late message for a step we've left is ignored.
private async Task Transition(Guid orderId, CheckoutStep from, CancellationToken ct, Action<CheckoutSaga> apply)
{
var saga = await db.Sagas.SingleOrDefaultAsync(s => s.OrderId == orderId, ct);
if (saga is null || saga.Step != from) return;
apply(saga);
await db.SaveChangesAsync(ct); // state + outbox commands in one transaction
}
}
public sealed class SagaDb(DbContextOptions<SagaDb> options) : DbContext(options)
{
public DbSet<CheckoutSaga> Sagas => Set<CheckoutSaga>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<CheckoutSaga>().HasKey(s => s.OrderId);
b.Entity<CheckoutSaga>().Property(s => s.RowVersion).IsRowVersion();
}
}
The choice between these is mostly a boundary decision made earlier, and a saga is often the bill for it. I'd rather spend an event-storming session finding the real invariants than spend months operating a saga that guards a rule which should have been a transaction. When a saga is right, I insist on the operating pieces from day one: persisted state, timeouts, an outbox for commands, a dashboard of sagas by state and age, and a runbook for manual recovery.
I also make the business own the pending-state experience and the timeout values, because they are product decisions: "payment may be pending for up to 15 minutes, then we cancel and email" is a sentence a product owner should sign off.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| One service, one transaction | Instant invariants; one team owns the data | Larger service | Data with different owners, scaling or compliance needs |
| Outbox + eventual | Pure reactions, never undone | Relay, dedup, lag monitoring | Later steps can fail for business reasons |
| Choreographed saga | 2-3 steps, independent teams | Hard to see state; scattered timeouts | Long flows, strict SLAs |
| Orchestrated saga | 4+ steps, compensations, deadlines | State store, orchestrator ownership, tooling licence | Simple reactions |
| Metric | Why |
|---|---|
| Sagas by state and age | Stuck flows |
| Compensation rate | Business failure trends (declines, out-of-stock) |
| Timeout rate | Lost messages or slow dependencies |
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.
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.
Two-phase commit (2PC) makes several resources commit atomically: a coordinator asks every participant to prepare (write, lock and vote yes), then tells all of them to commit. It is correct, but it is a blocking protocol: if the coordinator fails after prepare, participants sit in-doubt holding locks. It also needs every participant available, holds locks across network round trips, and most cloud resources (Service Bus, Kafka, Cosmos DB, third-party HTTP APIs) cannot enlist at all. In .NET 10, MSDTC-backed distributed transactions work only on Windows.
So instead we:
The trade-off: you give up immediate atomicity across services and accept eventual consistency, which you must design and monitor for.
How to tell it (STAR)
**S:** At [company], stock was drifting and [about 40 orders a day] were stuck in processing, with no errors anywhere. **T:** I was asked to find out why and redesign the flow. **A:** Tracing stuck orders showed a PaymentDeclined event had dead-lettered in Stock, so reservations were never released, and in a choreographed chain no one owned a timeout. I cleaned up the backlog, then replaced the chain with an orchestrated saga with persisted state, a 15-minute timeout per step, compensations, and the non-reversible delivery step moved last. **R:** Stuck orders went from [about 40 a day] to [a few a week], each visible on a dashboard, and stock reconciliation has stayed within [0.1%].
Last updated 23 Nov 2026.