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

📚 Interview question

Walk me through an end-to-end order flow across Ordering, Payment and Inventory services that uses the outbox, the inbox and an orchestrated saga. At each step, what happens if a service crashes, a message is duplicated, or a reply never arrives?

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.

Senior Architecture Advanced architecture azure-service-bus distributed-systems inbox outbox saga

🎯 Key points

  • Each service commits its state change and outgoing messages atomically (outbox) and dedups incoming ones (inbox)
  • The saga orchestrator persists its state per order and reacts to events with commands; its own state change and outgoing commands also use the outbox
  • Compensations are semantic undo (release stock, refund), not rollbacks; they must be idempotent
  • Timeouts via scheduled messages; late replies after a timeout are handled explicitly (e.g. refund a late capture)
  • Crash at any step: either nothing committed (message redelivered) or everything committed (outbox resends): no lost or phantom messages
  • Duplicates absorbed by inbox plus idempotent operations keyed by order id
  • Poison messages dead-letter after MaxDeliveryCount with alerting and a replay runbook
  • Observability: correlation id across the flow, saga state queries, distributed tracing

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

🗣 Full answer (senior)

How I would answer this in an interview

"I'll walk the happy path first, then break it. The customer submits an order. Ordering saves the Order as Pending and an OrderPlaced outbox 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 state AwaitingStock, and in the same transaction writes a ReserveStock command to its outbox plus a scheduled timeout. Inventory consumes ReserveStock, records the message id in its inbox, reserves stock and writes StockReserved to its outbox, all in one transaction. The saga moves to AwaitingPayment and sends CapturePayment with an idempotency key of the order id. Payment calls the gateway, records the result and publishes PaymentCaptured; 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 a PaymentUnknown state 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."


Failure-point analysis

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 vs choreography for this flow

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can combine outbox, inbox and sagas into a coherent design and reason precisely about each failure point.

Green flags

  • Atomic state-plus-outbox in every participant and in the saga
  • Inbox dedup and idempotent operations keyed by order id
  • Explicit timeout and late-reply states, compensations as semantic undo
  • Concurrency control on saga state
  • Observability for stuck sagas and DLQs

Red flags

  • Distributed transactions or two-phase commit as the answer
  • Happy path only
  • "Just retry" with no idempotency

📚 Learn in depth

1. The flow

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                            |

2. The saga state machine

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

3. Why each piece is necessary

  • Outbox in every participant and in the saga: the state change and the next message commit together; no lost or phantom messages.
  • Inbox in every consumer: at-least-once delivery becomes effectively-once processing.
  • Idempotent operations keyed by order id: ReserveStock(orderId) twice reserves once; payment uses the order id as the gateway idempotency key.
  • Concurrency control on saga state: a row version (optimistic concurrency) so two messages for the same saga processed in parallel don't both transition. Service Bus sessions keyed by order id serialise them instead.
  • Scheduled messages for timeouts: Service Bus ScheduleMessageAsync, or the saga library's scheduler.

4. Compensation is not rollback

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.

5. Implementation choices in .NET (late 2026)

  • MassTransit state machine sagas with EF Core persistence and the EF Core transactional outbox. Note that MassTransit v9 moved to a commercial licence, while v8 remains Apache 2.0; check current terms before adopting.
  • Wolverine sagas with its EF Core or Marten outbox.
  • NServiceBus sagas (commercial).
  • Hand-rolled: a Sagas table with state, version and data, plus the outbox and inbox. Viable for one or two flows.
  • Azure Durable Functions / Durable Task orchestrations as an alternative workflow engine.

6. Observability

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.

Try it yourself

  1. Model the state machine above as a table: rows are states, columns are messages, each cell an action. Fill every cell.
  2. Implement the flow with MassTransit or Wolverine in-memory transports and write tests that inject duplicates and drop replies.
  3. Kill the Inventory consumer after commit but before completion and verify StockReserved is still sent once.
  4. Simulate a gateway timeout followed by a late success and check the refund path.
  5. Add an alert on sagas older than 10 minutes in a non-terminal state.

💻 Code

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

⚠ Common mistakes

  • Mistake: Designing only the happy path. Why it is wrong: the saga's value is in duplicates, timeouts and late replies. Instead: a full state-by-message table with an action in every cell.
  • Mistake: Treating compensation as rollback. Why it is wrong: other parties already saw the intermediate state, and some actions can't be undone. Instead: semantic, idempotent compensations; irreversible steps last.
  • Mistake: Saga state saved separately from its outgoing commands. Why it is wrong: a crash between them loses or duplicates commands. Instead: saga state and outbox rows in one transaction.
  • Mistake: No concurrency control on saga state. Why it is wrong: two messages processed in parallel both transition. Instead: row version or Service Bus sessions keyed by order id.
  • Mistake: Guessing on timeout (assume payment failed). Why it is wrong: a capture may still succeed, charging a customer for a cancelled order. Instead: a PaymentUnknown state that queries by idempotency key, plus refund on late success.
  • Mistake: Non-idempotent participants. Why it is wrong: redelivery double-reserves stock or double-charges. Instead: inbox plus operations keyed by order id.
  • Mistake: No visibility into stuck sagas. Why it is wrong: orders silently hang. Instead: alerts on non-terminal sagas older than a threshold, correlation ids in traces.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the saga or compensations. Why: Checks pattern-level saga design (orchestration vs choreography, persistence).
    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 relies on the outbox at each step. Why: Checks depth on outbox mechanics.
    How to 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.

  3. When: Candidate says duplicates are absorbed by an inbox. Why: Checks the inbox implementation details.
    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

Payment gateway outage leaves orders in limbo
Situation
A [ticketing] platform ran an orchestrated order saga across Ordering, Inventory and Payment on Azure Service Bus at [~25 orders per second]. The payment gateway had a [20-minute] partial outage during an on-sale.
Signals
Sagas in `AwaitingPayment` climbed to [3,000+]; payment timeouts fired; customers reported "charged but no ticket" on social media; DLQ depth on the payment subscription rose.
Investigation
Queried saga states and time-in-state; traced sample orders end to end in Application Insights using correlation ids; compared gateway settlement reports with saga states; reviewed the timeout handler, which originally assumed failure and released stock.
Resolution
Immediate: paused timeouts and replayed the DLQ after the gateway recovered; reconciled captures against the settlement report and refunded [~40] orders captured after release. Long term: added a `PaymentUnknown` state that queries the gateway by idempotency key, an explicit refund path for late captures, and an alert on time-in-state.
Prevention
State-by-message table reviewed for every saga change; chaos tests that drop and delay payment replies; daily reconciliation between gateway settlements and saga states; a runbook for gateway outages.

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.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me