← Back to System Design, page 4

system-design-0068 · Medium fresher

Design the checkout and inventory system for an e-commerce site with 5 million orders per day, so stock is never oversold and a failed payment does not lose the order.

At checkout, reserve stock with an atomic conditional decrement (only if available is at least the quantity), create the order in a pending state, then take payment with an idempotency key. On success, confirm the order and the reservation; on failure or timeout, release the reservation. These steps form a saga with compensations rather than one distributed transaction. 5 million orders per day is about 580 per second at a 10x peak.

Full answer

Requirements

Functional:

  • Add to cart, check out with an address and payment method, receive an order confirmation.
  • Stock levels per product and warehouse; reservations during checkout.
  • Cancel and refund.

Non-functional:

  • Never sell more units than exist (for normal products).
  • A user who clicks "Pay" twice is charged once.
  • The cart and product pages can be slightly stale; stock decisions cannot.

Capacity estimates

Assumptions: 5M orders per day, peak factor 10 during sales, 3 items per order.

  • Orders: 5M / 86,400 = about 58 per second; about 580 per second at peak.
  • Stock updates: 3 x 580 = about 1,740 reservations per second at peak, spread over many products.
  • One busy product may see hundreds of reservations per second during a sale, which is the real hot spot (see flash sale design for extreme cases).

API

POST /v1/carts/{id}/items {"sku": "TSHIRT-M-BLUE", "qty": 2} POST /v1/checkout Idempotency-Key: 9b2e... {"cart_id", "address_id", "payment_method_id"} -> 201 {"order_id": "o_5521", "status": "CONFIRMED"} or 409 {"error": "OUT_OF_STOCK", "sku": ...} POST /v1/orders/{id}/cancel

Data model

sql
CREATE TABLE inventory (
  sku        VARCHAR(40),
  warehouse  VARCHAR(10),
  on_hand    INT NOT NULL,
  reserved   INT NOT NULL DEFAULT 0,
  PRIMARY KEY (sku, warehouse),
  CHECK (reserved <= on_hand)
);
  • reservations: reservation_id, order_id, sku, warehouse, qty, status (held, committed, released), expires_at.
  • orders: order_id, user_id, items, amount, status, payment_id, idempotency_key (unique).

High-level design

mermaid
flowchart LR
  U[User] --> CO[Checkout service]
  CO --> INV[Inventory service]
  INV --> IDB[(Inventory DB)]
  CO --> ODB[(Orders DB)]
  CO --> PAY[Payment service]
  CO -- "order events" --> BUS[(Event bus)]
  BUS --> FUL[Fulfilment]
  BUS --> EMAIL[Email]
  EXP[Reservation expiry worker] --> INV

Checkout saga

  1. Check the idempotency key; return the earlier result if found.
  2. Reserve stock for each item: UPDATE inventory SET reserved = reserved + :q WHERE sku = :s AND warehouse = :w AND on_hand - reserved >= :q. If any update affects 0 rows, release earlier reservations and return out of stock.
  3. Create the order as PENDING_PAYMENT.
  4. Charge the payment with the order ID as the idempotency key.
  5. Success: mark the order CONFIRMED, commit reservations (decrement on_hand and reserved when shipped). Failure: mark the order PAYMENT_FAILED and release reservations.
  6. Reservations have an expiry; the worker releases any left behind by crashes.

Each step is idempotent, so the saga can be retried from any point.

Bottlenecks and trade-offs

  • Reserve at add-to-cart or at checkout? Reserving at checkout avoids stock being locked in abandoned carts; the cost is that a user may find an item gone at checkout.
  • Hot products make one row hot; split stock into several rows (buckets) and reserve from any bucket that has enough.
  • Payment timeouts keep the order pending until the payment status is known, rather than releasing stock and charging later.
  • Overselling on purpose is sometimes chosen for items that restock fast; that is a business decision, not a bug.
  • Cart and catalogue are cached and eventually consistent; only the inventory and order writes need strong consistency.

By level

Fresher: Explain that stock is checked and reduced in one safe step, and that the order waits for payment before it is confirmed. A fresher should know why a double click must not create two orders.

Mid: Write the reservation update, design the saga with compensations and expiry, and size the peak. Discuss when to reserve.

Senior: Cover hot rows with bucketed stock, payment timeouts, intentional overselling, multi-warehouse allocation and consistency boundaries. Expect clear failure handling at each step.

Key points

  • Reserve stock with an atomic conditional update
  • Order states move from pending to confirmed or failed
  • Saga with compensations instead of a distributed transaction
  • Idempotency key on checkout and payment
  • Reservation expiry cleans up after crashes

Common mistakes

  • Reading stock then writing it in two steps without a condition
  • Reserving at add-to-cart with no expiry
  • Releasing stock when a payment times out but may have succeeded
  • Using a distributed transaction across inventory, orders and payment

Follow-ups

  • How would you split an order across two warehouses?
  • How do you handle a return?
  • What changes for a flash sale with 100,000 units in 10 seconds?

Tips

  • Write the conditional update
  • Walk through the saga steps and compensations
  • Separate strong and eventual consistency areas

Evaluation rubric

  • Correct reservation logic
  • Saga with compensations and idempotency
  • Capacity math
  • Hot products and timeout handling