Skip to content

Design Amazon's Shopping Cart and Checkout

A system design interview walkthrough for an Amazon-style shopping cart and checkout, covering cart storage, inventory reservation and the order saga.

Advanced24 minUpdated 2 December 2026

Before this: Microservices Architecture, Distributed Transactions (SAGA Pattern), Idempotency

"Design Amazon" is too big for forty-five minutes, so a good candidate narrows it in the first two. The part worth designing is the path from adding an item to a cart to a confirmed order: the cart, the checkout and the order that results.

That path crosses several services (cart, pricing, inventory, payment, orders, shipping), and each owns its own data. The interviewer is testing whether you know what that costs. You cannot wrap five services in one database transaction, so what happens when payment succeeds and the order write fails? Or stock is reserved and the card is declined? The answer is an order saga: a sequence of local steps with an undo for each, driven by a durable state machine.

Search and recommendations are out of scope here, as is the flash-sale surge (Design a Flash Sale). The money details are in Design a Payment System. Background: microservices, distributed transactions and idempotency.

Clarify the requirements

Functional requirements:

  1. Add, change and remove items in a cart, from any device, signed in or not.
  2. View the cart with current prices and availability.
  3. Check out: confirm address and shipping, pay, and receive an order confirmation.
  4. View order status and history.
  5. Cancel an order before it ships.

Out of scope, said aloud: product search, recommendations, reviews, returns and refunds, the warehouse systems, and the internals of payment processing.

Non-functional requirements: these shape the design.

  • The cart is always writable. A shopper who cannot add an item loses a sale, so the cart favors availability over strict consistency.
  • An order is placed exactly once, effectively. A shopper who double-clicks or retries gets one order and one charge.
  • Never promise stock you do not have. Overselling creates canceled orders and unhappy customers, so inventory is reserved before payment is taken.
  • No step may be half done and forgotten. Every failure ends in a completed order or a clean undo.
  • Checkout is slower and rarer than cart browsing, so it can be more careful.

Estimate the scale

Assume 50 million daily active users, each making 4 cart changes and viewing pages that read the cart 20 times a day, and 5 million orders a day.

Cart writes: 50M × 4 = 200M a day ÷ 86,400 ≈ 2,300 per second, about 7,000 at peak.

Cart reads: 50M × 20 = 1 billion a day ≈ 11,600 per second, about 35,000 at peak.

Orders: 5M ÷ 86,400 ≈ 58 per second, 174 at peak (3×), and say 600 during a big sale (10×).

Cart storage: keep 50 million active carts at about 2 KB each: 100 GB. Carts are small, keyed by user or session, and expire.

Order storage: 5M × 3 KB = 15 GB a day, about 27 TB over five years.

"Carts are a high-volume key-value workload: 11,600 reads a second against 100 GB, which fits a key-value store with the lowest latency. Orders are only 58 a second, which is low volume with high stakes. So I will optimize the cart for availability and speed, and the order for correctness."

The capacity estimator reproduces the order rate (writes are orders per user per day) and the order storage.

API and data model

PUT    /v1/cart/items/{sku}      { quantity }        -> cart
GET    /v1/cart                                      -> items, prices, availability
POST   /v1/checkout              { cartVersion, addressId, paymentMethodId, checkoutId }
                                 (checkoutId is the idempotency key)
GET    /v1/orders/{id}                               -> status, items, tracking
POST   /v1/orders/{id}/cancel
cart       (owner_id PK)  items{sku -> qty, added_at}, version, updated_at
inventory  (sku PK)       on_hand, reserved
reservation(order_id, sku PK)  qty, expires_at
orders     (id PK)        customer_id, status, total, checkout_id UNIQUE
saga       (order_id PK)  step, state, attempts, compensating

The non-obvious choice is checkout_id with a unique constraint on orders. The client creates it when the shopper opens the checkout page, and every retry reuses it, so a duplicate attempt finds the existing order.

High-level design

The slice worth running is checkout: a gateway, a checkout service that reads the cart and reserves stock, the order store, and a queue that hands the confirmed order to fulfillment workers.

Checkout reads the cart, reserves inventory, writes the order and queues it for fulfillment workers that finish the order asynchronously.clientsgatewaycheckout apicart and stockorder storefulfillment queuefulfillment workers
Checkout reads the cart, reserves inventory, writes the order and queues it for fulfillment workers that finish the order asynchronously.
  • Clients reach the checkout service through a gateway.
  • The checkout service reads the cart and stock, writes the order, and queues it for fulfillment workers.
Describe this diagram

Components

  • clients (Client)
  • gateway (API gateway)
  • checkout api (Service)
  • cart and stock (DynamoDB)
  • order store (PostgreSQL)
  • fulfillment queue (SQS queue)
  • fulfillment workers (Service)

Connections

  • clients sends to gateway
  • gateway sends to checkout api
  • checkout api sends to cart and stock
  • checkout api sends to order store
  • checkout api sends to fulfillment queue
  • fulfillment queue sends to fulfillment workers

Run it, then try a sale-sized load and see which store saturates first.

The cart path: the client writes to a key-value store keyed by user (or by an anonymous session id that merges into the user's cart at sign-in). A read returns the items, and the price and availability are looked up fresh, not stored in the cart.

The checkout path: the checkout service starts a saga for the order. It re-prices the cart, reserves stock, authorizes payment, writes the order and publishes an event. Everything after that, such as picking, packing, shipping and capturing payment, is asynchronous and driven by events.

The interesting problem: placing an order across services

Inventory, payment and orders are separate services with separate databases. A shopper clicks Place Order, and all of it must either happen or be undone.

Approach A: one distributed transaction

Use two-phase commit across the inventory, payment and order databases.

Good: one atomic outcome, simple to reason about on paper.

Bad: the payment provider is an external system and does not take part in your commit protocol. Locks are held across services for the whole duration, so one slow participant stalls checkout for everyone. It also couples the availability of every service to the lowest one. This is why large systems avoid it, as the distributed transactions lesson explains.

Approach B: choreography

Each service reacts to events: OrderPlaced makes inventory reserve stock and emit StockReserved, which makes payment charge and emit PaymentAuthorized, which makes orders confirm.

Good: loosely coupled, no central coordinator, easy to add a new listener.

Bad: the flow lives in nobody's code. When an order is stuck, you must reconstruct what happened from several services' logs, and compensation logic for each failure case spreads across all of them.

Approach C: an orchestrated saga

A checkout orchestrator owns a persisted state machine for the order and calls each step, recording progress after each:

  1. Re-price the cart and confirm the total with the shopper's expectation.
  2. Reserve inventory with an expiry. Undo: release the reservation.
  3. Authorize payment (a hold on the card, not a charge). Undo: void the authorization.
  4. Create the order as confirmed. This is the point of no return, so it must be retried until it succeeds.
  5. Publish OrderConfirmed. Fulfillment starts, and payment is captured at the point the business chooses, often when items ship.

Good: the whole flow is in one place, it is visible (the saga row says exactly which step an order is in), and each failure maps to a named undo.

Bad: the orchestrator is another component to run and make highly available, and every step and compensation must be idempotent.

The recommended answer is C. Two rules make it sound. First, order the steps so that the easiest to undo come first and the hardest last: releasing a reservation is trivial, voiding an authorization is routine, and an order that exists is visible to the customer. Second, make every step and every compensation idempotent, keyed by the order id, so the orchestrator can crash and resume without doing anything twice.

Conceptual diagramdeclinedfails: retry, do not undoStart: checkoutIdRe-price cartReserve inventoryAuthorize paymentCreate order: point of no returnPublish OrderConfirmedRelease reservationRetry order creation
Diagram, as text
  • Start: checkoutId leads to Re-price cart
  • Re-price cart leads to Reserve inventory
  • Reserve inventory leads to Authorize payment
  • Authorize payment leads to Create order: point of no return
  • Create order: point of no return leads to Publish OrderConfirmed
  • Authorize payment leads to Release reservation (declined)
  • Create order: point of no return leads to Retry order creation (fails: retry, do not undo)

The second decision: the cart's consistency and what a cart holds

Availability over consistency for the cart. The shopper adds an item on a phone while a replica is unreachable, and later adds another on a laptop. A strict, single-leader store would reject one of the writes during a failure. A key-value store that keeps the cart writable on any replica accepts both, and merges the two versions when they meet. The Dynamo paper used the shopping cart as its motivating example for exactly this: the merge is a union of items, so an add is never lost, with the known side effect that an item the shopper deleted can occasionally reappear. For a cart, that is the right trade, because a reappearing item is cheap to remove and a refused add is a lost sale.

What the cart stores. Store SKU, quantity and when it was added. Do not store the price as the source of truth, and do not reserve stock for items in the cart. Prices change, and holding inventory for every cart would let people who never buy lock up stock. Look up the price when the cart is shown, and at checkout compare the total with what the shopper last saw: if it changed, show the new total and ask again.

When to reserve stock. Reserve at checkout, with an expiry of a few minutes, not at add-to-cart. For items with very limited stock, mention that a short-lived reservation at the moment of checkout is the compromise, and refer to Design a Flash Sale for the extreme case.

Anonymous carts. Key the cart by an anonymous session id with an expiry, and merge it into the user's cart at sign-in by union, taking the larger quantity of any duplicated SKU.

Bottlenecks and failures

Payment provider slow or down. The saga waits with a timeout, and on failure the reservation is released and the shopper sees a clear message. Never leave a reservation held without an expiry.

Crash after authorizing payment. The saga row says payment succeeded and the order is not yet created. On restart the orchestrator resumes at step 4 and retries it, because the authorization is already in hand. The idempotency key on the authorization prevents a second hold.

Duplicate submissions. A double click sends two checkout requests with the same checkoutId. The unique constraint returns the existing order for the second one.

Hot SKUs. A popular item's inventory row is updated by every checkout. Use a conditional decrement (reserved + qty <= on_hand) so the database decides in one atomic step, and split the counter across rows if one SKU becomes the bottleneck.

Inventory drift. Reservations that never confirm or expire leave reserved too high. A job that reconciles reservations against orders and releases expired ones keeps the counter honest.

Compensation fails. A void that errors must be retried until it succeeds, and a human alert is raised after a limit. Record every attempt in the saga so you can see what is owed.

What if the order queue is down? The order is already confirmed in the database. The event is written through an outbox, so fulfillment starts when the queue returns. Nothing is lost, and shoppers still see a confirmed order.

Trade-offs to name aloud

  • Orchestration over choreography: one component to run and keep available, in exchange for visible, debuggable flow.
  • An always-writable cart: deleted items may reappear after a merge, in exchange for never refusing an add.
  • Reserve at checkout, not at add-to-cart: stock is not tied up by browsers, in exchange for the occasional "sold out" at the last step.
  • Authorize now, capture later: protects the shopper from being charged for items that cannot ship, in exchange for tracking an authorization's lifetime.

What interviewers listen for

  • A working answer: a cart store, an order table, and a checkout that reserves stock, takes payment and creates the order.
  • A strong answer: explains why one transaction across services does not work, uses a saga with compensations, makes steps idempotent with a checkout id, and keeps the cart writable.
  • A standout answer: orders the steps by how hard they are to undo, identifies the point of no return and retries past it, adds a sweeper for stuck sagas, re-prices at checkout, and reconciles inventory drift.

Check your understanding

Common mistakes

Treating checkout as one transaction. It spans services and an external payment provider. Name the saga.

Reserving stock when an item is added to the cart. Browsers who never buy would hold inventory hostage. Reserve at checkout, with an expiry.

Storing prices in the cart as truth. Prices change. Re-price at checkout and show the shopper any difference.

Non-idempotent steps. A retried "authorize payment" that charges twice is worse than a failed order. Key every step by the order id.

Forgetting what happens after the point of no return. Once payment is authorized, create the order and retry until it exists. Do not compensate your way out of a step that can simply be retried.

No way to find stuck orders. A crashed orchestrator leaves sagas in the middle. A sweeper with a time limit per step is part of the design.

Practice

After a deploy, 200 orders show payment authorized but no order exists. Customers have holds on their cards. How do you find and fix them, and prevent a repeat?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Use the saga table as the record of what step each order reached.

Show a strong answer

Find them. Query sagas where the payment step is complete and the order step is not, older than a few minutes. Each row has the order id, the authorization id and the step, so the list is exact, with no guessing.

Finish them. For each, resume at the order-creation step. It is idempotent on the checkout id, so rerunning it is safe. If an order cannot be created (for example, the item became unavailable after the reservation expired), compensate: void the authorization and notify the customer.

Prevent a repeat. Find why the step failed after the deploy, such as a schema change the orchestrator did not expect, and add a test that drives the saga through a crash after each step. Add an alert on sagas older than their expected time in any step.

The pattern worth keeping: a saga's persisted state turns "something went wrong" into a precise worklist, and the sweeper turns that worklist into automation.

A mobile client loses connection after tapping Place Order and retries 10 seconds later. The first request may or may not have succeeded. What does your design guarantee?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Think about what identifies the shopper's intent and where the duplicate is caught.

Show a strong answer

One intent, one key. The client generated checkoutId when the checkout page opened, and both requests carry it. The server stores the order with a unique constraint on that id.

The server's behavior. If the first request completed, the retry finds the existing order and returns it, with no second reservation and no second authorization. If the first is still running, the retry can wait for it or return the saga's current state. If the first never arrived, the retry simply runs the saga.

Make every step safe too. The inventory reservation is keyed by order id and the payment authorization carries an idempotency key derived from it, so even if the orchestrator restarts mid-way, no step is done twice.

The pattern worth keeping: the client creates the identity of an intent once, and the server uses it at every layer to make a retry harmless. Say "effectively once", not "exactly once".

Key takeaways

  • Narrow the question: cart to confirmed order is the interesting path.
  • Checkout is a saga, not a distributed transaction: local steps, each with an undo, recorded in a durable state machine.
  • Order steps by how hard they are to undo, and retry past the point of no return.
  • Make every step and compensation idempotent, keyed by the order id, with a unique checkout id at the front.
  • The cart favors availability and merges by union, while orders favor correctness.
  • Reserve stock at checkout with an expiry, and re-price at the same moment.

Further reading

  • Giuseppe DeCandia et al., "Dynamo: Amazon's highly available key-value store", SOSP (2007): includes the shopping cart as its motivating example and the merge behavior described above.
  • Hector Garcia-Molina and Kenneth Salem, "Sagas", ACM SIGMOD (1987): the original long-lived transaction with compensations.
  • Pat Helland, "Life beyond Distributed Transactions: an Apostate's Opinion", CIDR (2007).

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track