Catalog, search, cart, stock, checkout and orders for millions of shoppers, with no overselling and no lost orders.
“Design an e-commerce system like Amazon.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Scoping an umbrella prompt | “E-commerce” is ten systems in one sentence. A strong candidate picks the flows to design (browse, cart, checkout, orders, stock), names the ones to leave out (search ranking, recommendations, payments), and says so out loud before drawing anything. |
| Putting consistency where it matters | A product page may be a few seconds stale. Stock, orders and money may not. The whole design is deciding which parts are allowed to be wrong, and which one decides. |
| Stock without overselling | Reserve at add-to-cart and abandoned carts lock stock. Check at payment and you oversell. The interviewer wants the middle path: a short, expiring reservation at checkout, and a plan for a hot item. |
| Multi-step orders across services | Order, stock, payment and shipping each have their own service and database. You cannot run one transaction across them. The answer is a saga with compensations and idempotency keys on every step. |
| Surviving the big sale day | Black Friday is ten to twenty times a normal day. The candidate should know what to cache, what to queue, what to turn off first, and why autoscaling alone does not fix a hot row. |
We design the shopping path: browse a product, add it to a cart, check out, get an order, and watch it ship. Browsing is read-heavy and may be a little stale, so it is cached hard. Stock and orders are small but must be exact, so they live in services with real transactions. The two meet in a checkout saga.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 5 | Scope aggressively: which flows, what is out, the stock rule, and the peak. |
| 2. Estimate | 3 | Page views, orders and cart operations per second; catalog and order storage; reservation rows in flight. |
| 3. API and data | 5 | Product, cart and checkout calls; products, inventory, cart and order tables. |
| 4. High-level design | 8 | Edge and cache, catalog, cart, inventory, order saga, events. |
| 5. Deep dives | 14 | Product page at scale, inventory without overselling, checkout saga, order lifecycle, peak day. |
| 6. Scale and failures | 7 | Stock drift, payment unknowns, a slow service, and what to switch off. |
| 7. Wrap up | 3 | Recap, trade-offs, and what to build next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Which flows do you want me to design: browsing and search, the cart, checkout, orders, fulfilment, recommendations, reviews, sellers? | An umbrella prompt cannot be covered in 45 minutes. Choosing the scope is the first thing a senior candidate does, and it shows judgement. | Browse a product, cart, checkout, orders and stock. Search, recommendations and payments are separate topics. | We design five parts and link the rest. This is the scope statement we repeat at the end. |
| Is it one seller (a retailer) or a marketplace with many sellers? | A marketplace changes who owns stock, how money is split and how orders are routed. | One retailer with its own warehouses. Marketplace is an extension we discuss at the end. | Inventory is owned by us. Payouts and split payments stay out of the core design. |
| What must never happen? | It sets which parts need strong consistency and which can be stale. | Never oversell an item, never lose an order, never charge a customer without an order record. | Stock, order and payment steps are strongly consistent. Pages, search and badges may be stale. |
| How big is it, and how big is the peak? | It decides what we cache, shard and queue. | 50 million daily users, 300 million products, 1 million orders a day, and a sale day of 10 to 20 times that. | About 12 orders a second normally and a few hundred at peak. Reads dominate, so caching is the main lever. |
| When should stock be set aside: when the item is added to the cart, or at checkout? | This is the most-asked design question here. Each answer has a clear cost. | Not at add-to-cart. Set it aside when checkout starts, for a short time. | A reservation table with an expiry. Carts hold no stock. |
| May we ever sell something we do not have (backorder or preorder)? | It is a business rule that changes the stock check. | Not by default. A per-item backorder flag can allow it later. | The stock check has an optional allowed-negative limit, off by default. |
| Do we need exactly the right price and stock on the product page? | This decides what we may cache. | No. A few seconds stale is fine, and the final check happens at checkout. | The page is cached. Checkout re-reads price and stock from the sources of truth. |
| How many warehouses, and does it matter which one ships? | Several warehouses make stock a per-warehouse number and add an allocation step. | Several. Prefer the nearest one with stock. | Inventory is keyed by (item, warehouse), and allocation picks a warehouse at reservation time. |
| Single region or global? How available must checkout be? | Two regions that both sell the last unit will sell it twice. | Users everywhere. Checkout 99.95% available, with one home region per customer. | Orders and carts are homed to a region. The catalog is replicated to all. |
| Assumption | Value |
|---|---|
| Daily users | 50 million (all numbers here are illustrative assumptions) |
| Products (SKUs) | 300 million, about 5 KB of metadata each, 10 images of 200 KB |
| Orders per day | 1 million, about 5 KB per order plus items and events |
| Product page views | 500 million a day, with a peak of about 100,000 a second |
| Sale-day peak for orders | 20 times the average |
| Cart operations | 4 per daily user per day, peak 10 times the average |
| Checkout takes | about 3 minutes (180 seconds) from start to payment |
| Items per order | 3 on average, 8 events per order |
| Warehouses per item | 3, with about 50 bytes per inventory row |
| What | Maths | Result |
|---|---|---|
| Average orders per second | 1,000,000 ÷ 86,400 | about 12 per second |
| Sale-day peak orders | 12 × 20 | about 230 per second |
| Average page views per second | 500,000,000 ÷ 86,400 | about 5,800 per second (100,000 at peak, 17 times) |
| Reads that miss the cache at a 98% hit rate | 100,000 × 2% | 2,000 per second (1,000 at 99%) |
| Catalog metadata | 300,000,000 × 5 KB | 1.5 TB (fits in memory across a cache cluster) |
| Product images | 300,000,000 × 10 × 200 KB | 600 TB, in object storage behind a CDN |
| Cart operations per second | 50,000,000 × 4 ÷ 86,400, then × 10 | about 2,300 average, 23,000 at peak |
| Active carts in memory | 50,000,000 × 1 KB | 50 GB (150 GB with 3 copies) |
| Order storage | 1,000,000 × 5 KB, then × 365 | 5 GB a day, about 1.8 TB a year (5.5 TB with 3 copies) |
| Inventory rows | 300,000,000 × 3 warehouses × 50 B | 900 million rows, about 45 GB |
| Events published | 1,000,000 × 8, then ÷ 86,400 and × 20 | about 93 a second on average, about 1,900 at peak |
| Stock reservation writes at peak | 230 orders × 3 items | about 700 writes per second (small) |
| Reservations open at once (3 minute checkout) | 230 × 180 s × 3 items | about 124,000 rows (a 15 minute limit would allow about 620,000) |
| One hot item on sale day | 10,000 buyers in 2 seconds ÷ 2 | 5,000 attempts a second on one row, against about 1,000 a row can take |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| GET | /v1/products/{id} | none | 200 { title, images, price, badge: IN_STOCK | LOW | OUT, variants } | From cache and CDN, a few seconds stale. The badge is a hint. Checkout re-reads price and stock from the sources of truth. |
| PUT | /v1/cart/items/{sku} | { quantity } | 200 { cart } | Idempotent: it sets the quantity, it does not add to it. Holds no stock. Works for guests (cookie) and merges into the account at login. |
| POST | /v1/checkout | Idempotency-Key header + { cartId, addressId, paymentMethodToken } | 202 { orderId, status: PENDING } then 200 when settled | Starts the saga. A retry with the same key returns the same order. Prices in the cart are re-checked here, and a difference is shown to the buyer before charging. |
| GET | /v1/orders/{id} | none | 200 { status, items, address, totals, events } | The buyer sees their own order right after placing it (read-your-writes). Status comes from the order service, not from a webhook. |
| POST | /v1/orders/{id}/cancel | Idempotency-Key | 200 or 409 when already shipped | A compensation: releases stock and voids or refunds. Only legal from certain states. |
| POST | (internal) /inventory/reservations | { orderId, lines: [{ sku, qty }], ttlSeconds } | 201 { reservationId, allocations } or 409 { short: [sku] } | All lines or none. Keyed by orderId, so a retry returns the same reservation. |
| inventory (one row per sku and warehouse) | Type | Why it is there |
|---|---|---|
| sku, warehouse_id | ids | The key. Stock is counted per warehouse. |
| on_hand | int | Physical units, changed by receipts, picks and cycle counts. |
| reserved | int | Units set aside for open checkouts. The conditional update keeps reserved <= on_hand. |
| version, updated_at | int, timestamp | Optimistic concurrency, and the data for drift checks. |
| reservations and carts | Key fields | Why |
|---|---|---|
| reservations | order_id, sku, warehouse_id, qty, expires_at, state (HELD, CONSUMED, RELEASED) | One row per line. The sweeper releases HELD rows past expires_at. Unique on (order_id, sku) so a retry is a no-op. |
| carts | user_id or cookie, items [{sku, qty, price_seen}], updated_at, expires_at | A key-value document with a time to live. No stock is held. price_seen lets checkout show a price change. |
| orders | order_id, user_id, status, items (price at purchase), address snapshot, totals, version, idempotency_key (unique) | The order keeps copies of price and address, so later changes cannot rewrite history. |
| order_events and outbox | order_id, seq, type, payload, published | An append-only history, and the rows a relay publishes to the event bus. |
BEGIN; UPDATE inventory SET reserved = reserved + :qty, version = version + 1 WHERE sku = :sku AND warehouse_id = :wh AND on_hand - reserved >= :qty; -- 0 rows changed: not enough stock here INSERT INTO reservations (order_id, sku, warehouse_id, qty, expires_at, state) VALUES (:order, :sku, :wh, :qty, now() + interval '15 minutes', 'HELD'); -- every line in the order is done in this one transaction (sorted by sku to avoid deadlocks). -- if any line changes 0 rows, ROLLBACK and answer 409 with the short items. COMMIT;
| Component | What it does |
|---|---|
| CDN and edge | Serves images and static page parts, and caches product documents for a short time. Takes most of the 100,000 page views a second. |
| API gateway | Authenticates, rate-limits and sheds load. On a bad day it drops optional calls (recommendations, reviews) first. |
| Catalog service and product cache | Owns product documents. A denormalised document (title, images, attributes) is cached. Price and the stock badge are fetched separately with a short life. |
| Cart service | A key-value document per user with a time to live. Holds no stock. Guest carts merge into the account at login. |
| Inventory service | The source of truth for stock. Reserves, releases and consumes units with conditional updates, per SKU and warehouse. |
| Order service | Owns the order state machine and runs the checkout saga: create, reserve, pay, confirm, with compensations. |
| Payment service (external) | Takes the payment with an idempotency key. We treat it as a service that can time out. See Design a Payment System. |
| Outbox, event bus and consumers | Publish order and stock events at least once. Fulfilment, notifications, search and analytics consume them idempotently. |
| Reservation sweeper | Releases reservations past their expiry. Correctness does not depend on it, because the stock check ignores expired rows. |
The problem: Product pages are about 99.5 percent of the traffic and they change rarely, but price and stock change often and must not look wrong for long. A viral item can send tens of thousands of requests a second to one key. A page that rebuilds on every miss will melt the catalog database.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Render from the database every time | Join products, prices, images and stock on each request. | Always fresh. Simplest. | 100,000 views a second would need an enormous database, and one popular item becomes a hot row. |
| Cache the whole page | Cache the finished HTML or JSON for each product for a minute. | Fast and cheap. A CDN can do it. | A price or stock change must wait for the cache life, or you purge the whole page. One changing field makes the whole page stale. |
| Denormalised document plus small fragments | Cache one product document (title, images, attributes) with a long life. Fetch price and stock badge as separate small values with a short life, and combine them in the page. | The big part is cached for a long time. The parts that change are tiny and cheap to refresh. | More requests per page, and a short window where document and price disagree. |
| Push updates into the cache | On a change event, rewrite the cache entry (a read model built with CQRS) instead of waiting for it to expire. | Fresh within a second or two, and the database is read only on rebuilds. | More machinery: an event stream, a builder and a way to rebuild the whole cache. |
Most of a product page never changes between purchases, so it belongs in a long-lived cache. Price and stock do change, so they get their own small cache entries with a life of a few seconds. A change to a price rewrites a few bytes, not a whole page. The read model is built from change events (CQRS style), so the catalog database is only touched when something actually changes, and a lost cache can be rebuilt from it.
The trouble spots are stampedes and hot keys. When a popular entry expires, thousands of requests miss at once, so we coalesce them (one rebuild, the others wait), add a little random jitter to lifetimes, and serve slightly stale data while a refresh runs. For one very hot item, we copy the entry into a small local cache on every web server, or store several copies under different keys and pick one at random.
| Part of the page | How fresh | Where it lives |
|---|---|---|
| Images and descriptions | Hours or days | Object storage and a CDN, with versioned file names so a change is a new URL |
| Product document | Seconds to minutes after a change event | Product cache (sharded memory store), rebuilt from the catalog database |
| Price | A few seconds | Small cache entry, set by the pricing service on every change |
| Stock badge (in stock, low, out) | A few seconds | Small cache entry derived from inventory events, and only a hint |
| The real price and the real stock | Exact | Read from the pricing and inventory services at checkout only |
The problem: The invariant is: reserved plus sold never exceeds what is on the shelf. When stock is set aside matters a lot. Too early and abandoned carts lock stock. Too late and two buyers pay for the last unit. A flash sale on one item then puts thousands of requests a second on a single row.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Take stock off at add-to-cart | Decrement the count when the item goes into the cart. | Never oversells. Simple. | Most carts are abandoned. Real buyers are told sold out while stock sits in dead carts. Bots can lock a whole warehouse. |
| Check stock, then decrement when payment succeeds | Show in stock, take the payment, then reduce the count. | Nothing is locked. | A race: two buyers both see one unit, both pay, one has to be refunded. The visualizer shows an oversold order. |
| Reserve at checkout with an expiry | A conditional update sets stock aside when checkout starts, for a limited time. Payment turns it into a sale. Expiry gives it back. | Abandoned checkouts release stock by themselves. No oversell. Locks only people who are really buying. | A reservation table and a sweeper. The time limit must fit real checkout times, or slow payers are refunded. |
| Pre-allocated stock buckets or a queue | Split a hot item's stock into several counters, or admit buyers through a waiting room. | Removes the hot row for flash sales. | A bucket can run empty while another still has units, so a few buyers are told sold out by mistake. A waiting room adds a wait. |
The invariant is reserved + sold ≤ on_hand, and the conditional update enforces it: UPDATE ... SET reserved = reserved + qty WHERE on_hand - reserved >= qty. Check and write are one statement, so there is no gap for a second buyer. All lines of an order are done in one transaction, with lines sorted by SKU so two orders cannot deadlock. If any line is short, everything rolls back and the buyer is told which item is gone.
The expiry is stored in the row. A reservation past its time no longer counts, so a late sweeper is harmless. When payment succeeds, the reservation becomes CONSUMED and on_hand goes down. For a hot item we split the stock into buckets so each row takes a fraction of the traffic. We accept that a few buyers are told sold out while another bucket still has units, and let a buyer try a second bucket to shrink that error.
| Case | What happens |
|---|---|
| Buyer abandons checkout | The reservation expires and the unit is back on sale. Nothing is stuck. |
| Card is declined | The saga releases the reservation at once, without waiting for the time limit. |
| Buyer pays after the reservation expired | If a unit is still free it is re-reserved and the order goes ahead. If not, the payment is refunded and the buyer is told. |
| Two orders want the last unit | One conditional update changes a row, the other changes none. The second buyer is told sold out before paying. |
| Several warehouses | Try the nearest warehouse that has all lines, then split across warehouses. Each warehouse is its own row. |
| Stock count differs from the shelf | A cycle count writes an adjustment. A reconciliation job compares counters with physical counts and alerts on drift. |
The problem: One checkout touches the order, inventory, payment and notification services, each with its own database. We cannot wrap them in one transaction. Any step can time out, repeat or fail after the one before it succeeded. The rules: one checkout makes at most one order, never charge without an order, and never leave stock locked for ever.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Two-phase commit across services | A coordinator asks every service to prepare and then commit. | All or nothing in theory. | Payment providers will not join. Locks are held while waiting, and a stuck coordinator blocks checkout. |
| One big service and one database | Keep orders, stock and payment records in one database and one transaction. | Simple and correct at small scale. | Does not scale or split by team. The payment call still happens outside the transaction. |
| Orchestrated saga | The order service runs the steps in order and keeps a state machine. Each step has a compensation (release stock, void payment). | Each step is a local transaction. Easy to see where an order is. Fits an outside payment service. | More states to design and test. Compensations are not true rollbacks, because an email may already be sent. |
| Choreographed events | Each service reacts to events and emits the next one, with no central coordinator. | Loose coupling. No central service to scale. | The flow is hard to follow. Failure paths spread across services and are easy to miss. |
The order service owns a state machine with only legal moves: PLACED, STOCK_RESERVED, PAYMENT_PENDING, PAID, then PICKING, SHIPPED and DELIVERED, or CANCELLED. Each step is a local transaction in one service. Failure paths are written down as compensations: a failed payment releases the reservation, and a failed confirm voids the payment. See the Saga, Compensating Transactions and Outbox pages for the building blocks.
Exactly one order per checkout comes from the Idempotency-Key, stored with a unique constraint on the order. The same key is passed on to inventory (the reservation is keyed by order id) and to payment (the order id is the payment key). An unknown payment outcome never becomes failure: the order waits in PAYMENT_PENDING, and a sweeper asks the payment service until it knows, as in Design a Payment System. Stock stays reserved only until the expiry, so even a stuck order cannot hold units for ever.
| Step that fails | State left behind | What the saga does |
|---|---|---|
| Reserve stock: an item is short | Order PLACED, nothing reserved | Cancel the order, tell the buyer which item is gone, charge nothing. |
| Payment is declined | Stock reserved | Release the reservation and cancel the order. |
| Payment times out | Stock reserved, outcome unknown | Keep PAYMENT_PENDING. Ask the payment service by order id. Resolve to PAID or cancel. Never charge twice. |
| Payment succeeds, order service crashes | Customer charged, order PAYMENT_PENDING | On restart the sweeper finds the payment by order id and completes the order. |
| Payment succeeds, reservation expired meanwhile | Charged, stock free or taken | Re-reserve if a unit is free. Otherwise refund and apologise. |
| Event is not published after commit | Order PAID, others do not know | The outbox row is still there. The relay publishes it. Consumers dedupe by event id. |
The problem: After the money is taken, the order lives for days and passes through warehouses and carriers that report in their own time and sometimes out of order. A shopper must see the right status at once. Orders get split, partly shipped and partly cancelled. History must be trustworthy for support and for legal reasons.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Update one status column | Overwrite the order's status as events arrive. | Simple to read. | No history. A late or duplicate event can move the status backwards. Hard to explain what happened. |
| State machine with an event log | Keep a status that only moves along legal transitions, and append every change to an order_events table. | Illegal moves are rejected. Full history. Easy to audit. | More tables, and consumers must handle duplicates and old events. |
| Full event sourcing | The event log is the only truth, and the order is rebuilt by replaying it. | Perfect history and replay. | A bigger change for the whole team, and harder to query. Not needed to solve this problem. |
| Read model for order history | Build a separate view, sharded by user, for the My Orders page, fed by events. | Fast reads at scale. The write model stays small. | Eventually consistent, so the page needs a plan for right after a purchase. |
Only legal transitions are accepted, with a version number so two updates cannot overwrite each other, and an event that arrives for an older state is a no-op. Warehouse and carrier events are consumed idempotently, keyed by event id. Every change is appended to order_events, so support can see exactly what happened and when.
Orders are split into shipments, each with its own state, so partial shipping and partial cancels are normal and the order status is derived from its parts. Returns and refunds are new events and compensations (a refund entry, a restock), never edits to history. For the shopper's My Orders page we use a read model sharded by user id. To avoid a missing order right after buying, the checkout response itself carries the new order, and reads in the next few seconds go to the primary (read-your-writes).
| Order state | How we get here | Ways out |
|---|---|---|
| PLACED | Checkout accepted, saved | STOCK_RESERVED, or CANCELLED if an item is short |
| STOCK_RESERVED | All lines reserved | PAYMENT_PENDING, or CANCELLED on timeout |
| PAYMENT_PENDING | Payment asked, outcome not yet known | PAID, or CANCELLED after a safe wait or a decline |
| PAID | Payment confirmed, reservation consumed | PICKING, or CANCELLED with a refund |
| PICKING, SHIPPED, DELIVERED | Warehouse and carrier events, per shipment | RETURN_REQUESTED after delivery |
| CANCELLED, REFUNDED | Final | Corrections are new events, never a status rewind |
The problem: On a sale day, traffic is ten to twenty times normal, one item draws most of the buyers, and every service is a little slower than usual. A slow service ties up threads everywhere. Autoscaling takes minutes and does nothing for one hot row. Something has to give, and the design should choose what.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Autoscale everything | Add servers as load rises. | Easy to say, and it helps stateless services. | Too slow for a spike. Does nothing for hot rows or a slow database, and more servers can add contention. |
| Queue the writes | Accept orders into a queue and process them at a steady rate. | Smooths a spike. Protects downstream services. | The buyer waits, so the interface needs an honest pending state. Ordering and duplicates need care. |
| Isolate and limit each service | Timeouts, concurrency limits, bulkheads and circuit breakers per dependency. | One slow service cannot take all the others with it. | Limits must be tuned, and rejected work needs a graceful answer. |
| Degrade on purpose | A planned list of features to switch off in order: recommendations, reviews, rich search filters, then more. | Keeps the money path alive when everything else is struggling. | Needs flags, practice, and an agreement with the business on what is optional. |
The money path (cart, checkout, inventory, order, payment) is protected first. Order intake goes through a queue with a visible pending state, so a spike becomes a steady rate. Every call between services gets a timeout, a concurrency cap and a circuit breaker, and each dependency has its own pool (a bulkhead), so a slow recommendation service cannot use up the threads that checkout needs.
Load is shed on purpose: feature flags switch off recommendations, reviews and heavy search filters first, in an order agreed beforehand and rehearsed in game days. Hot items get bucketed stock or a waiting room. Autoscaling still helps the stateless web tier and the catalog readers, and we pre-scale before a known sale instead of reacting. Queue depth, p99 latency per service and the checkout funnel tell us when to pull each lever.
| Lever | When to pull it | What the shopper sees |
|---|---|---|
| Pre-scale web and cache tiers | Before a planned sale | Nothing, the site stays fast |
| Turn off recommendations and reviews | Latency rises on the page | A plainer product page |
| Serve slightly older cache entries | The catalog database is struggling | A price that is a few seconds old |
| Waiting room for one hot item | One SKU gets thousands of attempts a second | A short line and an honest wait time |
| Queue order intake | Order service latency rises | “We are placing your order”, then a confirmation |
| Reject new carts from bots and over-limit clients | Abuse patterns appear | Bots see errors, people are served |
| Buyer | What they do | Order at this tick | State |
|---|---|---|---|
| Buyer 1 | cart t0, checkout t1, pays 2 ticks after starting checkout | order confirmed | |
| Buyer 2 | cart t0, checkout t1, walks away | reservation expired | |
| Buyer 3 | cart t1, checkout t2, pays 2 ticks after starting checkout | order confirmed | |
| Buyer 4 | cart t1, checkout t2, card is declined | card declined | |
| Buyer 5 | cart t2, checkout t3, pays 7 ticks after starting checkout (slow) | checking out, unit reserved | |
| Buyer 6 | cart t2, checkout t3, pays 2 ticks after starting checkout | told sold out | |
| Buyer 7 | cart t3, checkout t4, pays 2 ticks after starting checkout | checking out, unit reserved | |
| Buyer 8 | cart t4, checkout t5, pays 2 ticks after starting checkout | checking out, unit reserved |
A teaching model with fixed numbers and no random values: 8 scripted buyers with fixed ticks, and 2,500 buyers assigned to buckets by a fixed hash. The 1,000 updates a second per row is an illustrative assumption, not a measurement. Real systems also copy the counters to a database and reconcile them with the physical stock.
| Bottleneck | Fix |
|---|---|
| One hot item: thousands of attempts a second on one stock row (5,000 against about 1,000) | Split the counter into buckets, or admit buyers through a waiting room. Keep the reservation transaction to one short statement. |
| Product page reads (100,000 a second at peak) | A CDN, a denormalised cached document, short-lived price and stock fragments, request coalescing and jittered lifetimes. |
| The order database during peak intake (about 230 orders a second, each with items and events) | Shard orders by user id, queue intake, batch the outbox relay, and keep order rows small by moving history to the events table. |
| The cart store (23,000 operations a second at peak, 50 GB of carts) | A replicated key-value store sharded by user, with a time to live, and a local cache of the cart for the current session. |
| A slow payment service ties up checkout threads | A timeout, a concurrency cap, a circuit breaker and a bulkhead. Queue the work and show a pending state. See Design a Payment System. |
| The search index lagging behind catalog changes | Update it from change events, alert on lag, and rebuild from the catalog database when it falls too far behind. |
| Reservation expiry and release storms after a sale | Expiry is lazy (a stale row is ignored), the sweeper works in small batches by SKU range, and releases are published in bulk. |
| Failure | How the design copes |
|---|---|
| The payment service times out | The order waits in PAYMENT_PENDING with the stock still reserved. A sweeper asks by order id. The reservation expiry bounds how long stock is held. The buyer is told it is processing. |
| The inventory database fails over | A synchronous replica takes over. Reservations are in the database, so they survive. Writes pause for seconds, and checkout shows a pending state while it happens. |
| The order service crashes mid-saga | The state is in its database. On restart a recovery job resumes every order that is not final, using the idempotency keys so no step repeats its effect. |
| The event bus is down | Events wait in the outbox. Orders keep being taken. Fulfilment starts a little late when the bus returns. |
| The product cache loses a node | That slice of keys misses. Request coalescing and a local fallback limit the stampede on the catalog database, and a replica or rebuild refills the cache. |
| Stock counters drift from the shelf | Cycle counts write adjustments. A job compares counters, reservations and shipped quantities, alerts when they diverge, and keeps safety stock on high-value items. |
A read side that is cached hard and allowed to be a few seconds stale, and a buy side that is exact. Stock is reserved at checkout with an expiry, using one conditional update, so it never oversells and abandoned checkouts free themselves. Checkout is a saga run by the order service with idempotency keys and an outbox, and an unknown payment outcome waits instead of failing. On a peak day we queue intake, isolate dependencies and switch off the optional features first.
| Decision | What we gain | What it costs |
|---|---|---|
| Reserve at checkout, not at add-to-cart | No stock locked in abandoned carts, and no oversell | A reservation table, an expiry to tune, and a late payer may be refunded |
| Cached, slightly stale product pages | 100,000 views a second cost the database almost nothing | A badge or price can be a few seconds wrong, so checkout must re-check |
| A saga, not a distributed transaction | Works with an external payment service and keeps services independent | More states and compensations to design and test |
| One database per service | Teams and scaling are independent, and hot stock rows do not fight catalog reads | No joins across services, so we need events and read models |
| Bucketed stock for hot items | No single row takes 5,000 updates a second | A few buyers are told sold out while another bucket still has units |
| Degrade optional features on a peak day | The money path stays alive under load | A plainer site, and a decision about what counts as optional |
The questions an umbrella prompt invites. Show judgement about what to build first and what is hardest.
The invariant and the hot item. Say the rule first, then show what enforces it.
Multi-step failures. Say what state is left behind and how you recover.
Catalog reads, sharding, consistency between services, and the big-sale day.
Changed requirements. They test whether you understand why the design looks the way it does.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Add a marketplace with many sellers | Inventory gets a seller id, orders split into shipments per seller, one payment is split into several credit entries with a platform fee, and payouts and returns become per seller. The saga keeps its shape with more lines. |
| Add flash sales with strict first-come, first-served fairness | A waiting room in front of the hot item, signed admission tokens tied to accounts, per-customer limits, and bucketed stock behind it. Same design as Design Ticket / Hotel Booking. |
| Make stock exact on the product page too | Not possible without making every page view hit the stock service. Instead show coarse badges, push stock events to the cache within a second, and keep the exact check at checkout. Say the cost: exact pages would need a database sized for 100,000 reads a second. |
| Sell digital goods with no stock | Skip the reservation and the warehouse. The saga becomes create order, pay, grant access. Add licence keys or download rights as the fulfilment step, and handle refunds by revoking access. |
| Two regions must both accept orders | Home each customer and their cart and orders to one region. Replicate the catalog everywhere. Inventory has one home per warehouse, and a region far from the warehouse sends the reservation to its home. Never let two regions decrement the same row. |
| Add subscriptions and repeat orders | A scheduler creates orders with deterministic idempotency keys (subscription id and date). A failed card retries on a schedule with notifications. Stock is reserved shortly before shipping, not at sign-up. |
| Add coupons and promotions | A promotion service computes the price. Limited-use coupons are counted with a conditional update, like stock, because two buyers must not both use the last coupon. Apply them at checkout re-pricing, not in the cart. |
| A supplier sends stock updates every night, and counts are often wrong | Treat supplier feeds as proposals. Reconcile them against received and shipped events, apply the difference as an adjustment, and keep safety stock back for items that drift. Alert on repeated mismatches per supplier. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Scoping | Tries to design everything, or starts drawing boxes at once. | Chooses a few flows and states what is left out. | Says the scope aloud, links the parts it skips, states the never-happen rules (no oversell, no lost order, no charge without an order) and confirms them. |
| Estimation | No numbers, or a big guess with no use. | Gets page views, orders and storage right. | Shows that reads dominate, that stock writes are small, and that one hot row (5,000 a second against 1,000) is the real risk. |
| Consistency boundaries | Everything strongly consistent, or everything cached. | Caches pages, keeps stock and orders exact. | Draws the line explicitly, explains the cost of a stale read against a wrong write, and re-checks price and stock at checkout. |
| Inventory | Read, then decrement. Or lock stock in the cart. | A conditional update and a reservation. | A reservation with an expiry stored in the row, all lines in one transaction, buckets for a hot item, and reconciliation with the shelf. |
| Checkout and failures | One transaction across services, or only the happy path. | A saga with compensations and an idempotency key. | Walks through payment timeout, crash after charge, and expired reservation, with recovery by order id and an outbox. |
| Operations and trade-offs | Autoscaling as the answer to everything. | Caches, queues and monitoring. | Isolates dependencies, degrades in a rehearsed order, names the cost of each choice, and says what to build next. |
| Mistake | Do this instead |
|---|---|
| Starting to draw the whole of Amazon | State the scope in the first five minutes: the flows you design and the ones you link to other case studies. |
| Taking stock off at add-to-cart | Reserve at the start of checkout with an expiry, so abandoned carts do not lock stock. |
| Checking stock and then decrementing in two steps | One conditional UPDATE, and check the number of changed rows. |
| Trusting the cached stock badge or price at checkout | Re-read price and stock from the sources of truth when the buyer checks out. |
| A distributed transaction across order, stock and payment | A saga with a state machine, compensations, idempotency keys and an outbox. |
| Treating a payment timeout as a failure | Keep the order in PAYMENT_PENDING, ask the payment service by order id, and never charge twice. |
| One hot item on a single stock row | Bucket the counter, or put a waiting room in front, and accept a few mistaken sold-out answers. |
| Relying on autoscaling for the sale day | Queue intake, isolate dependencies, pre-scale for known sales and degrade optional features first. |
The payment step of checkout: idempotency, the ledger and unknown outcomes.
The same stock problem with holds, a waiting room and flash-sale traffic.
How product search is built and ranked.
The “you may also like” row that we left out.
The checkout flow with compensations.
How order and stock events are published without loss.
Why a repeated checkout or reservation has no new effect.
The read model behind the product page and order history.