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

📚 Interview question

Design an order management system for a retailer that sells online and in stores: orders flow through payment, stock allocation, fulfilment from a warehouse or store, shipping, cancellations and returns, and several services own those steps. Walk me through the order lifecycle, how services communicate with events, how you keep them consistent without distributed transactions, and how customer service sees where an order is.

A full order management system design: requirements and order-volume estimates, an explicit order state machine, service boundaries, the transactional outbox and Azure Service Bus for events, an orchestrated saga with compensations and timeouts, idempotent consumers, ordering per order, a read model for order tracking, and failure handling, on Azure with .NET.

Senior SystemDesign Advanced azure-service-bus event-driven order-management outbox saga system-design

🎯 Key points

  • Clarify: channels, order volume and peaks, split shipments, cancellation and return rules, who owns stock truth
  • Explicit order state machine (Placed → PaymentAuthorised → Allocated → Shipped → Delivered; Cancelled, Returned) with allowed transitions only
  • Each service owns its data; events published with the transactional outbox so state change and event commit together
  • Orchestrated saga in the Order service for the multi-step flow, with compensations (void payment, release stock) and timeouts
  • At-least-once delivery: idempotent consumers keyed by message id plus a business key
  • Per-order ordering with Service Bus sessions (SessionId = OrderId); events carry a version
  • Order tracking read model (projection) for customers and support, rebuilt from events
  • Dead-letter queues, stuck-order detection and reconciliation jobs as part of the design

⏱ 30-second answer

I model the order as an explicit state machine owned by the Order service, with Payment, Inventory, Fulfilment and Shipping each owning their own data. Services communicate with events and commands over Azure Service Bus, published through a transactional outbox so a state change and its event commit together. The multi-step flow is an orchestrated saga: the Order service sends commands, waits for replies, applies timeouts, and runs compensations (void the payment, release stock) when a step fails. Delivery is at-least-once, so every consumer is idempotent, and sessions keyed by OrderId keep one order's messages in order. Customer service reads a tracking projection built from the events. The trade-off: no distributed transactions means eventual consistency, so you design for stuck and out-of-order states explicitly.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd clarify the scope first: [online and 150 stores], [20,000] orders a day with [10×] peaks at sales events, orders that can split across a warehouse and a store, cancellation allowed until picking starts, and returns within [30 days]. Then I'd name the core idea: the order is a state machine, and the Order service is the only thing that changes its state. Payment, Inventory, Fulfilment and Shipping are separate services with their own databases, because they change for different reasons and scale differently.

The flow is a saga. When an order is placed, the Order service saves it and an outbox row in the same transaction, then the relay publishes OrderPlaced. I prefer orchestration for this: the Order service sends AuthorisePayment, waits for PaymentAuthorised or PaymentDeclined, then AllocateStock, then CreateShipment. Each reply moves the state machine. If allocation fails after payment was authorised, the compensation is VoidAuthorisation, not a rollback. Every step has a timeout, so an order doesn't sit in AwaitingPayment forever. Service Bus delivers at least once, so every handler records the message id and checks the business state before acting, and I use sessions with the order id so messages for one order are processed in order.

For example, at [company] we [had orders stuck between payment and allocation after a consumer crashed]; [adding timeouts, a stuck-order dashboard and a nightly reconciliation against the payment provider] [cut manual fixes from about 40 a week to 2].

Customer service never queries five services. A tracking projection subscribes to all order events and keeps one denormalised row per order with its timeline, so 'where's my order?' is one read.

The mistake I see is publishing events after SaveChanges without an outbox. A crash in between loses the event, and the order silently stops moving. The outbox, idempotent consumers and timeouts are what make an event-driven order system trustworthy."


Requirements

Type Requirement Assumption
Functional Place, pay, allocate, fulfil, ship, track Split shipments allowed
Functional Cancel before picking; return within 30 days Refund via original payment
Functional Support view of full order timeline One read
Non-functional No lost or duplicated orders, no double charge Outbox + idempotency
Non-functional Place order p95 < 500 ms Async downstream steps
Non-functional Peak 10× at sales events Queue-based load levelling

Capacity estimate

Quantity Arithmetic Result
Orders 20,000/day ≈ 0.25/s avg, peak ×10 (concentrated) ≈ 30/s
Messages per order ~12 commands and events ≈ 240,000/day, peak ≈ 360/s
Order rows 7.3M/year × ~5 KB with lines ≈ 37 GB/year
Event history 88M events/year × 1 KB ≈ 88 GB/year (archive after 2 years)

The volumes are modest; the hard part is correctness, not scale.

State machine

Placed ─► AwaitingPayment ─► PaymentAuthorised ─► Allocating ─► Allocated ─► Picking ─► Shipped ─► Delivered
   │            │ declined/timeout        │ out of stock          │ cancel (before picking)          │ return
   └────────────┴─────────────────────────┴─ void auth / release stock ──► Cancelled              └► Returned → Refunded

High-level design

Web / POS ─► Orders API (ASP.NET Core) ─► Order DB (Azure SQL) + Outbox
                                           │ relay
                                           ▼
                         Azure Service Bus (topics + session queues, DLQ)
          ┌─────────────────────┼───────────────────────────┐
          ▼                     ▼                    ▼                   ▼
     Payment svc         Inventory svc        Fulfilment svc       Shipping svc (carrier APIs)
     (own DB)            (own DB)             (warehouse/store)    (labels, tracking webhooks)
          └──────── replies/events ────► Order saga (orchestrator in Order svc)
                                  └────► Tracking projection (Cosmos DB / SQL) ◄── Support UI, customer app

Orchestration vs choreography

Aspect Orchestration Choreography
Flow visibility In one place (saga state) Spread across services
Coupling Orchestrator knows participants Services know events only
Timeouts and compensation Natural Hard to coordinate
Fits Core order flow Side effects (emails, analytics, loyalty points)

Production example

A retailer processing [25,000] orders a day moved from a synchronous chain of HTTP calls to an outbox plus an orchestrated saga on Service Bus: place-order p95 fell from [2.4 s to 300 ms], orders lost during partial outages went from [dozens per incident to zero], and stuck orders were detected within [15 minutes] instead of by customer complaints.

🔍 What the interviewer is checking

Checks that the candidate can design an event-driven order flow that stays correct without distributed transactions: state machine, outbox, saga with compensations and timeouts, idempotent consumers and a read model.

Green flags

  • Explicit order state machine with a single owner
  • Transactional outbox and idempotent consumers
  • Orchestrated saga with compensations and timeouts
  • Per-order ordering (sessions) and a tracking projection
  • Reconciliation and stuck-order detection

Red flags

  • Distributed transactions across services
  • Publishing events without an outbox
  • Assuming exactly-once delivery or global ordering
  • No plan for stuck or half-finished orders

📚 Learn in depth

1. Why not one transaction

Payment, stock and shipping live in different services and often in external systems (payment provider, carrier). A distributed transaction (2PC) across them either isn't supported or couples their availability. A saga replaces one ACID transaction with a sequence of local transactions plus compensations.

2. The outbox

BEGIN TRAN
  UPDATE Orders SET Status='AwaitingPayment', Version=Version+1 WHERE Id=@id AND Version=@v
  INSERT Outbox(Id, Type, Payload, OccurredAt)
COMMIT
Relay: SELECT unsent → publish to Service Bus → mark sent   (at-least-once)

The relay may publish twice after a crash, so consumers must deduplicate. Libraries such as MassTransit or NServiceBus provide outbox, saga persistence and inbox deduplication; hand-rolled is fine for a few message types.

3. The orchestrated saga

The saga state is stored with the order: current step, correlation id, deadline. Each incoming reply is handled in one local transaction that updates the state and writes the next command to the outbox. Timeouts are scheduled messages (Service Bus scheduled enqueue) that, if the saga is still waiting, trigger a retry or compensation.

4. Compensations are business actions

| Step done | Failure later | Compensation | |---|---|---| | Payment authorised | Out of stock | Void authorisation (or refund if captured) | | Stock allocated | Customer cancels | Release allocation | | Shipped | Return | Return label, restock after inspection, refund | Compensations can fail too, so they are retried and monitored, and some end in a human task.

5. Idempotency and ordering

  • Inbox table of processed message ids, written in the same transaction as the effect.
  • State checks: PaymentAuthorised for an order already Cancelled triggers a void, not a state change.
  • Service Bus sessions with SessionId = OrderId give FIFO per order and one consumer per session at a time. Across orders, processing stays parallel.
  • Events carry the order version so projections can ignore older events.

6. Read model for tracking

A projection handler consumes all order-related events and upserts a document per order with status, lines, shipments and a timeline. It can be rebuilt by replaying events. It is eventually consistent, usually seconds behind, which is fine for 'where is my order'.

7. Failure handling and reconciliation

  • Dead-letter queues with alerting and a replay tool.
  • Stuck-order query: orders in a non-terminal state past their deadline.
  • Nightly reconciliation with the payment provider (authorised but no order, captured but cancelled) and the warehouse system.

8. AWS mapping

SQS FIFO with MessageGroupId = OrderId, SNS or EventBridge for fan-out, Step Functions as a managed orchestrator, DynamoDB or Aurora for service data.

Try it yourself

  1. Implement the outbox with EF Core and kill the process between commit and publish; confirm the event still goes out.
  2. Deliver the same PaymentAuthorised twice and prove the handler is idempotent.
  3. Model the order state machine as a C# class whose Apply rejects invalid transitions, and unit-test every transition.
  4. Schedule a timeout message and verify the saga compensates when payment never replies.
  5. Rebuild the tracking projection from the event history and compare it with the live one.

💻 Code

An order aggregate with an explicit state machine, an idempotent saga handler that writes the next command to the outbox in the same transaction, and session-based ordering.

using Microsoft.EntityFrameworkCore;

namespace Orders;

public enum OrderStatus { Placed, AwaitingPayment, PaymentAuthorised, Allocating, Allocated, Picking, Shipped, Delivered, Cancelled }

public sealed class Order
{
    private static readonly Dictionary<OrderStatus, OrderStatus[]> Allowed = new()
    {
        [OrderStatus.Placed] = [OrderStatus.AwaitingPayment, OrderStatus.Cancelled],
        [OrderStatus.AwaitingPayment] = [OrderStatus.PaymentAuthorised, OrderStatus.Cancelled],
        [OrderStatus.PaymentAuthorised] = [OrderStatus.Allocating, OrderStatus.Cancelled],
        [OrderStatus.Allocating] = [OrderStatus.Allocated, OrderStatus.Cancelled],
        [OrderStatus.Allocated] = [OrderStatus.Picking, OrderStatus.Cancelled],
        [OrderStatus.Picking] = [OrderStatus.Shipped],
        [OrderStatus.Shipped] = [OrderStatus.Delivered],
    };

    public Guid Id { get; init; }
    public OrderStatus Status { get; private set; }
    public int Version { get; private set; } // concurrency token
    public DateTimeOffset? StepDeadline { get; private set; }

    public bool TryMoveTo(OrderStatus next, DateTimeOffset? deadline = null)
    {
        if (!Allowed.TryGetValue(Status, out var targets) || !targets.Contains(next)) return false;
        Status = next; StepDeadline = deadline; Version++;
        return true;
    }
}

public sealed record OutboxMessage(Guid Id, string Type, string Payload, Guid OrderId, DateTimeOffset OccurredAt);
public sealed record InboxEntry(Guid MessageId, DateTimeOffset ProcessedAt);

public sealed class OrderDb(DbContextOptions<OrderDb> o) : DbContext(o)
{
    public DbSet<Order> Orders => Set<Order>();
    public DbSet<OutboxMessage> Outbox => Set<OutboxMessage>();
    public DbSet<InboxEntry> Inbox => Set<InboxEntry>();
    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Order>().Property(x => x.Version).IsConcurrencyToken();
        b.Entity<InboxEntry>().HasKey(x => x.MessageId); // duplicate delivery → PK violation
    }
}

public sealed record PaymentAuthorised(Guid MessageId, Guid OrderId);

public sealed class OrderSaga(OrderDb db, TimeProvider clock)
{
    public async Task HandleAsync(PaymentAuthorised msg, CancellationToken ct)
    {
        if (await db.Inbox.AnyAsync(i => i.MessageId == msg.MessageId, ct)) return; // already processed
        var order = await db.Orders.SingleAsync(o => o.Id == msg.OrderId, ct);
        var now = clock.GetUtcNow();

        if (order.Status == OrderStatus.Cancelled)
            db.Outbox.Add(Command("VoidAuthorisation", order.Id, now)); // late reply: compensate
        else if (order.TryMoveTo(OrderStatus.PaymentAuthorised) && order.TryMoveTo(OrderStatus.Allocating, now.AddMinutes(10)))
            db.Outbox.Add(Command("AllocateStock", order.Id, now)); // next step, same transaction

        db.Inbox.Add(new InboxEntry(msg.MessageId, now));
        await db.SaveChangesAsync(ct); // state + outbox + inbox commit atomically
    }

    private static OutboxMessage Command(string type, Guid orderId, DateTimeOffset now) =>
        new(Guid.NewGuid(), type, $"{{\"orderId\":\"{orderId}\"}}", orderId, now);
}
// Relay excerpt: SessionId = OrderId keeps one order's messages in FIFO order.
var message = new Azure.Messaging.ServiceBus.ServiceBusMessage(outbox.Payload)
{
    MessageId = outbox.Id.ToString(),   // enables broker duplicate detection if turned on for the queue
    SessionId = outbox.OrderId.ToString(),
    Subject = outbox.Type
};
await sender.SendMessageAsync(message, ct);

⚠ Common mistakes

  • Mistake: Publishing events after SaveChanges without an outbox. Why it is wrong: a crash between the two loses the event and the order stops moving. Instead: the transactional outbox with a relay.
  • Mistake: Treating compensations as rollbacks. Why it is wrong: a captured payment can't be un-captured; it needs a refund with its own failure modes. Instead: model compensations as business actions that are retried and monitored.
  • Mistake: Non-idempotent consumers. Why it is wrong: Service Bus delivers at least once, so a redelivered AllocateStock after a lock timeout allocates twice, and a redelivered RefundRequested refunds twice. Instead: record processed message ids in an inbox table in the same transaction as the effect, and check the current business state before acting (an order already Allocated ignores a second allocation; a PaymentAuthorised for a Cancelled order triggers a void instead of a transition).
  • Mistake: No timeouts in the saga. Why it is wrong: orders sit in AwaitingPayment forever after a lost reply. Instead: scheduled timeout messages and a stuck-order alert.
  • Mistake: A chain of synchronous HTTP calls for the whole flow. Why it is wrong: availability is the product of every service's availability and latency adds up. Instead: accept the order quickly and run downstream steps asynchronously.
  • Mistake: Free-form status updates from any service. Why it is wrong: invalid transitions such as Shipped → AwaitingPayment corrupt the order. Instead: one owner and an explicit state machine.
  • Mistake: Building the support view by calling every service. Why it is wrong: slow, fragile and couples support to internals. Instead: a tracking projection built from events.
  • Mistake: Assuming global ordering of messages. Why it is wrong: messages for one order arrive out of order across partitions and retries. Instead: sessions per order and versioned events.
  • Mistake: Hiding eventual consistency from users. Why it is wrong: customers see 'Order confirmed' and then a cancellation email when stock runs out. Instead: honest intermediate states ('Order received, confirming stock') and a clear message when a step fails.

🏛 Senior insight: trade-offs

Volume is rarely the hard part of an order system; correctness under partial failure is. I spend the deep-dive time on the state machine, the outbox, idempotency and timeouts, and I treat reconciliation and stuck-order detection as features, not afterthoughts. Orchestrate the core flow where you need visibility and compensation, and use choreography for side effects that nobody waits on.

Eventual consistency is a product decision. Between placing an order and allocation there is a window, usually seconds, longer at peak when queues back up. The UI shows 'received' rather than 'confirmed', confirmation emails go out after allocation, and at a flash sale I'd reserve stock synchronously at checkout (see the checkout design) so the window can't oversell. Queue depth at peak becomes customer-visible latency, so I alert on it.

History and audit. The order's events are its history: every transition with who, when and why, stored in an order-events table alongside the state. That gives support a timeline and auditors a trace. Full event sourcing (the events are the state) is an option for the Order service, but it adds replay, versioning and snapshot complexity; a state table plus an append-only event history gives most of the benefit for an order domain. Neither removes the need for sagas across services.

Option When it fits Cost When not to
Orchestrated saga Multi-step flow with compensations Orchestrator is a central component Simple fan-out side effects
Choreography Independent reactions (email, loyalty) Flow hard to see Steps that must be coordinated
State + event history Most order domains One extra table When you need temporal queries of everything
Event sourcing Rich temporal queries, audit-heavy domains Replay, versioning, snapshots Teams new to it, simple CRUD

I measure orders per state and time in state, stuck orders past deadline, DLQ depth, compensation rate and success, reconciliation mismatches, queue lag at peak and place-order p95.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a saga Why: Checks orchestration vs choreography and compensation design in depth
    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 publishing events after saving the order Why: Checks the dual-write problem and how the outbox relay works
    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 mentions allocating stock Why: Checks inventory reservation that never oversells
    How to answer

    Never overselling comes down to one atomic, conditional reservation: UPDATE Stock SET Available = Available - @qty WHERE Sku = @sku AND Available >= @qty. Zero rows means sold out. I reserve at checkout, not at add-to-cart, with a reservation row and an expiry (say 10 minutes) and a sweeper that releases expired holds. The flow is a saga: reserve stock → take payment → confirm the order; if payment fails, compensate by releasing the reservation. Each step is idempotent and events go through an outbox. For a flash sale, one SKU row becomes a lock hotspot, so I split its stock into buckets or use a Redis counter with the database as the record, and add a waiting room. The trade-off: strong consistency only on the reservation, eventual consistency everywhere else.

🛠 Real-world problems: how you handle them

Orders stuck between payment and allocation after a consumer crash
Situation
An [omnichannel retailer] with [25,000] orders a day on [ASP.NET Core services] and Azure Service Bus; payment and inventory in separate services.
Signals
Customer complaints that orders were charged but never shipped; [about 40] manual fixes a week; no errors on the order API; DLQ for the allocation queue slowly growing.
Investigation
Application Insights end-to-end traces showed `PaymentAuthorised` handled but no `AllocateStock` sent for affected orders; the code published the command after `SaveChanges`, and pod restarts during deploys fell between the two. Queried orders in `PaymentAuthorised` older than [30 minutes].
Resolution
Immediate: a script re-sent allocation commands for stuck orders and DLQ messages were replayed. Long term: transactional outbox for every state change, inbox deduplication, scheduled timeout messages per saga step, and a stuck-order dashboard with alerts.
Prevention
Chaos test that kills the consumer between commit and publish; alert on orders past their step deadline; nightly reconciliation with the payment provider; outbox required by code review checklist.

How to tell it (STAR)

**S:** At [company] customers were being charged for orders that never shipped, and support fixed about [40] by hand every week. **T:** I needed to find why orders stalled and make the flow self-healing. **A:** Tracing showed we sent the next command after `SaveChanges`, so deploys and crashes lost it. I introduced a transactional outbox and inbox deduplication, added timeout messages to every saga step, and built a stuck-order dashboard plus nightly reconciliation against the payment provider. **R:** Manual fixes dropped from [40] a week to [about 2], and stuck orders were caught within [15 minutes] instead of by customer complaints.

↩ Usually asked after

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me