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

📚 Interview question

A business process spans several steps and services. How do you decide between keeping it in one service with one database transaction, using an outbox with eventual consistency, and building a saga with compensations? Walk me through the questions you ask, the trade-offs, and an example of each choice.

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.

Senior Architecture Advanced architecture data-consistency distributed-systems eventual-consistency outbox saga

🎯 Key points

  • First question: which invariants must hold at every instant? Those stay in one aggregate and one transaction
  • Outbox + idempotent consumers when downstream effects can lag and never need undoing
  • Saga when a later step can fail for business reasons and earlier steps must be compensated
  • Orchestration for flows with many steps, timeouts and visibility needs; choreography for 2-3 loosely coupled reactions
  • Compensations are new business actions (refund, release), not rollbacks; some steps can't be compensated and go last
  • Reservations with expiry (try, confirm, cancel) for scarce resources such as stock or credit
  • Design the pending state for users: 'order received, confirming payment', with timeouts and escalation
  • Operating cost rises: saga state, timeouts, dead letters, dashboards and reconciliation

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 OrderPlaced outbox 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."


The decision path

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

Comparison

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 or choreography

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts with invariants and aggregate boundaries
  • Clearly separates "react, never undo" (outbox) from "may need undoing" (saga)
  • Orders saga steps by compensability and adds timeouts
  • Talks about the pending-state UX and the operating cost

Red flags

  • Reaches for a saga for every cross-service interaction
  • Thinks compensations are rollbacks or ignores timeouts
  • Proposes distributed transactions as the default

📚 Learn in depth

1. Invariants decide boundaries

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.

2. Outbox: eventual, no undo

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.

3. Saga: a state machine with compensations

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.

4. Ordering steps by compensability

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.

5. The user experience of eventual consistency

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?

6. Tooling in .NET (as of November 2026)

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.

Try it yourself

  1. List the rules for a checkout in a table and mark each as invariant, eventual policy or process rule.
  2. Implement the orchestrated saga in the code example with an in-memory bus, then make payment decline 20% of the time and assert stock is always released.
  3. Add a timeout using a scheduled message and test that a lost reply triggers compensation.
  4. Make the stock service deliver every reply twice and confirm the saga ignores the duplicate.
  5. Model the same flow as choreography with events and draw the event chain; compare how hard it is to answer "where is order 123?"

💻 Code

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

⚠ Common mistakes

  • Mistake: Splitting data that shares an invariant into two services, then building a saga to keep them in step. Why it is wrong: A saga can't enforce an instant invariant; there is always a window where the rule is broken. Instead: Keep the invariant in one aggregate and one transaction.
  • Mistake: Using a saga where an outbox would do. Why it is wrong: State machines, timeouts and compensations add cost for effects that never need undoing. Instead: Outbox plus idempotent consumers for pure reactions.
  • Mistake: Choreographing a long flow with many steps. Why it is wrong: Nobody can answer where an order is stuck, and timeouts end up scattered or missing. Instead: Orchestrate flows with more than about three steps or with deadlines.
  • Mistake: Treating compensation as rollback. Why it is wrong: The customer may have seen the charge, and the refund has fees and timing. Instead: Model compensations as visible business actions and tell the user.
  • Mistake: Putting the non-compensatable step early. Why it is wrong: A later failure leaves you with something you can't undo. Instead: Order steps by compensability; the pivot step goes last.
  • Mistake: No timeouts in the saga. Why it is wrong: A lost reply leaves the order and its reserved stock stuck forever. Instead: Schedule a timeout message per step and compensate or escalate.
  • Mistake: Saga handlers that aren't idempotent. Why it is wrong: At-least-once delivery means a duplicate reply charges or ships twice. Instead: Check the current step before transitioning and dedupe commands downstream.
  • Mistake: Hiding the pending state from users. Why it is wrong: Users retry or call support when an order looks lost. Instead: Return 202 with a status, and show an honest "confirming payment" state.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate chooses a saga Why: Checks saga design detail: orchestration, persistence, late replies
    How to answer

    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.

    • Choreography: services react to each other's events. It's simple for two or three steps, but the flow is implicit.
    • Orchestration: a state machine (such as a MassTransit saga) sends commands, persists its state per correlation id, and handles failures. The flow is explicit and observable.

    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.

  2. When: Candidate mentions combining outbox, inbox and saga Why: Checks failure handling at each step of an outbox, inbox and saga flow
    How to answer

    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.

  3. When: Candidate is asked why not just use a distributed transaction Why: Checks why two-phase commit isn't the answer
    How to answer

    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:

    • keep each invariant inside one service and one local transaction,
    • propagate changes with the transactional outbox and idempotent consumers,
    • coordinate longer flows with sagas and compensations.

    The trade-off: you give up immediate atomicity across services and accept eventual consistency, which you must design and monitor for.

🛠 Real-world problems: how you handle them

Orders stuck with reserved stock in a choreographed checkout
Situation
An online retailer's checkout across Orders, Stock, Payments and Delivery services on [AKS, Australia East], [20,000 orders a day], built as a chain of events with no central state.
Signals
Stock counts drifting down over weeks; [about 40 orders a day] showing 'processing' forever; customer complaints about out-of-stock items that were in the warehouse; no errors in any single service's logs.
Investigation
Traced stuck orders in Application Insights by operation_Id and found the PaymentDeclined event had been dead-lettered in Stock after a deserialisation error, so the reservation was never released. Service Bus dead-letter queues held [several thousand] messages across subscriptions. Nobody owned the end-to-end flow, so no one had a timeout.
Resolution
Immediate: replayed the fixed dead-lettered messages and ran a script that released reservations older than 24 hours with no paid order. Real fix: an orchestrated saga with persisted state, a 15-minute timeout per step with compensation, the delivery booking moved to after payment, and commands sent through an outbox.
Prevention
A dashboard of sagas by state and age with an alert on any saga older than 30 minutes, a dead-letter alert per subscription, a nightly stock reconciliation against reservations and orders, and an ADR recording why the flow is orchestrated.

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

↩ Usually asked after

More in Data Consistency

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me