Commerce and money · Design 26

Design Amazon checkout

Design an Amazon-style cart and checkout in a 45-minute interview: inventory reservation vs overselling, an order saga with compensations, idempotency keys and flash sales.

AdvancedInterview priority: High55 min
On this page
  1. How to use this page
  2. 1. Clarify the requirements
  3. 2. Back-of-the-envelope estimates
  4. 3. API
  5. 4. Data model
  6. 5. High-level design
  7. 6. Deep dives
  8. 7. Bottlenecks, failures and monitoring
  9. 8. Follow-up questions
  10. Quiz

How to use this page

This page follows the order of a real system design interview. At each step there is a Your turn box: write your own answer first (it stays in your browser), then open ours and compare. Reading a finished design feels easy; producing one under time pressure is the skill you are practising.

PhaseTime in a 45-min interviewWhat you produce
1. Clarify requirements5 minFunctional list, non-functional targets, what's out of scope
2. Estimate5 minPage views/s, orders/s at peak, read/write ratio
3. API5 minProduct, cart, checkout, order calls
4. Data model5 minCatalog, cart, inventory, orders, outbox
5. High-level design10 minThe cached read path and the checkout saga
6. Deep dives10–15 minOverselling, the saga, idempotency, payments, flash sales
7. Wrap up2–3 minBottlenecks, failures, what you would monitor

Customers view products with price and stock, add them to a cart, and check out: reserve inventory, take payment, and create an order they can track. Skip search and recommendations, reviews, sellers’ tools, and warehouse fulfilment details.

1. Clarify the requirements

Your turn: scope it

The interviewer says: "Design Amazon's checkout." Write down your questions, 4–5 functional requirements, 4–5 non-functional requirements with targets, and what you'd leave out.

Compare with our answer

The questions that matter most: Is search in scope? One warehouse or many? Can we ever oversell? When is the card charged? Do we need to handle flash deals? Push search, recommendations and warehouse operations out; they are separate interviews.

A strong answer mentions: product page with stock · a cart that survives across devices · checkout that reserves stock, takes payment and creates an order · cancel before shipping · no overselling, no double charges, no lost orders · peak events at 10× normal.

Functional: what it must do

  • Product page: Details, price, “In stock”
  • Shopping cart: Add, remove, keep for days, across devices
  • Checkout: Address, shipping option, payment
  • Order created and tracked: Confirmed, shipped, delivered
  • Cancel / refund: Before shipping

Out of scope

Search and recommendationsReviewsSeller toolsWarehouse robotics

Non-functional: how well it must work

QualityTargetWhy
Product page latency< 100 msEvery 100 ms costs sales
Checkout correctnessNever oversell; never charge twice; never lose an orderMoney and stock
AvailabilityCart and checkout 99.99%Downtime = lost revenue
Peak handling10× normal on Prime Day / Black Friday
ConsistencyStrong for inventory and payments; eventual is fine for “In stock” badgesChoose per data type

2. Back-of-the-envelope estimates

Your turn: the numbers

100 M daily shoppers view 20 products each; 5% place an order; Prime Day peaks at 10× the average order rate. Work out product views/s, orders/s on average and at peak, and the ratio of views to orders.

Compare with our answer
  • Views: 100 M × 20 = 2 B a day ÷ 86,400 ≈ 23,000/s on average (and several times that at peak).
  • Orders: 100 M × 5% = 5 M a day ≈ 58/s average, ~580/s at a 10× peak.
  • Ratio: 20 views ÷ 0.05 orders = 400 views per order.
  • Each order touches 4–5 services (cart, inventory, payments, orders, events), so checkout does a few thousand internal calls a second at peak: modest, but each must be correct.

A strong answer mentions: reads outnumber orders by hundreds · peak factor · that order volume is small but every order matters · the split into a caching problem and a correctness problem.

Assumptions: daily shoppers 100 M; product views per shopper per day 20; shoppers who order (%) 5; peak vs average 10.

NumberEstimateWhy it matters
Product page views per second23.1 K / s≈ 23,000/s average: serve from caches and CDN.
Orders per second (avg)57.9 / s
Orders per second (peak)579 / s≈ 580/s: modest, but each order touches several services and must be exact.
Views per order400Reads outnumber orders by hundreds: optimise pages, protect checkout.
  • The read path (pages) and the write path (checkout) have completely different scale and correctness needs: design them separately.

The key insight: the product page is a caching problem and checkout is a correctness problem. Design them separately. Even at Prime Day peaks, a few hundred orders a second is well within what sharded SQL databases handle; what makes checkout hard is that it spans several services that can each fail.

3. API

Your turn: the API

Write the calls for the product page, the cart and checkout. Which call must carry an idempotency key, and what does it return if the same key arrives twice?

Compare with our answer

A strong answer mentions: a cached product read whose availability may be stale · cart add/remove keyed by user or anonymous session · one checkout call with a mandatory idempotency key that returns the same order for a repeated key · order status · cancel that triggers compensation (release stock, void or refund payment).

CallRequestResponseNotes
GET /v1/products/{id}–{ title, price, images, availability }Cached; availability may be slightly stale
POST /v1/cart/items{ productId, qty }200 { cart }Cart keyed by user (or anonymous session)
POST /v1/checkout{ cartId, addressId, shippingOption, paymentMethodId }201 { orderId, status }Idempotency-Key header is mandatory
GET /v1/orders/{id}–{ status, items, tracking }
POST /v1/orders/{id}/cancel–200Triggers refund + inventory release

The checkout call is one request from the client, even though it starts many steps on the server. The client should never orchestrate "reserve, then pay, then create" itself: a phone that loses signal halfway would leave stock reserved and nobody responsible for finishing or undoing it. The Idempotency-Key makes retrying the whole call safe; how the key is stored and matched is covered in duplicates and idempotency.

4. Data model

Your turn: the tables

Where do you keep products, carts, stock counts and orders? Which needs strong consistency, and which needs to be always writeable?

Compare with our answer

A strong answer mentions: catalog in a document or key-value store behind caches · carts in a highly available key-value store keyed by user · inventory in a strongly consistent store with available and reserved counts and a version · orders in SQL with a status · reservations with an expiry · an outbox table next to orders.

catalog Document store (DynamoDB) + cache + CDN

  • product_id
  • title, attributes{}, images[]
  • price (from pricing service)

Flexible attributes per product type, read-heavy, key lookups.

carts Key-value store (DynamoDB)

  • user_id → items[{productId, qty, addedAt}]
  • updated_at, TTL

Highly available writes; one item per user; Amazon’s Dynamo paper was literally about the cart.

inventory Strongly consistent SQL (sharded by product / warehouse)

  • product_id, warehouse_id
  • available, reserved
  • version

Conditional decrements must be exact under concurrency.

orders SQL (sharded by customer)

  • order_id, customer_id, status
  • items, totals, address
  • payment_id, created_at

Transactional state machine with money attached.

outbox Table in the orders DB

  • event_id, type, payload, published

Events written in the same transaction as the order, then published.

Two details worth adding:

  • Inventory is per product per warehouse. The number shown to shoppers is the sellable quantity: on hand minus reserved minus a small safety buffer for damaged or miscounted items. Reservations are rows with an expiry (reservation_id, product_id, warehouse_id, qty, expires_at), so an abandoned checkout gives its stock back automatically.
  • The cart does not reserve stock. Carts are abandoned most of the time; reserving on "add to cart" would lock up stock for days. The cart is a wish list; reservation happens at checkout.
The Dynamo shopping cart

Amazon's 2007 Dynamo paper was built around the cart: it must accept "add to cart" even during network partitions. When two replicas accept different writes, Dynamo keeps both versions (tracked with vector clocks) and the cart merges them on read by taking the union of items. The known side effect: an item you deleted on one replica can reappear after a merge. That was judged better than losing an "add". Modern DynamoDB is a different system with single-leader partitions and optional strongly consistent reads, but the trade-off is still a good interview story.

5. High-level design

Your turn: draw it

Sketch the read path for a product page and the write path for checkout. Who coordinates checkout, and what happens if the card is declined after stock was reserved?

Compare with our answer

Compare with the figure. The things people forget: the orchestrator owning the checkout's progress (and persisting it), compensations for every step, and that the availability badge comes from a cached snapshot, not the inventory database.

The architecture, then a product page from caches

  1. Reads and writes are split. Product pages come from the CDN and catalog caches. Checkout is an orchestrator that runs a saga across the cart, inventory, payments and orders services, and an event stream drives fulfilment and notifications.
  2. A product page is assembled from cached data: static parts from the CDN, details from the catalog cache. The availability badge comes from a cached snapshot of inventory, which may be seconds old, and that’s fine.
ComponentWhat it does
CDN + catalog cacheFast product pages; slightly stale availability is fine
Cart serviceHighly available key-value store per user
Checkout orchestratorRuns the saga; stores its progress so it can resume after a crash
Inventory serviceExact, conditional reservations with expiry
PaymentsAuthorise at checkout, capture at shipping; idempotent
Orders + outboxOrder state machine; events published reliably
Fulfilment / notificationsReact to order events asynchronously

Checkout as a saga, and what happens when payment fails

  1. Checkout is a saga: a sequence of local steps, each with an undo. Reserve the stock, authorise the payment, create the order. If any step fails, the earlier steps are undone with compensating actions, like releasing the reservation.
  2. If the card is declined after stock was reserved, the saga runs its compensating action: release the reservation, so the item goes back on sale, and tell the shopper.

Trace checkout out loud:

  1. The client sends POST /checkout with an idempotency key. The orchestrator records a new saga (key, cart, step = started) in its own database. If the key already exists, it returns that saga's result instead.
  2. Reserve stock for each line with a conditional update; record step = reserved.
  3. Authorise the payment (hold the money), passing an idempotency key to the payment provider; record step = authorised.
  4. Create the order and an order.placed outbox row in one transaction; record step = done; return the order ID.
  5. If step 3 fails, run the compensation for step 2 (release the reservation) and tell the shopper to try another card.

6. Deep dives

Your turn: the hard parts

Before reading on: how do you stop two shoppers buying the last unit? How do you make reserve, pay and create order all-or-nothing across three services? What happens on Prime Day when 100,000 people want one deal with 1,000 units?

Compare with our answer

A strong answer mentions:

  • An atomic conditional decrement (or reservation insert) that fails cleanly when stock is short; reservations expire.
  • A saga with persisted state, idempotent steps and compensations, rather than two-phase commit.
  • Idempotency keys at the checkout API and at the payment provider.
  • Authorise at checkout, capture at shipment.
  • Flash sales: a waiting room or admission gate, per-customer limits, stock split across counters, and the database as the final check.

Never oversell the last item

Reserve with an atomic conditional update

  1. Deep dive: overselling. Reserve stock with an atomic conditional update that only succeeds if enough is left.

The naive code reads the stock, checks it, and writes it back. Two checkouts that interleave both read available = 1, both pass the check, both write 0: two orders for one unit. The fix is to make the check part of the write:

UPDATE inventory
   SET available = available - 2, reserved = reserved + 2
 WHERE product_id = 'B0123' AND warehouse_id = 'FRA1' AND available >= 2;
-- 1 row affected: reserved.  0 rows: not enough stock, try another warehouse or fail.

The database applies the two updates one after the other on that row, and the second sees the new value. The same race and its other fixes are covered in contention and double booking.

When to take stockOversell riskCatch
At add to cartNoneAbandoned carts lock stock for days
At checkout, as a reservation with an expiryNoneReservations must be released on failure or timeout
At payment success onlyYes, between "in stock" and paymentCustomers pay for items that are gone
Never: sell freely, fix laterYesCancellations and apology emails; acceptable only for restockable goods

Choice: reserve at checkout with a 10–15 minute expiry; confirm the reservation when the order is created; a background job releases expired ones.

The saga: all-or-nothing across services

Inventory, payments and orders each have their own database. A single ACID transaction across them would need two-phase commit (a coordinator asks every participant to prepare and lock, then tells all to commit), which blocks everyone if the coordinator or one participant is slow, and most payment providers don't take part in it anyway.

A saga (compared with two-phase commit in transactions across services) instead runs a sequence of local transactions, each with a compensating action (a business-level undo) used if a later step fails:

StepActionCompensation
1Reserve stockRelease the reservation
2Authorise paymentVoid the authorisation
3Create order + outbox eventCancel the order (emits order.cancelled)

Rules that make it work:

  • Persist the saga's progress after each step, so if the orchestrator crashes, another instance resumes from the last recorded step.
  • Make every step and compensation idempotent (keyed by saga ID), because resuming may repeat a step whose result wasn't recorded.
  • Compensations must eventually succeed: retry them with backoff; if they keep failing, alert a human. A compensation cannot itself "fail and give up".
  • Put the riskiest reversible step early. Reserve stock first (cheap to undo), payment second; the order is created last because it triggers shipping, which is hard to undo.
Orchestration or choreography?

In orchestration (chosen), one coordinator calls each step and owns the state machine: the whole flow is in one place and easy to monitor. In choreography, services react to each other's events (inventory hears checkout.started, emits stock.reserved; payments hears that, and so on). It has fewer moving parts for two or three steps, but the flow is spread across services and hard to follow or change. For checkout, with its compensations and timeouts, orchestration is the usual answer. Workflow engines such as Temporal or AWS Step Functions provide the persisted state and retries.

Idempotency: one click, one order

Retries happen at every layer: the shopper double-clicks, the phone retries after a timeout, the load balancer retries a dropped connection, the orchestrator retries a slow payment call. Every one of them must be safe.

  • Checkout API: the client sends a key (a UUID created when the checkout page loads). The orchestrator stores key → saga ID with a unique constraint. A second request with the same key returns the first saga's status or result, never a new order.
  • Payment provider: the orchestrator passes its own key (for example saga-8812-authorise) so a retried authorisation is recognised by the provider and not taken twice.
  • Event consumers: fulfilment de-duplicates by event ID, because the outbox relay publishes at least once.

Authorise now, capture at shipping

Authorising at checkout guarantees the money without moving it. Capturing when the item ships means an order cancelled or found to be out of stock in the warehouse needs only a void, not a refund (refunds cost fees and take days). For a multi-item order that ships in parts, capture per shipment.

Flash sales: 100,000 people, 1,000 units

A Lightning Deal opens at 12:00. One inventory row now takes every checkout. Row-level locking serialises the updates, so throughput on that row is bounded by how fast one transaction commits (often a few hundred to a few thousand per second, much less if it waits on replication), and requests pile up and time out.

OptionHowCatch
Admission gateA waiting room or token bucket lets in only a little more than the stock size (say 2,000 shoppers for 1,000 units)Most people are told "sold out" in the queue rather than at checkout; needs a fair queue
Split the stock into buckets10 rows of 100 units; each checkout picks a random bucketThe last units are scattered: one bucket is empty while another has 3 left, so retry other buckets
Pre-gate in RedisDECR deal:42 (atomic); only requests that get a value ≥ 0 go on to the database reservationRedis is a fast filter, not the truth: after a failover it can let a few extra through, which the database then rejects
Per-customer limitOne unit per account, checked at reservationBots with many accounts; needs bot defence

Choice: a gate in front (waiting room or Redis counter) so only about as many shoppers as units reach checkout, bucketed counters if the row is still hot, a per-customer limit, and the database conditional update as the final word. The Ticketmaster design takes the waiting room further.

7. Bottlenecks, failures and monitoring

Scaling bottlenecks

BottleneckFix
Product page trafficCDN, catalog caches, pre-rendered pages; inventory badge from a cached snapshot
Prime Day spikeLoad tests, pre-scaling, queueing checkouts, shedding non-essential features (recommendations)
Hot item (a deal everyone wants)Split its stock into several counters (buckets) to spread contention
Cart availabilityDynamo-style always-writeable store; merge on conflict

When things fail

FailureWhat happens
Payment service downSaga pauses; reservations held briefly then released; shopper told to retry
Orchestrator crashes mid-sagaSaga state is persisted; another instance resumes from the last step
Inventory reservation not confirmedReservation expires automatically and stock returns
Event published twiceConsumers de-duplicate by event id

What to monitor

Checkout success rateSaga step latency and failuresOversell incidents (should be 0)Payment authorisation rateOutbox lagProduct page p99

8. Follow-up questions

Your turn: the interviewer pushes

Answer in order: 1) The orchestrator authorised the payment, then crashed before recording it. What happens on restart? 2) The price changed between the product page and checkout. What should happen? 3) The payment provider is down for 20 minutes on Black Friday. What do you do?

Compare with our answer

A strong answer mentions:

  1. It resumes from the last recorded step (reserved) and repeats the authorisation with the same idempotency key; the provider returns the existing authorisation, so there is no double hold.
  2. Checkout prices from the source of truth, not the client; if it differs from what was shown, stop and ask the shopper to confirm the new price.
  3. Accept orders as "pending payment" with short reservations extended, retry authorisation with the same keys, fail over to a second provider, and stop non-essential features to protect checkout.
How do you handle flash deals with very limited stock?

Put buyers through a waiting room/queue, pre-split stock into buckets, and reserve with short expiries (see the Ticketmaster design).

How does the cart survive a database conflict?

Dynamo-style: keep conflicting versions and merge (union of items) when read; the original Dynamo paper is about exactly this.

How do prices stay consistent?

The price shown is quoted with a version; checkout re-validates and shows a change if it moved.

Amazon checkout on one page
  • Numbers: ~23 K product views/s, ~58 orders/s average, ~580/s at peak; ~400 views per order.
  • Read path: CDN + catalog cache; "In stock" from a cached snapshot (seconds stale is fine).
  • Cart: always-writeable key-value store; no stock reserved; re-price at checkout.
  • Oversell: UPDATE … SET available = available − n WHERE available >= n; reservation with expiry, released by a sweeper.
  • Saga: reserve → authorise → create order (+ outbox); compensations release → void → cancel; state persisted; steps idempotent; compensations retried until done.
  • No isolation: reserved counts are a semantic lock; shoppers can see intermediate states.
  • Idempotency: checkout key → saga ID (unique); same key to the payment provider; consumers de-dup by event ID.
  • Payments: authorise at checkout, capture at shipment.
  • Flash sales: admission gate, Redis pre-gate, bucketed stock, per-customer limit, database as the final check.
Mock interviewPractise it as a mock interview: scope, size and the big decisionsOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Two shoppers check out the last unit at the same moment. Which approach prevents overselling without slowing every checkout?

2. Why does the cart not reserve stock when an item is added?

3. Payment is declined after stock was reserved. What does the checkout saga do?

4. The orchestrator crashes after authorising payment but before recording that step. What keeps the restart safe?

5. Why choose a saga over two-phase commit for checkout?

6. A Lightning Deal has 1,000 units and 100,000 shoppers at 12:00. What is the main bottleneck without special handling?

7. A team uses a Redis counter as the only record of a flash deal's remaining stock. What is the risk?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.