Skip to main content

Order Management & State Machines

Learning objectives
  • Model an order lifecycle as an explicit state machine with guarded transitions and emitted events.
  • Split a checkout into a parent order, seller sub-orders and shipments, and allocate amounts so partial refunds are correct.
  • Coordinate payment, inventory and shipping with a saga, including compensations for realistic failures.
  • Design cancellation and return (RMA) flows and their money and stock effects.
  • Keep a complete, queryable order history, and integrate safely with external OMS, WMS and ERP systems.

TL;DR​

  • An order is a long-running business process. Model it as an explicit state machine: a transition table, guards, and one event per transition. Persist transitions with a conditional update (WHERE status = :from) so concurrent actors can't both win.
  • Shape: one parent order (what the customer checked out and paid) → N sub-orders (per seller or fulfilment node) → M shipments. The parent's status is derived from its children.
  • Allocate every discount, voucher and shipping fee down to order lines at creation time, and record who funded each discount (platform or seller). Partial cancellations and refunds then become arithmetic, not guesswork.
  • Saga after payment: commit inventory → request fulfilment → book carrier → track delivery. Each step is idempotent and has a compensation (release stock, cancel the line, refund partially).
  • Cancellation rules depend on state (free before packing, needs a return after shipping). Returns are their own state machine (request → approve → ship back → inspect → refund → restock or write off).
  • History: an append-only status history table and the event stream give you the customer timeline, support tooling and audit. A separate read model sharded by user serves "My orders".
  • OMS/WMS/ERP integration goes through an anti-corruption layer with status mapping, idempotent messages, retries with a DLQ, and periodic reconciliation of states.

Why it matters​

Most e-commerce support tickets are about orders: where is it, why was it cancelled, where's my refund. Most money bugs come from orders as well: a refund issued twice, a voucher refunded in full on a partial cancellation, a seller paid for a returned item. A clear state machine with allocated amounts and an audit trail prevents whole classes of these bugs. Interviewers use "design order management" or "what happens after the customer pays?" to see whether you can model a long-running process across services without 2PC, and whether you think about partial failure, concurrency between actors (customer cancels while seller ships) and history.

Core concepts​

Order structure​

  • Parent order: the customer's checkout, linked to the payment(s). Totals here are what the customer paid.
  • Sub-order: one per seller (marketplace) or per fulfilment node (retailer with several warehouses). This is the unit sellers act on, with its own state machine.
  • Shipment: what a carrier moves. A sub-order may ship in several packages (partial availability, oversize items).
  • Order line: an immutable snapshot of SKU, name, options and unit price, plus line adjustments: each discount with its kind (item promo, shop voucher, platform voucher, coins), its funding source and its allocated amount.

The lifecycle as a state machine​

Sub-order lifecycle (simplified, marketplace flavour):

COD orders skip PendingPayment → Paid: they go straight to Confirmed, and payment happens at delivery. A failed delivery has no money to refund but does cost shipping fees.

Rules that make state machines work in production:

  • A transition table in code (from, event → to, guard, side effects), not if statements spread across handlers.
  • Guards: e.g. Cancel from Packing needs seller approval. Refund requires a prior capture. Guards are evaluated against the current persisted state.
  • Atomic persistence: UPDATE sub_orders SET status = :to, version = version + 1 WHERE id = :id AND status = :from, plus a history row and an outbox event in the same transaction. Zero rows updated means someone else moved it first, so reload and re-evaluate.
  • Idempotent events in: carrier webhooks and payment events are delivered at least once and out of order. Ignore transitions that aren't valid from the current state (a late "in transit" after "delivered").
  • Timers drive time-based transitions: payment timeout, seller confirmation SLA (auto-cancel if the seller doesn't confirm within N days), auto-complete after the return window. Use a durable scheduler or delayed queue, and re-check the state when the timer fires.

Split orders and amount allocation​

One checkout with two sellers:

LineSellerUnit × qtyItem promo (seller)Platform voucher (allocated)Net
L1 ShirtA200,000 × 2−40,000−36,000324,000
L2 CapA100,000 × 10−10,00090,000
L3 ShoesB500,000 × 1−50,000−45,000405,000
Shipping AA30,000−30,000 (free-ship voucher, platform)0
Shipping BB25,000025,000

The platform voucher here is 91,000 (10% of the 910,000 post-promo item subtotal), allocated in proportion to each line's post-promo value: 360,000 → 36,000, 100,000 → 10,000, 450,000 → 45,000. The customer pays 819,000 for items plus 25,000 shipping = 844,000. When the proportions don't divide evenly, use a documented rounding rule (proportional with largest-remainder rounding is common; see Pricing & Promotions). The point:

  • Allocation happens once, at order creation, and is stored. Never recompute it at refund time from current rules.
  • A partial cancellation of L2 refunds 90,000 (its net), not 100,000. The voucher's allocated 10,000 is either forfeited or returned to the customer's voucher wallet, per policy.
  • Funding source drives seller settlement: seller-funded promos reduce the seller's payout, and platform-funded vouchers are a platform marketing expense. See Double-Entry Ledger Design.
  • Parent status is derived: e.g. Completed when all sub-orders are terminal, PartiallyShipped when some have shipped. Compute it from children rather than storing a second state machine that can drift.

Saga across payment, inventory and shipping​

After payment, the order service orchestrates fulfilment:

Compensations and retries:

FailureHandling
Inventory commit fails (reservation expired)Try to re-reserve. If unavailable, cancel the line and refund partially
Seller doesn't confirm within SLAAuto-cancel the sub-order, refund it, penalize the seller
Carrier booking failsRetry with backoff, then try an alternative carrier, then escalate to manual handling
Refund call times outUnknown outcome: retry with the same idempotency key, query the status (see Payments & Card Flows)
Delivery failsReturnToSender, then restock on arrival, refund if prepaid, apply COD-refusal risk rules

Choose orchestration (the order service drives) for this core flow because the steps depend on each other and need a visible status. Use choreography for side effects (notifications, loyalty points, analytics). See Distributed Transactions: 2PC, TCC, Saga and Microservices Patterns.

Cancellations​

WhenWhoEffect
Pending paymentCustomer / timeoutRelease reservation and voucher. No money moved
Paid, not confirmedCustomerUsually immediate. Release stock, full refund of the sub-order's net, voucher policy applies
Confirmed / packingCustomerOften requires seller approval (they may already have packed)
Paid / confirmedSeller (out of stock)Refund, seller penalty metrics, possibly compensation voucher for the customer
Any pre-shipSystem (fraud, payment reversal)Cancel, refund or void, flag the account
Shipped—Not a cancellation: refused delivery or return flow

Concurrency example: the customer presses cancel while the seller hands the parcel to the carrier. Both transitions start from Confirmed. The conditional update lets exactly one win. If Shipped wins, the cancel request turns into "you can refuse delivery or request a return".

Returns and refunds (RMA)​

  • The refund amount comes from the stored line allocations: line net × returned quantity / ordered quantity, plus or minus shipping per policy.
  • Refund to the original method where possible (card refund, wallet credit), or to a platform wallet. Each refund has its own idempotency key and status (see unknown outcomes on the payments page).
  • Stock effect: restock as sellable, restock as B-grade, or write off. Each is an inventory adjustment with a reason.
  • Seller settlement: if the seller was already paid out, the refund becomes a seller receivable, deducted from the next payout. That's why many marketplaces hold payouts until the return window closes.

Order history and audit​

  • Status history table (append-only): sub_order_id, from_status, to_status, event, actor_type, actor_id, reason, occurred_at, request_id. This drives the customer timeline and support tools, and it's the audit record.
  • Event stream (OrderPaid, SubOrderShipped, RefundIssued…) for other services and analytics, published via the outbox (Transactional Outbox & CDC).
  • Read model for "My orders": the write model is sharded by order id, but customers query by user. Maintain a denormalized projection keyed by user (or shard the write DB by user id from the start). See Event-Driven Architecture, CQRS & Event Sourcing.
  • Archival: orders older than N months move to cheaper storage but stay queryable for customers, returns, disputes, tax and legal retention.
  • Event sourcing of orders is possible (state = fold of events), but most teams get the important benefits with state + history + outbox and avoid the cost of rebuilding projections.

Integrating with OMS, WMS and ERP​

Many retailers run an external OMS or ERP (SAP, Oracle, or a regional product), and many marketplaces integrate with 3PL warehouse systems and carrier platforms.

  • Status mapping: external systems have their own states and codes. Map them in the adapter into platform events, and reject or park unknown codes instead of guessing.
  • Idempotency both ways: send your sub-order id as the external reference, and deduplicate incoming updates by external event id or by (reference, status, timestamp).
  • Ordering and gaps: external updates can skip states (Packed arrives before Confirmed). Decide whether the machine allows that jump (often yes, with implied intermediate transitions recorded) or parks the update.
  • Retries and DLQ: with a replay console for operations, so stuck orders don't need database edits.
  • Reconciliation: a daily comparison of order states between systems (orders shipped in the WMS but not in the platform, or cancelled in the platform but still picked) catches lost messages. Same idea as Reconciliation & Settlement.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Explicit state machine (table-driven)Valid transitions are enforced, easy to audit, testableUpfront modeling, migrations when states changeAlways, for orders
Ad-hoc status updatesFast to startInvalid states, race bugs, unclear historyNever for money-related entities
Orchestrated saga in order serviceVisible progress, explicit compensationsOrder service becomes central, needs durabilityCore fulfilment flow
Choreographed eventsLoose couplingHard to trace and reason about end-to-endSide effects (notify, loyalty, analytics)
Workflow engine (e.g. Temporal-style)Durable timers, retries, visibility built inNew platform dependency, learning curveMany long-running flows with timers
State + history + outboxSimple queries, full auditHistory and state could diverge if not written atomicallyDefault
Full event sourcingComplete replayable history, temporal queriesProjection rebuilds, event versioning complexityStrong audit or replay needs, experienced team
Shard by order idEven distribution"My orders" needs a projectionVery high write volume
Shard by user id"My orders" is a local queryHot users (large B2B buyers), cross-user admin queriesConsumer platforms

In practice​

  • Rough numbers: an order typically produces a dozen or more status events over its life (payment, confirmation, packing, several tracking updates, delivery, completion), and tracking webhooks can outnumber orders several times over. Size the event pipeline accordingly.
  • SLAs as timers: seller confirmation deadlines, ship-by dates and return windows are business rules that drive automatic transitions and seller performance metrics.
  • Support tooling: agents need safe actions (cancel, refund, re-ship) that go through the same state machine and maker-checker for large refunds (see Compliance). They should never get raw DB access.

A table-driven transition with conditional update, history and outbox in one transaction:

package order

import (
"context"
"database/sql"
"errors"
"fmt"
)

type Status string
type Event string

const (
Paid Status = "PAID"
Confirmed Status = "CONFIRMED"
Packing Status = "PACKING"
Shipped Status = "SHIPPED"
Cancelled Status = "CANCELLED"
)

type key struct {
From Status
Event Event
}

var transitions = map[key]Status{
{Paid, "seller_confirm"}: Confirmed,
{Paid, "cancel"}: Cancelled,
{Confirmed, "start_packing"}: Packing,
{Confirmed, "cancel_approved"}: Cancelled,
{Packing, "handover"}: Shipped,
}

var (
ErrInvalidTransition = errors.New("invalid transition")
ErrConcurrentUpdate = errors.New("order changed concurrently")
)

type Actor struct {
Type, ID, Reason string
}

func Apply(ctx context.Context, db *sql.DB, subOrderID int64, ev Event, a Actor) (Status, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer tx.Rollback()

var from Status
if err := tx.QueryRowContext(ctx,
`SELECT status FROM sub_orders WHERE id = $1`, subOrderID).Scan(&from); err != nil {
return "", err
}
to, ok := transitions[key{from, ev}]
if !ok {
return from, fmt.Errorf("%w: %s on %s", ErrInvalidTransition, ev, from)
}

res, err := tx.ExecContext(ctx, `
UPDATE sub_orders SET status = $1, version = version + 1, updated_at = now()
WHERE id = $2 AND status = $3`, to, subOrderID, from)
if err != nil {
return "", err
}
if n, _ := res.RowsAffected(); n == 0 {
return "", ErrConcurrentUpdate // caller reloads and re-evaluates
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO sub_order_status_history
(sub_order_id, from_status, to_status, event, actor_type, actor_id, reason)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
subOrderID, from, to, ev, a.Type, a.ID, a.Reason); err != nil {
return "", err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO outbox (aggregate_id, type, payload)
VALUES ($1, $2, json_build_object('sub_order_id', $1::bigint, 'from', $3::text, 'to', $4::text))`,
subOrderID, "SubOrderStatusChanged", from, to); err != nil {
return "", err
}
return to, tx.Commit()
}

Common pitfalls​

  • Status as a free-form string updated from anywhere. Symptom: orders in impossible states (DELIVERED with no shipment), and nobody can say how they got there.
  • Unconditional status updates. Symptom: a late carrier webhook moves a delivered order back to "in transit", or a cancel and a ship both "succeed".
  • Recomputing discounts at refund time. Symptom: refunds that don't add up to what was paid, and vouchers refunded twice on partial returns.
  • Storing parent status independently of children. Symptom: the parent says "Completed" while one sub-order is still in return.
  • Timers held only in memory. Symptom: after a deploy, payment-timeout cancellations never fire and stock stays reserved.
  • Paying sellers before the return window closes, without a receivable mechanism. Symptom: refunds the platform can't recover.
  • Integration adapters that guess unknown external statuses. Symptom: orders marked shipped that never left the warehouse.

Interview angle​

  • Typical prompts: "Design an order management system", "What happens after payment?", "How do you handle a customer cancelling while the seller is shipping?", "How do you refund part of an order that used a voucher?"
  • A strong answer: a parent/sub-order/shipment model, an explicit state machine with conditional updates and history plus outbox in one transaction, amount allocation stored at creation, an orchestrated fulfilment saga with compensations, durable timers, return flows with seller settlement effects, a read model for order history, and an integration adapter with reconciliation.
  • Follow-ups: How do you shard orders? How do you migrate the state machine when adding a state? How do you prevent duplicate refunds? How do you handle a carrier marking delivered when the customer says otherwise?
  • Red flags: a single status column with no history, 2PC between order and payment, refund amounts computed from the current catalog price, ignoring concurrent actors. See E-commerce Order Platform.

Self-check​

1. Why persist transitions with a conditional update on the current status?

Several actors (customer, seller, carrier webhook, timers) can try to move the same order at the same time. WHERE status = :from makes the database pick exactly one winner. The loser sees zero rows updated, reloads, and re-evaluates against the new state, so the order can't take two incompatible paths.

2. Why allocate vouchers to order lines at creation instead of at refund time?

Promotion rules, prices and voucher terms change after the order is placed. Refunds, seller settlements and invoices must reflect what was actually agreed at purchase. Stored allocations make partial cancellations and returns simple arithmetic, keep the money consistent with the payment, and record who funded each discount.

3. A sub-order line can't be fulfilled after payment. List the saga steps.

Mark the line cancelled (state transition with history), release its inventory reservation, issue a partial refund for the line's allocated net amount with an idempotency key, apply the voucher policy (return it or not), adjust seller settlement, notify the customer, and record seller performance impact. If the sub-order has no remaining lines, transition the whole sub-order to cancelled.

4. How is the parent order's status determined?

Derive it from the sub-orders' states with explicit rules, e.g. all terminal → completed, any shipped and some not → partially shipped, all cancelled → cancelled. Compute it on change (or on read) rather than running an independent state machine, so it can't drift from the children.

5. Scenario: the 3PL WMS sends "SHIPPED" for a sub-order the platform has already cancelled. What do you do?

The adapter maps the event, and the state machine rejects Cancelled → Shipped. Raise an exception case instead of silently dropping it: the goods are physically moving, so operations must intercept the parcel or turn it into a return to sender, and the refund state has to be checked. The daily reconciliation between the WMS and the platform should also flag it.

6. Why might a marketplace hold seller payouts until the return window closes?

Refunds for returns have to be funded. If the seller has already been paid, the platform must claw back from future payouts, which fails if the seller has no future sales or leaves. Holding funds (or a reserve) until the window closes limits that credit risk.

🧠 Flashcards0/8 learned · 0 retries

Exercise​

Implement a sub-order state machine service:

  1. Postgres tables for parent orders, sub-orders, lines with adjustments, status history and outbox.
  2. A table-driven Apply function (like the one above) covering the full diagram, including returns.
  3. A durable timer mechanism (a timers table polled with FOR UPDATE SKIP LOCKED) for payment timeout, seller SLA and auto-complete.
  4. A test that fires cancel and handover concurrently 1,000 times and asserts exactly one wins each time and the history is consistent.
  5. A partial-return calculator from stored allocations, with a property test asserting the sum of all possible refunds never exceeds the amount paid.

Done when: tests pass under -race, every state change has exactly one history row and one outbox row, and the refund property holds for randomized orders.

Further reading​

  • Chris Richardson, Microservices Patterns — sagas, the order service example, semantic locks.
  • Vaughn Vernon, Implementing Domain-Driven Design — aggregates and domain events.
  • Martin Fowler, "Event Sourcing" and "Domain Event" articles (martinfowler.com).
  • Temporal / Cadence documentation — durable workflows and timers, for comparison with hand-built sagas.
  • Martin Kleppmann, Designing Data-Intensive Applications — derived data and keeping projections consistent.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).