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 Evin JohnPublished 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
| Quantity | Assumption | Result |
|---|---|---|
| Orders on a normal day | 5 million | about 58 a second on average |
| Cart writes | about 20 cart changes per order | around 1,200 writes a second on average |
| Flash sale peak | 50 times the normal order rate for an hour | about 2,900 checkouts a second |
| One hot item | 10,000 units sold in a few minutes | tens of decrements a second on a single stock record, with many more failed attempts |
| Order record | about 5 KB with lines and addresses | about 25 GB of new orders a day |
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 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
| Service | Table | Key fields |
|---|---|---|
| Cart | cart_item | cart_id, sku, quantity, added_at (key-value or document store is fine) |
| Checkout | checkout | checkout_id, cart snapshot, quote (lines, discounts, tax, shipping, total), quote_version, status, saga step |
| Inventory | stock and reservation | sku, warehouse, on_hand, reserved; reservation: checkout_id, sku, qty, expires_at, state |
| Order | order and order_line | order_id, customer, totals, status; per line: sku, qty, unit price, allocated discount, tax |
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]6. Inventory: reserve, then commit or release
- Reserve at checkout startCreate a reservation for each line with an expiry (say 10 minutes) and increase
reservedwith a conditional update: only ifon_hand - reserved >= qty. If any line fails, release the others and tell the customer which item ran out. - Commit on paymentWhen the order is placed, mark reservations committed and move the quantity from reserved to sold in the same local transaction.
- 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.
| Step | Action | If a later step fails |
|---|---|---|
| 1 | Validate the quote version and the reservations | Nothing to undo |
| 2 | Authorize payment with an idempotency key | Void the authorization |
| 3 | Commit inventory reservations | Return the quantities to available stock |
| 4 | Create the order record, status confirmed | Mark the order cancelled (never delete it) |
| 5 | Capture payment (now or at shipment) | Refund |
| 6 | Publish OrderConfirmed; clear the cart | Retried until delivered; consumers are idempotent |
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
- Clients
- Web and mobile store
- Edge
- CDN for product pages
- API gateway
- Waiting room (sales only)
- Checkout
- Cart
- Checkout orchestrator
- Pricing and promotions
- Tax
- Domain services
- Inventory
- Payment
- Order
- Async
- Outbox relay and event log
- Fulfillment
- Analytics
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 | Effect | Mitigation |
|---|---|---|
| Payment times out | Unknown whether the card was authorized | Query the payment service with the same key before deciding; never retry with a new key |
| Orchestrator crashes mid-saga | Stock reserved, payment authorized, no order | Resume from the stored step; a recovery job scans stuck checkouts |
| Price changed between cart and pay | Customer charged a price they did not see | Quote versioning and a 409 that shows the new total |
| Bots during a limited drop | Real customers lose out, stock tied up in reservations | Per-account limits, a waiting room, short reservations, purchase caps per customer |
- 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
- 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.
