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.
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.
"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 sendsAuthorisePayment, waits forPaymentAuthorisedorPaymentDeclined, thenAllocateStock, thenCreateShipment. Each reply moves the state machine. If allocation fails after payment was authorised, the compensation isVoidAuthorisation, not a rollback. Every step has a timeout, so an order doesn't sit inAwaitingPaymentforever. 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
SaveChangeswithout 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."
| 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 |
| 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.
Placed ─► AwaitingPayment ─► PaymentAuthorised ─► Allocating ─► Allocated ─► Picking ─► Shipped ─► Delivered
│ │ declined/timeout │ out of stock │ cancel (before picking) │ return
└────────────┴─────────────────────────┴─ void auth / release stock ──► Cancelled └► Returned → Refunded
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
| 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) |
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.
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
Red flags
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.
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.
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.
| 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.
PaymentAuthorised for an order already Cancelled triggers a void, not a state change.SessionId = OrderId give FIFO per order and one consumer per session at a time. Across orders, processing stays parallel.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'.
SQS FIFO with MessageGroupId = OrderId, SNS or EventBridge for fan-out, Step Functions as a managed orchestrator, DynamoDB or Aurora for service data.
PaymentAuthorised twice and prove the handler is idempotent.Apply rejects invalid transitions, and unit-test every transition.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);
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.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).AwaitingPayment forever after a lost reply. Instead: scheduled timeout messages and a stuck-order alert.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.
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 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.
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.
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.
Last updated 23 Nov 2026.