Design a Multi-Step Order Processing Pipeline
System DesignModel answerLast updated
Design the backend system that moves a customer order through reservation, payment, fulfillment, and shipping while handling failures and partial states gracefully.
Background
You are designing the backend for an e-commerce platform. When a customer places an order, several independent services need to coordinate: inventory must be reserved, payment must be collected, a warehouse must pick and pack the items, and a carrier must be notified. Each of these is owned by a separate team and runs on a separate data store.
Task
Walk through the complete lifecycle of an order — from the moment it is placed to the moment it is delivered or cancelled — covering:
- State machine — what states an order moves through, what triggers each transition, and what invariants must hold at each step
- Service decomposition — how you split responsibility across services and what each service owns
- Data flow — how services communicate (synchronous calls, async events, or both) and where the authoritative record lives
- Failure recovery — what happens when inventory is reserved but payment fails, or payment is captured but the warehouse never acknowledges the job
- Duplicate and out-of-order messages — how you ensure that replaying an event does not double-charge a customer or double-reserve stock
- Customer-facing status — how a customer sees a single coherent order status even when internal state is scattered across services
Constraints and Assumptions
- Inventory and payment run on separate databases; no distributed transaction spans both.
- The message bus may deliver events more than once, out of order, or with arbitrary delay.
- The system must support at least: reservation expiry, payment failure, partial fulfilment (only some items are in stock), cancellation before shipment, and post-shipment return initiation.
- Peak load is on the order of tens of thousands of new orders per minute during sale events.
What Is Expected
Describe your architecture in prose and/or diagrams (ASCII is fine). Justify the key design choices and call out the trade-offs you are consciously accepting. You do not need to write production code, but pseudocode or API sketches are welcome where they sharpen the explanation.
Cover the clarifying questions you would ask before committing to a design, then proceed with reasonable assumptions.
Hints
Hint 1
Start with the state machine before talking about services — every architectural decision should be traceable back to a valid state transition. Draw it out: PENDING → RESERVED → PAYMENT_CAPTURED → IN_FULFILLMENT → SHIPPED → DELIVERED, plus the cancellation and failure branches.
Hint 2
Because inventory and payment can't share a transaction, you need the Saga pattern. Think through whether you want choreography (services react to each other's events) or orchestration (a central workflow service drives the steps). Both work — but pick one and defend it, don't try to mix them without a reason.
Hint 3
Idempotency is the main reliability tool here. Every state-changing operation should accept a stable idempotency key (typically the order ID plus a step name) so that retrying a failed step produces the same outcome rather than a double charge or double reservation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions First
Before designing anything, a strong candidate asks:
- When is inventory committed? Is a soft reservation at order placement enough, or does physical commitment happen only when the warehouse starts picking? How long can a reservation live before it expires and stock is returned to the pool?
- Payment timing — is the card authorized at placement and captured at shipment, or charged immediately? This changes the compensation story significantly.
- Partial fulfillment policy — if 3 of 5 items are in stock, do we ship what we have, hold the order, or cancel it? Does the customer choose?
- Return and cancellation windows — can an order be cancelled after shipment starts? Who initiates a return and what triggers a refund?
Assuming: soft inventory reservation at placement with a 30-minute TTL, auth-at-placement / capture-at-shipment for payment, configurable partial fulfillment (default: ship available items, backorder the rest).
Order State Machine
The authoritative order state lives in a dedicated Order Service database. Every other service publishes events; Order Service consumes them and advances its own state machine. This gives customers one place to query.
PENDING
→ RESERVATION_FAILED (inventory unavailable)
→ RESERVED
→ PAYMENT_FAILED (auth declined)
→ PAYMENT_AUTHORIZED
→ CANCELLED (customer or timeout cancels before pick)
→ IN_FULFILLMENT
→ PARTIALLY_SHIPPED
→ SHIPPED
→ DELIVERED
→ RETURN_INITIATED → REFUNDED
Each transition is triggered by a domain event. The Order Service applies transitions idempotently: receiving the same event twice leaves state unchanged if the transition was already applied.
Service Decomposition
| Service | Owns | Communicates via |
|---|---|---|
| Order Service | Order state, customer view | REST (write), events (read) |
| Inventory Service | Stock levels, reservations | Sync for reservation, events for TTL expiry |
| Payment Service | Charges, refunds | Sync call + async confirmation event |
| Fulfillment Service | Warehouse jobs, picking | Consumes events, publishes job status |
| Shipment Service | Carrier labels, tracking | Consumes fulfillment-complete events |
| Notification Service | Emails, push alerts | Consumes all status-change events |
Saga: Orchestration Over Choreography
With five services and compensating actions on every failure path, pure choreography (each service reacts to the previous service's event) becomes very hard to reason about. Instead, a workflow orchestrator (AWS Step Functions, Temporal, or a hand-rolled saga table) drives the happy path and compensation explicitly:
start_order_saga(order_id):
1. call InventoryService.reserve(order_id, items, ttl=30m)
on failure → emit OrderReservationFailed, done
2. call PaymentService.authorize(order_id, amount)
on failure → call InventoryService.release(order_id), emit OrderPaymentFailed, done
3. emit OrderAuthorized → Fulfillment picks it up
4. on FulfillmentComplete event → call PaymentService.capture(order_id)
5. on CaptureFailed → emit OrderPaymentCaptureFailed (alert ops; rare path)
6. call ShipmentService.createLabel(order_id)
7. on ShipmentCreated → advance order to SHIPPED
The saga table stores the current step and is the source of truth for the orchestrator. If the orchestrator crashes mid-saga, it resumes from the last durable step.
Idempotency
Every state-changing operation accepts a stable idempotency key, typically {order_id}:{step_name}. Services store processed keys in a table with a short TTL (e.g. 24 hours). On retry:
- Inventory reservation with the same key returns the existing reservation rather than decrementing stock again.
- Payment authorization with the same key returns the existing auth token rather than re-charging.
This handles the common case of the orchestrator retrying after a timeout where the downstream call actually succeeded.
Handling Delayed and Out-of-Order Events
Events carry a sequence_number (or Lamport timestamp) and order_version. The Order Service drops any event whose implied transition is not valid from the current state. For example, a FulfillmentComplete arriving before OrderAuthorized is stored in a pending event buffer for that order and re-evaluated when state advances. A small redelivery window (e.g., 5 minutes) handles most real-world out-of-order cases; anything older is flagged for manual review.
Failure Recovery and Compensation
Reservation held, payment fails: The orchestrator calls InventoryService.release(order_id). Because the release call is idempotent, retrying it is safe even if a timeout made the first attempt ambiguous.
Payment captured, warehouse never ACKs: The saga has a deadline on the fulfillment step. After N minutes with no FulfillmentAcknowledged event, the orchestrator re-sends the job creation message (idempotent on job ID). Ops dashboards surface orders stuck in IN_FULFILLMENT beyond SLA.
Shipment label created, carrier confirmation delayed: The order stays in SHIPPED (not DELIVERED) until the carrier webhook fires. A background reconciliation job polls the carrier API for orders older than 24 hours with no delivery confirmation.
Customer-Facing Status
Order Service maps its internal state to a small set of human-readable statuses: Processing, Confirmed, Preparing your order, On its way, Delivered, Cancelled, Return in progress. The mapping is a simple lookup table — internal states that are transient or operational (e.g., PAYMENT_AUTHORIZED vs IN_FULFILLMENT) collapse to the same customer-visible label. This decouples internal state richness from UX simplicity.
Scalability Notes
At tens of thousands of orders per minute, the bottlenecks are typically inventory reservation contention and the saga orchestrator throughput. Mitigations:
- Inventory: use optimistic locking with version counters, and pre-aggregate available stock into a Redis counter for fast reservation checks before hitting the authoritative DB.
- Orchestrator: shard the saga table by
order_id mod Nso multiple orchestrator instances process disjoint shards in parallel. - Events: use a log-based broker (Kafka or Kinesis) with per-order keyed partitioning to preserve order within a single order's event stream.
Common Mistakes to Avoid
- Using a global distributed transaction (2PC) across inventory and payment — this creates tight coupling and is a liveness risk.
- No idempotency keys — leads to duplicate charges under retry, which is catastrophic.
- Choreography without explicit saga state — when a failure happens three steps in, it is very hard to know what has and hasn't been compensated.
- Exposing internal state directly to customers — every internal refactor breaks the customer-facing API if they share the same enum.