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.
On this page
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.
| Phase | Time in a 45-min interview | What you produce |
|---|---|---|
| 1. Clarify requirements | 5 min | Functional list, non-functional targets, what's out of scope |
| 2. Estimate | 5 min | Page views/s, orders/s at peak, read/write ratio |
| 3. API | 5 min | Product, cart, checkout, order calls |
| 4. Data model | 5 min | Catalog, cart, inventory, orders, outbox |
| 5. High-level design | 10 min | The cached read path and the checkout saga |
| 6. Deep dives | 10–15 min | Overselling, the saga, idempotency, payments, flash sales |
| 7. Wrap up | 2–3 min | Bottlenecks, 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
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
| Quality | Target | Why |
|---|---|---|
| Product page latency | < 100 ms | Every 100 ms costs sales |
| Checkout correctness | Never oversell; never charge twice; never lose an order | Money and stock |
| Availability | Cart and checkout 99.99% | Downtime = lost revenue |
| Peak handling | 10× normal on Prime Day / Black Friday | |
| Consistency | Strong for inventory and payments; eventual is fine for “In stock” badges | Choose per data type |
2. Back-of-the-envelope estimates
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.
| Number | Estimate | Why it matters |
|---|---|---|
| Product page views per second | 23.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 order | 400 | Reads 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
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).
| Call | Request | Response | Notes |
|---|---|---|---|
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 | – | 200 | Triggers 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
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_idtitle, 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_idavailable, reservedversion
Conditional decrements must be exact under concurrency.
orders SQL (sharded by customer)
order_id, customer_id, statusitems, totals, addresspayment_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
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
- 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.
- 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.
| Component | What it does |
|---|---|
| CDN + catalog cache | Fast product pages; slightly stale availability is fine |
| Cart service | Highly available key-value store per user |
| Checkout orchestrator | Runs the saga; stores its progress so it can resume after a crash |
| Inventory service | Exact, conditional reservations with expiry |
| Payments | Authorise at checkout, capture at shipping; idempotent |
| Orders + outbox | Order state machine; events published reliably |
| Fulfilment / notifications | React to order events asynchronously |
Checkout as a saga, and what happens when payment fails
- 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.
- 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:
- The client sends
POST /checkoutwith 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. - Reserve stock for each line with a conditional update; record
step = reserved. - Authorise the payment (hold the money), passing an idempotency key to the payment provider; record
step = authorised. - Create the order and an
order.placedoutbox row in one transaction; recordstep = done; return the order ID. - If step 3 fails, run the compensation for step 2 (release the reservation) and tell the shopper to try another card.
6. Deep dives
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
- 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 stock | Oversell risk | Catch |
|---|---|---|
| At add to cart | None | Abandoned carts lock stock for days |
| At checkout, as a reservation with an expiry | None | Reservations must be released on failure or timeout |
| At payment success only | Yes, between "in stock" and payment | Customers pay for items that are gone |
| Never: sell freely, fix later | Yes | Cancellations 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:
| Step | Action | Compensation |
|---|---|---|
| 1 | Reserve stock | Release the reservation |
| 2 | Authorise payment | Void the authorisation |
| 3 | Create order + outbox event | Cancel 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 IDwith 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.
| Option | How | Catch |
|---|---|---|
| Admission gate | A 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 buckets | 10 rows of 100 units; each checkout picks a random bucket | The last units are scattered: one bucket is empty while another has 3 left, so retry other buckets |
| Pre-gate in Redis | DECR deal:42 (atomic); only requests that get a value ≥ 0 go on to the database reservation | Redis is a fast filter, not the truth: after a failover it can let a few extra through, which the database then rejects |
| Per-customer limit | One unit per account, checked at reservation | Bots 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
| Bottleneck | Fix |
|---|---|
| Product page traffic | CDN, catalog caches, pre-rendered pages; inventory badge from a cached snapshot |
| Prime Day spike | Load 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 availability | Dynamo-style always-writeable store; merge on conflict |
When things fail
| Failure | What happens |
|---|---|
| Payment service down | Saga pauses; reservations held briefly then released; shopper told to retry |
| Orchestrator crashes mid-saga | Saga state is persisted; another instance resumes from the last step |
| Inventory reservation not confirmed | Reservation expires automatically and stock returns |
| Event published twice | Consumers 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
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:
- 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. - 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.
- 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.
- 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.
1. Two shoppers check out the last unit at the same moment. Which approach prevents overselling without slowing every checkout?
The check and the change happen in one atomic statement, so the second update affects zero rows. Read-then-write races; a table lock serialises the whole store.
2. Why does the cart not reserve stock when an item is added?
Reserving at add-to-cart would make popular items look sold out. Reserve at checkout with a short expiry instead.
3. Payment is declined after stock was reserved. What does the checkout saga do?
Each saga step is already committed locally, so there is nothing to roll back; the saga undoes it with a compensation.
4. The orchestrator crashes after authorising payment but before recording that step. What keeps the restart safe?
Resuming may repeat a step whose result wasn't saved; idempotent steps make the repeat harmless.
5. Why choose a saga over two-phase commit for checkout?
2PC is atomic but blocking and needs every participant (including payment providers) to support it. Sagas trade isolation for independence.
6. A Lightning Deal has 1,000 units and 100,000 shoppers at 12:00. What is the main bottleneck without special handling?
One hot row serialises all reservations. Gate admissions, split stock into buckets and use the database as the final check.
7. A team uses a Redis counter as the only record of a flash deal's remaining stock. What is the risk?
Redis replicates asynchronously. As a pre-gate it's fine; the durable conditional update must remain the source of truth.
Score 60% or more and the lesson is marked complete.