System design interview: design an e-commerce checkout

An e-commerce checkout turns a cart into a paid order: it prices the items, reserves stock, takes payment and creates the order, and it has to do that correctly even when services fail halfway through. The interview usually centers on inventory (how not to oversell a popular item) and on coordinating several services without a distributed transaction.

By Published 8 min read

1. Clarify the requirements

"Design Amazon" is far too wide for 45 minutes. Agree that you will design the path from cart to confirmed order, and treat catalog search and fulfillment as neighbors you only connect to.

  • Functional: add and remove cart items; see a price breakdown with promotions, shipping and tax; choose an address and delivery option; pay; receive an order confirmation; cancel before shipping.
  • Non-functional: never charge without creating an order and never create a paid order without stock; the checkout page responds quickly; the system survives a flash sale with many times normal traffic; prices shown at the final step are the prices charged.
  • Out of scope unless asked: recommendations, seller onboarding, warehouse picking and shipping logistics, returns processing.

2. Estimate the scale

Back-of-envelope estimate for a large online store (assumed figures)
QuantityAssumptionResult
Orders on a normal day5 millionabout 58 a second on average
Cart writesabout 20 cart changes per orderaround 1,200 writes a second on average
Flash sale peak50 times the normal order rate for an hourabout 2,900 checkouts a second
One hot item10,000 units sold in a few minutestens of decrements a second on a single stock record, with many more failed attempts
Order recordabout 5 KB with lines and addressesabout 25 GB of new orders a day
Back-of-envelope estimate for a large online store (assumed figures). Scroll sideways on a small screen.

Overall volume is moderate for a sharded database. The difficulty is concentration: during a sale, thousands of people fight over the same few stock records, and every component in the checkout path sees its peak at the same moment.

3. Define the API

PUT  /v1/carts/{cartId}/items/{sku}     { quantity }               -> 200 { cart }
POST /v1/checkouts                       { cartId, addressId }      -> 201 { checkoutId, quote, reservationExpiresAt }
PUT  /v1/checkouts/{id}/delivery         { option }                 -> 200 { quote }
POST /v1/checkouts/{id}/place            { paymentMethodId, quoteVersion, idempotencyKey }
     -> 201 { orderId, status: "confirmed" } | 409 quote changed | 410 reservation expired
POST /v1/orders/{id}/cancel                                          -> 200 { status }
The quote is the contract: the order is created from a stored quote, not from numbers the client sends.

The client sends quoteVersion when placing the order. If anything changed (a promotion ended, a price was updated, stock moved), the server answers 409 with the new quote and the customer confirms again. The client never sends amounts the server trusts.

4. Sketch the data model

Each service owns its tables
ServiceTableKey fields
Cartcart_itemcart_id, sku, quantity, added_at (key-value or document store is fine)
Checkoutcheckoutcheckout_id, cart snapshot, quote (lines, discounts, tax, shipping, total), quote_version, status, saga step
Inventorystock and reservationsku, warehouse, on_hand, reserved; reservation: checkout_id, sku, qty, expires_at, state
Orderorder and order_lineorder_id, customer, totals, status; per line: sku, qty, unit price, allocated discount, tax
Each service owns its tables. Scroll sideways on a small screen.

5. Pricing you can defend line by line

Do all money math in integer minor units (cents, pence, yen) and never in floating point. Promotions apply in a fixed order: item discounts, then order-level coupons, then shipping, then tax on the discounted amounts where the jurisdiction requires it. Tax rules vary by country and region, so most stores call a tax service or vendor rather than encoding rules themselves.

One detail shows real experience: an order-level coupon must be split across the lines it applies to. Partial refunds, per-line tax and returns all need to know how much of the discount each line received, and the parts must add up to the coupon exactly.

// Split an order-level discount across lines in proportion to their value,
// in integer cents, so the parts always add up to the whole discount.
function allocateDiscount(lineCents, discountCents) {
  const total = lineCents.reduce((a, b) => a + b, 0);
  if (total === 0) return lineCents.map(() => 0);
  const exact = lineCents.map((c) => (c * discountCents) / total);
  const parts = exact.map(Math.floor);
  let left = discountCents - parts.reduce((a, b) => a + b, 0);
  // hand leftover cents to the lines with the largest remainders
  const order = exact
    .map((x, i) => [x - Math.floor(x), i])
    .sort((a, b) => b[0] - a[0] || a[1] - b[1]);
  for (let k = 0; left > 0; k++, left--) parts[order[k][1]] += 1;
  return parts;
}

allocateDiscount([1999, 4999, 999], 1000); // [250, 625, 125]
Split an order discount across lines in integer cents (largest-remainder method). Tested with node on random orders.

6. Inventory: reserve, then commit or release

  1. Reserve at checkout startCreate a reservation for each line with an expiry (say 10 minutes) and increase reserved with a conditional update: only if on_hand - reserved >= qty. If any line fails, release the others and tell the customer which item ran out.
  2. Commit on paymentWhen the order is placed, mark reservations committed and move the quantity from reserved to sold in the same local transaction.
  3. Release on failure or timeoutA failed payment, an abandoned checkout or an expired reservation returns the quantity. A sweeper finds expired reservations; the reserve step also ignores them, so stock frees up even if the sweeper lags.

Hot items during a sale. A single stock row updated thousands of times a second turns into a lock queue. Split the item's available stock into several sub-counters (for example 20 buckets of 500 units), pick a bucket at random for each reservation and try another when one runs dry. Contention drops by roughly the number of buckets. For extreme drops, put stock counters in an in-memory store with atomic decrements, admit buyers through a queue (the waiting room described in the ticket booking walk-through), and write the durable record after the decrement succeeds.

7. Place the order as a saga

Cart, inventory, payment and order are separate services with separate databases, so one ACID transaction across them is not available. A checkout orchestrator runs the steps in order, saves its progress after each one, and knows the undo for every step.

Saga steps and their compensations
StepActionIf a later step fails
1Validate the quote version and the reservationsNothing to undo
2Authorize payment with an idempotency keyVoid the authorization
3Commit inventory reservationsReturn the quantities to available stock
4Create the order record, status confirmedMark the order cancelled (never delete it)
5Capture payment (now or at shipment)Refund
6Publish OrderConfirmed; clear the cartRetried until delivered; consumers are idempotent
Saga steps and their compensations. Scroll sideways on a small screen.

Because the orchestrator stores the current step, a crash after step 2 resumes at step 3 on restart instead of charging again; every call also carries the same idempotency key. Events leave through an outbox table written in the same transaction as the state change. Authorization, capture, the ledger and reconciliation are covered in the payment system walk-through; here, treat payment as one service with authorize, capture, void and refund calls.

8. The architecture

  1. Clients
    • Web and mobile store
  2. Edge
    • CDN for product pages
    • API gateway
    • Waiting room (sales only)
  3. Checkout
    • Cart
    • Checkout orchestrator
    • Pricing and promotions
    • Tax
  4. Domain services
    • Inventory
    • Payment
    • Order
  5. Async
    • Outbox relay and event log
    • Email
    • Fulfillment
    • Analytics
Checkout path from cart to confirmed order. Web and mobile clients reach an API gateway that authenticates them and applies rate limits. The cart service keeps carts in a key-value store. The checkout orchestrator builds a quote using the pricing and promotion service and a tax service, reserves stock through the inventory service, then runs the saga: payment authorization, inventory commit, order creation and capture. Each service has its own database. State changes go through outbox tables to an event log, read by email, fulfillment and analytics consumers. A waiting-room queue sits in front of checkout during flash sales.

Authentication, rate limits and request routing at the front are the job of an API gateway; during a sale, per-user limits there stop bots from hammering the place-order endpoint.

9. What breaks, and trade-offs to discuss

Failure modes worth naming
FailureEffectMitigation
Payment times outUnknown whether the card was authorizedQuery the payment service with the same key before deciding; never retry with a new key
Orchestrator crashes mid-sagaStock reserved, payment authorized, no orderResume from the stored step; a recovery job scans stuck checkouts
Price changed between cart and payCustomer charged a price they did not seeQuote versioning and a 409 that shows the new total
Bots during a limited dropReal customers lose out, stock tied up in reservationsPer-account limits, a waiting room, short reservations, purchase caps per customer
Failure modes worth naming. Scroll sideways on a small screen.
  • Reserve at add-to-cart, at checkout, or at payment. Earlier reservations protect the customer but let idle carts lock stock; reserving at checkout with an expiry is the usual middle ground.
  • Orchestration or choreography. A central orchestrator is easier to reason about and debug; services reacting to each other's events avoid a central component but make the flow harder to follow.
  • Authorize then capture later, or capture at once. Capturing at shipment avoids refunds for unshippable orders; capturing immediately is simpler for digital goods.
  • Strict or relaxed stock checks. Strict reservations prevent overselling at a throughput cost; relaxed checks sell faster and handle the rare oversell with an apology and a refund.

10. How to talk through it in the interview

Fictional example

The oversell follow-up during a flash sale
Interviewer
You have 5,000 units of a new console and 200,000 people waiting. How do you avoid overselling?
Candidate
Admit buyers through a waiting room at a rate checkout can handle. Split the 5,000 units into buckets so reservations do not queue on one row, and make each reservation a conditional decrement with a ten-minute expiry. Payment failures and timeouts release units back into a bucket.
Interviewer
And if the payment service is slow that day?
Candidate
Reservations expire before stock is lost for long, and the saga keeps its step, so a slow authorization is retried with the same key instead of creating a second charge.
  • Say "saga with compensations" and then show the table; naming it without the undo steps earns little.
  • Keep payment as a black box unless asked; point to idempotency and move on.
  • Use the flash-sale numbers from your estimate to justify buckets and the waiting room.

Practicing this design with Natively

The saga and the oversell questions are good drills because the follow-ups chain together. Run a mock over a call and keep Natively open on your computer: it builds a transcript as the conversation happens and can suggest talking points when you ask, for instance the compensation you left out. A screenshot of your whiteboard lets it point out missing pieces such as the outbox, and you can ask it to draw the saga as a flow. Read back the notes to see whether you explained why there is no distributed transaction.

Questions people ask

How do you prevent overselling in an e-commerce system design?

Reserve stock when checkout starts with a conditional update that only succeeds if enough units are free, give the reservation an expiry, and convert it to a sale when payment succeeds. For a very popular item, split its stock into several counters so reservations do not all queue on one database row.

What is a saga in an e-commerce checkout?

It is a sequence of local steps across services (authorize payment, commit stock, create the order, capture payment) where each step has a compensating action such as voiding the authorization. An orchestrator stores which step it reached, so after a crash it resumes or undoes instead of repeating a charge.

Why should prices be calculated on the server at checkout?

The server applies the current prices, promotions, shipping and tax, stores the result as a versioned quote and creates the order from that quote. The client only confirms a version number, so it cannot alter amounts, and a changed price produces a clear 409 asking the customer to confirm the new total.

How do you handle a flash sale in a checkout design?

Put a waiting room in front of checkout to admit buyers at a rate the system can serve, apply per-account limits at the gateway, use short stock reservations spread across several counters, and keep product pages on a CDN so browsing traffic never reaches the checkout services.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP