SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design an E-commerce System (Amazon)

Catalog, search, cart, stock, checkout and orders for millions of shoppers, with no overselling and no lost orders.

⏱ 40 min readHard case studyAdvanced28 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design an e-commerce system like Amazon.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy 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 mattersA 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 oversellingReserve 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 servicesOrder, 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 dayBlack 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.

TL;DRThe whole design in 60 seconds

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.

  • Scope first: we design catalog and product page, cart, inventory, checkout and order lifecycle. Search, recommendations and the payment ledger are linked case studies, not redesigned here.
  • Browsing: a denormalised product document in a cache behind a CDN. Price and stock badge are fetched separately with a short life. Roughly 100,000 page views a second at peak become about 1,000 to 2,000 reads at the origin.
  • Stock invariant: reserved plus sold never exceeds on-hand. We reserve at the start of checkout with a short time limit, using one conditional update. Abandoned checkouts release their stock by themselves.
  • Checkout: create the order as PENDING, reserve stock, pay (external), confirm. If a step fails, compensate: release the stock, void or refund. Every call carries an idempotency key, and events leave through an outbox.
  • Hot items: split the stock counter into buckets, or put a waiting room in front, so one row is not hit 5,000 times a second.
  • Sale day: queue order intake, cap each service, and switch off the optional things (recommendations, reviews) before checkout suffers.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

5
3
5
8
14
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify5Scope aggressively: which flows, what is out, the stock rule, and the peak.
2. Estimate3Page views, orders and cart operations per second; catalog and order storage; reservation rows in flight.
3. API and data5Product, cart and checkout calls; products, inventory, cart and order tables.
4. High-level design8Edge and cache, catalog, cart, inventory, order saga, events.
5. Deep dives14Product page at scale, inventory without overselling, checkout saga, order lifecycle, peak day.
6. Scale and failures7Stock drift, payment unknowns, a slow service, and what to switch off.
7. Wrap up3Recap, trade-offs, and what to build next.

Step 1Clarify requirementsabout 5 min

🤔
Pause. Try it yourself first
You have 60 seconds. This prompt is huge. Write down the three or four flows you will design and the ones you will leave out. Hint: what is the smallest set of services that lets a customer buy one item and never be oversold?

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Browse product pages with price, images and a stock badge
  • •Add, change and remove items in a cart that follows the user across devices
  • •Check out: confirm address and price, set aside stock, pay, and get an order
  • •See order status and history, and cancel before it ships
  • •Update stock when goods arrive, are picked, shipped or returned
Non-functional (how well)
  • •Correct: never oversell, never lose an order, never charge without an order
  • •Fast: product page under 200 ms at p99 from cache, checkout under a few seconds
  • •Available: browsing 99.99%, checkout 99.95% (about 4 hours of downtime a year)
  • •Scalable: 100,000 page views a second and a few hundred orders a second on a sale day
  • •Durable: an accepted order is never lost, even if a zone fails
Out of scope (say it)
  • •Search and ranking (see Design a Search Engine) and recommendations (see Design a Content Recommendation System (YouTube/Netflix))
  • •Payments and the ledger (see Design a Payment System): we treat payment as an external service
  • •Seller onboarding, reviews, returns logistics, ads and delivery routing
  • •Fraud models and tax rules (we only leave a place to call them)
🎤
Say it out loud
“Let me narrow this before I draw. E-commerce is huge, so I will design five things: the product page, the cart, inventory, checkout and the order lifecycle. Search, recommendations and the payment system are their own problems, and I will treat payment as an external service. It is one retailer with several warehouses, 50 million daily users and 1 million orders a day, with a sale day of up to twenty times that. The rule that matters: never oversell, never lose an order, never charge without an order. Pages may be a few seconds stale, but stock and orders must be exact. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: orders and page views per second (normal and peak), cart operations, how big the catalog and orders get, and how many reservations are open at once. Which of these decides the design?

Assumptions (say them first)

AssumptionValue
Daily users50 million (all numbers here are illustrative assumptions)
Products (SKUs)300 million, about 5 KB of metadata each, 10 images of 200 KB
Orders per day1 million, about 5 KB per order plus items and events
Product page views500 million a day, with a peak of about 100,000 a second
Sale-day peak for orders20 times the average
Cart operations4 per daily user per day, peak 10 times the average
Checkout takesabout 3 minutes (180 seconds) from start to payment
Items per order3 on average, 8 events per order
Warehouses per item3, with about 50 bytes per inventory row

The arithmetic, line by line

WhatMathsResult
Average orders per second1,000,000 ÷ 86,400about 12 per second
Sale-day peak orders12 × 20about 230 per second
Average page views per second500,000,000 ÷ 86,400about 5,800 per second (100,000 at peak, 17 times)
Reads that miss the cache at a 98% hit rate100,000 × 2%2,000 per second (1,000 at 99%)
Catalog metadata300,000,000 × 5 KB1.5 TB (fits in memory across a cache cluster)
Product images300,000,000 × 10 × 200 KB600 TB, in object storage behind a CDN
Cart operations per second50,000,000 × 4 ÷ 86,400, then × 10about 2,300 average, 23,000 at peak
Active carts in memory50,000,000 × 1 KB50 GB (150 GB with 3 copies)
Order storage1,000,000 × 5 KB, then × 3655 GB a day, about 1.8 TB a year (5.5 TB with 3 copies)
Inventory rows300,000,000 × 3 warehouses × 50 B900 million rows, about 45 GB
Events published1,000,000 × 8, then ÷ 86,400 and × 20about 93 a second on average, about 1,900 at peak
Stock reservation writes at peak230 orders × 3 itemsabout 700 writes per second (small)
Reservations open at once (3 minute checkout)230 × 180 s × 3 itemsabout 124,000 rows (a 15 minute limit would allow about 620,000)
One hot item on sale day10,000 buyers in 2 seconds ÷ 25,000 attempts a second on one row, against about 1,000 a row can take
What the numbers tell us about the design
  • •Reads dominate: about 100,000 page views a second against a few hundred orders. The product page is a caching problem, and it is solved with a denormalised document, a CDN and short-lived fragments.
  • •Writes are small: 700 stock writes a second is easy for a sharded database. The danger is not the average but one hot item: 5,000 attempts a second on a single row is five times too many.
  • •Catalog and orders are modest in size (1.5 TB of metadata, 5 GB of orders a day). Images (600 TB) are the big number, and they belong in object storage and a CDN.
  • •Open reservations stay in the low hundreds of thousands, so an expiry of a few minutes keeps the reservation table small and the release job cheap.
  • •The stock write and the payment call are separate systems, so correctness cannot come from one transaction. It has to come from the saga, the reservation and idempotency.
🎤
Say it out loud
“Let me do the maths. A million orders a day is 12 a second, and a sale day is about 230 a second. Page views are 500 million a day, about 5,800 a second and 100,000 at peak, so reads dominate and a cache with a 98 percent hit rate leaves 2,000 a second at the origin. Stock writes are only about 700 a second, which is easy, and a three-minute checkout means about 124,000 open reservations. The numbers say two things: browsing is a caching problem, and the real risk is a single hot item, where 10,000 buyers in two seconds put 5,000 attempts a second on one row.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the calls a shopper makes: read a product, change the cart, check out. Then say what makes checkout safe to retry, and which table decides whether the last unit can be sold twice.

Endpoints

MethodPathRequestResponseNotes
GET/v1/products/{id}none200 { 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/checkoutIdempotency-Key header + { cartId, addressId, paymentMethodToken }202 { orderId, status: PENDING } then 200 when settledStarts 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}none200 { 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}/cancelIdempotency-Key200 or 409 when already shippedA 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.

Data model

inventory (one row per sku and warehouse)TypeWhy it is there
sku, warehouse_ididsThe key. Stock is counted per warehouse.
on_handintPhysical units, changed by receipts, picks and cycle counts.
reservedintUnits set aside for open checkouts. The conditional update keeps reserved <= on_hand.
version, updated_atint, timestampOptimistic concurrency, and the data for drift checks.
reservations and cartsKey fieldsWhy
reservationsorder_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.
cartsuser_id or cookie, items [{sku, qty, price_seen}], updated_at, expires_atA key-value document with a time to live. No stock is held. price_seen lets checkout show a price change.
ordersorder_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 outboxorder_id, seq, type, payload, publishedAn append-only history, and the rows a relay publishes to the event bus.
Reserve stock: one conditional update per line, in one transaction
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;
📝Which store, and why
Four stores for four different jobs. The catalog is read-heavy and tolerates staleness: a document store or key-value cache fed from a source database, behind a CDN. The cart is a small document per user with a time to live: a key-value store with replication. Inventory and orders need transactions, unique constraints and strong consistency: relational databases, sharded by SKU for inventory and by user for orders, one database per service. Search is a separate index rebuilt from change events. One shared database for everything would couple the services and make the hot inventory rows fight the catalog reads.
🎤
Say it out loud
“The shopper reads a product from a cache, sets quantities in a cart that holds no stock, and posts one checkout with an idempotency key. Inventory is a row per SKU and warehouse with on-hand and reserved, and the reservation is one conditional update: reserved goes up only if on-hand minus reserved is at least the quantity, in one transaction across all lines, or it rolls back. The order keeps a copy of the price and address at purchase time, and an outbox table publishes its events. Each service owns its own database.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes between a shopper and the stock count. Which ones are only caches? Which one is allowed to say yes to the last unit? Where does payment sit?
E-commerce: high-level design
🛍️Shopperweb, app
→↓HTTPS
🌍CDN + edgeimages, pages, 30 s cache
→↓miss
🚪API gatewayauth, rate limit, shed load
Browse (eventual)
📚Catalog serviceproduct documents
⚡Product cachedoc + price + badge
🔎Search indexsee search case study
Buy (strong)
🛒Cart servicekey-value, TTL
🧭Order servicestate machine + saga
📦Inventory servicereserve, release, count
Outside and after
💳Payment serviceexternal, see payment case study
🏭Fulfilmentpick, pack, ship
🔔Notificationsemail, push
Events
📤Outbox + relay
📨Event busKafka-like
🧹Reservation sweeperfrees expired holds
Reads go through the CDN and caches and may be stale. Checkout is a saga run by the order service: reserve stock, pay, confirm. Events leave through an outbox.
ComponentWhat it does
CDN and edgeServes images and static page parts, and caches product documents for a short time. Takes most of the 100,000 page views a second.
API gatewayAuthenticates, rate-limits and sheds load. On a bad day it drops optional calls (recommendations, reviews) first.
Catalog service and product cacheOwns product documents. A denormalised document (title, images, attributes) is cached. Price and the stock badge are fetched separately with a short life.
Cart serviceA key-value document per user with a time to live. Holds no stock. Guest carts merge into the account at login.
Inventory serviceThe source of truth for stock. Reserves, releases and consumes units with conditional updates, per SKU and warehouse.
Order serviceOwns 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 consumersPublish order and stock events at least once. Fulfilment, notifications, search and analytics consume them idempotently.
Reservation sweeperReleases reservations past their expiry. Correctness does not depend on it, because the stock check ignores expired rows.
Write path (follow one request)
  1. The shopper changes the cart. The cart service sets the quantities in its store. No stock is touched.
  2. At checkout the order service creates the order as PENDING in its own database, with the idempotency key, a copy of the prices and the address, and an outbox row.
  3. It asks the inventory service to reserve every line. Inventory runs one transaction: a conditional update per line and a reservation row with an expiry. Any short line rolls everything back and the buyer is told which item is gone.
  4. With the stock held, the order service asks the payment service to authorise, passing the order id as the idempotency key. An unknown outcome leaves the order in PAYMENT_PENDING and a sweeper asks again.
  5. On success, one transaction marks the order PAID, turns the reservations into CONSUMED (on_hand goes down) and writes an outbox event. On failure or timeout past the limit, the reservation is released and the order is CANCELLED.
  6. The relay publishes order.paid. Fulfilment picks and ships. Notifications send the receipt. Search and analytics update.
Read path (follow one request)
  1. A shopper opens a product page. The CDN serves the images and any cached page parts.
  2. On a miss, the catalog service reads the product document from the product cache (a hit rate of 98 percent or more).
  3. Price and the stock badge come from separate cached fragments with a life of a few seconds, so a price change does not require rebuilding the whole document.
  4. The page shows IN_STOCK, LOW or OUT as a hint, and never as a promise.
  5. At checkout, price and stock are read from the sources of truth. If the price moved, the shopper sees the difference before paying. If stock ran out, they are told at reservation time.
🎤
Say it out loud
“Here is the picture. The browse side is cached and may be stale: a CDN, a product cache with a denormalised document, and short-lived price and stock fragments. The buy side is strong: a cart in a key-value store that holds no stock, an order service that runs the checkout as a saga, and an inventory service that owns the stock. Checkout creates the order as pending, reserves every line in one conditional transaction, asks the external payment service with an idempotency key, then marks the order paid and consumes the reservation. Events go out through an outbox to fulfilment, notifications and search.”

Step 5Deep dive into the hard partsabout 14 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

The product page at 100,000 views a second

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.

OptionHow it worksGoodBad
Render from the database every timeJoin 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 pageCache 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 fragmentsCache 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 cacheOn 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.
Pick
A denormalised product document built from change events (a read model), with price and stock as short-lived fragments, all behind a CDN

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 pageHow freshWhere it lives
Images and descriptionsHours or daysObject storage and a CDN, with versioned file names so a change is a new URL
Product documentSeconds to minutes after a change eventProduct cache (sharded memory store), rebuilt from the catalog database
PriceA few secondsSmall cache entry, set by the pricing service on every change
Stock badge (in stock, low, out)A few secondsSmall cache entry derived from inventory events, and only a hint
The real price and the real stockExactRead from the pricing and inventory services at checkout only
🧠The page may be wrong, the checkout may not
A stale badge costs a polite message at checkout. A stale stock count at checkout costs an oversold item. So the cache sits on the browse side only, and checkout always asks the source of truth.
🎤
Say it out loud
“Browsing is a caching problem, so I split the page by how often each part changes. Images and the product document change rarely and sit in a long-lived cache behind a CDN, built from change events. Price and the stock badge are tiny fragments with a life of a few seconds. For a viral item I coalesce misses, add jitter to lifetimes, serve slightly stale data during a refresh, and keep a small copy on each web server. The page is allowed to be a few seconds wrong, because checkout re-reads price and stock from the sources of truth.”
5.2

Inventory without overselling

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.

OptionHow it worksGoodBad
Take stock off at add-to-cartDecrement 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 succeedsShow 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 expiryA 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 queueSplit 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.
Pick
Reserve at checkout with an expiry, using one conditional update, and split the counter into buckets (or queue the buyers) only for hot items

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.

CaseWhat happens
Buyer abandons checkoutThe reservation expires and the unit is back on sale. Nothing is stuck.
Card is declinedThe saga releases the reservation at once, without waiting for the time limit.
Buyer pays after the reservation expiredIf 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 unitOne conditional update changes a row, the other changes none. The second buyer is told sold out before paying.
Several warehousesTry the nearest warehouse that has all lines, then split across warehouses. Each warehouse is its own row.
Stock count differs from the shelfA cycle count writes an adjustment. A reconciliation job compares counters with physical counts and alerts on drift.
💡Try it in the visualizer
The first half replays 8 buyers against 5 units under three policies. The second half splits a 1,000-unit item into buckets and shows the busiest row drop below its limit, at the price of a few wrong sold-out answers.
🎤
Say it out loud
“The invariant is reserved plus sold never exceeds on-hand. I would not take stock at add-to-cart, because abandoned carts lock it, and I would not check at payment, because two buyers can both pay for the last unit. I reserve at checkout, with an expiry, using one conditional UPDATE across all lines in one transaction, sorted to avoid deadlocks. Payment turns the reservation into a sale, and abandoning or declining gives it back. For a flash sale on one item I split the counter into buckets so no row takes more than it can, and accept a few mistaken sold-out answers.”
5.3

Checkout across services without a distributed transaction

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.

OptionHow it worksGoodBad
Two-phase commit across servicesA 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 databaseKeep 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 sagaThe 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 eventsEach 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.
Pick
An orchestrated saga in the order service, with idempotency keys on every call and an outbox for events

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 failsState left behindWhat the saga does
Reserve stock: an item is shortOrder PLACED, nothing reservedCancel the order, tell the buyer which item is gone, charge nothing.
Payment is declinedStock reservedRelease the reservation and cancel the order.
Payment times outStock reserved, outcome unknownKeep PAYMENT_PENDING. Ask the payment service by order id. Resolve to PAID or cancel. Never charge twice.
Payment succeeds, order service crashesCustomer charged, order PAYMENT_PENDINGOn restart the sweeper finds the payment by order id and completes the order.
Payment succeeds, reservation expired meanwhileCharged, stock free or takenRe-reserve if a unit is free. Otherwise refund and apologise.
Event is not published after commitOrder PAID, others do not knowThe outbox row is still there. The relay publishes it. Consumers dedupe by event id.
⚠️Price changes between cart and checkout
The cart remembers the price the buyer saw. Checkout re-prices from the pricing service. If it differs, stop and show the difference before charging. Never silently charge a new price or silently honour an old one.
🎤
Say it out loud
“There is no transaction across order, stock and payment, so the order service runs a saga with a state machine. Each step is a local transaction, and each failure has a compensation: a declined card releases the reservation, a late confirm voids the payment. One idempotency key makes one order per checkout, and the order id is passed on as the key for the stock and payment calls. A payment timeout never becomes failure. The order waits in payment-pending while a sweeper asks, and the reservation expiry stops stock being held for ever. Events leave through an outbox.”
5.4

Order lifecycle, fulfilment and history

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.

OptionHow it worksGoodBad
Update one status columnOverwrite 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 logKeep 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 sourcingThe 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 historyBuild 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.
Pick
A state machine with an append-only event log, plus a read model for history sharded by user

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 stateHow we get hereWays out
PLACEDCheckout accepted, savedSTOCK_RESERVED, or CANCELLED if an item is short
STOCK_RESERVEDAll lines reservedPAYMENT_PENDING, or CANCELLED on timeout
PAYMENT_PENDINGPayment asked, outcome not yet knownPAID, or CANCELLED after a safe wait or a decline
PAIDPayment confirmed, reservation consumedPICKING, or CANCELLED with a refund
PICKING, SHIPPED, DELIVEREDWarehouse and carrier events, per shipmentRETURN_REQUESTED after delivery
CANCELLED, REFUNDEDFinalCorrections are new events, never a status rewind
📝What if the warehouse is out of stock after the order?
It happens: counts drift and goods get damaged. The warehouse raises a shortage event. The order service tries another warehouse, offers the buyer a delay or a substitute, or cancels that line with a refund. The counters are corrected with an adjustment, and drift is tracked as a metric.
🎤
Say it out loud
“After payment, the order is a state machine that only accepts legal moves, with a version to stop overwrites and every change appended to an event log. Warehouse and carrier events are applied idempotently by event id, and an event for an older state is ignored. Orders split into shipments, so partial shipping and cancels are normal, and the order status is derived from its parts. A refund or return is a new event, never an edit. A read model sharded by user serves My Orders, and the checkout response plus reads from the primary give the shopper their new order at once.”
5.5

Surviving the peak day

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.

OptionHow it worksGoodBad
Autoscale everythingAdd 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 writesAccept 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 serviceTimeouts, 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 purposeA 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.
Pick
Queue order intake, isolate every dependency, and degrade in a rehearsed order, with autoscaling for the stateless edge only

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.

LeverWhen to pull itWhat the shopper sees
Pre-scale web and cache tiersBefore a planned saleNothing, the site stays fast
Turn off recommendations and reviewsLatency rises on the pageA plainer product page
Serve slightly older cache entriesThe catalog database is strugglingA price that is a few seconds old
Waiting room for one hot itemOne SKU gets thousands of attempts a secondA short line and an honest wait time
Queue order intakeOrder service latency rises“We are placing your order”, then a confirmation
Reject new carts from bots and over-limit clientsAbuse patterns appearBots see errors, people are served
🎤
Say it out loud
“On a peak day I protect the money path first. Orders go through a queue with an honest pending state, so a spike becomes a steady rate. Every dependency has a timeout, a concurrency limit, a circuit breaker and its own thread pool, so a slow recommendation service cannot starve checkout. We switch off optional features in a rehearsed order, recommendations then reviews then heavy filters, and hot items get bucketed stock or a waiting room. Autoscaling helps the stateless tier, and we pre-scale for a known sale, but it does nothing for a hot row.”
VisualizerProtecting the last units: three policies, and a hot itemPart 1 replays 8 buyers against 5 units. Switch between taking stock at the cart, at payment and at checkout with a time limit, and move the reservation time. Part 2 splits a hot item's counter into buckets and shows the busiest row.
Part 1: 5 units on the shelf, 8 buyers, three ways to protect the stock
When is a unit set aside for a buyer?
Shelf at tick 5:
soldsoldheldheldheld
BuyerWhat they doOrder at this tickState
Buyer 1cart t0, checkout t1, pays 2 ticks after starting checkout
CartCheckoutOrder
order confirmed
Buyer 2cart t0, checkout t1, walks away
CartCheckoutOrder
reservation expired
Buyer 3cart t1, checkout t2, pays 2 ticks after starting checkout
CartCheckoutOrder
order confirmed
Buyer 4cart t1, checkout t2, card is declined
CartCheckoutOrder
card declined
Buyer 5cart t2, checkout t3, pays 7 ticks after starting checkout (slow)
CartCheckoutOrder
checking out, unit reserved
Buyer 6cart t2, checkout t3, pays 2 ticks after starting checkout
CartCheckoutOrder
told sold out
Buyer 7cart t3, checkout t4, pays 2 ticks after starting checkout
CartCheckoutOrder
checking out, unit reserved
Buyer 8cart t4, checkout t5, pays 2 ticks after starting checkout
CartCheckoutOrder
checking out, unit reserved
Buyer 2: the reservation runs out and the unit goes back on sale. Buyer 8 starts checkout. One unit is reserved for 4 ticks.
Orders confirmed
5
of 5 units
Oversold
0
promised, none left
Told sold out
1
would have paid
Stuck units
0
locked, nobody paying
Refunded
0
paid too late
Unsold at the end
0
lost sales
All 5 units sold, none oversold, none stuck. Abandoned and declined checkouts gave their units back by themselves, and the slow buyer still found a free unit. One buyer was turned away because there are only 5 units and six people wanted one.
Part 2: a hot item, 1,000 units and 2,500 buyers: split the counter
How many buckets is the stock counter split into?
A buyer whose bucket is empty tries one more
Updates per second on each bucket. The dashed line is what one row can take (1,000 a second, an assumption).
Busiest bucket
5,000/s
limit 1,000/s
Units sold
1,000
of 1,000
Wrongly told sold out
0
units left elsewhere
Rightly told sold out
1,500
no units left
The busiest counter takes 5,000 attempts a second but a row can only do about 1,000. The buyers queue on a lock and checkout slows for everyone. Split the counter into more buckets.

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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run the worst day. A hot item sells out in seconds. The payment service slows down. A warehouse count is wrong. A cache node dies. What breaks first, and what do you switch off?

What breaks first, and the fix

BottleneckFix
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 threadsA 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 changesUpdate 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 saleExpiry is lazy (a stale row is ignored), the sweeper works in small batches by SKU range, and releases are published in bulk.

What if a part fails?

FailureHow the design copes
The payment service times outThe 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 overA 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-sagaThe 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 downEvents wait in the outbox. Orders keep being taken. Fulfilment starts a little late when the bus returns.
The product cache loses a nodeThat 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 shelfCycle counts write adjustments. A job compares counters, reservations and shipped quantities, alerts when they diverge, and keeps safety stock on high-value items.
What to monitor
  • •Checkout funnel: cart to checkout to paid, and where the drop is, per minute
  • •Stock reservation failures (sold out), expiries, and the number of open reservations
  • •Orders stuck in PAYMENT_PENDING, with the age of the oldest
  • •Inventory drift between counters and physical counts, per warehouse
  • •Latency and error rate per service, queue depth, and cache hit ratio for product pages
  • •Outbox backlog and consumer lag for fulfilment and notifications
Security and abuse
  • •Never trust the client for price, quantity limits or stock: re-check on the server at checkout
  • •Send card details straight to the payment provider, so they never touch our systems (tokens only)
  • •Rate limits and bot checks on cart, checkout and coupon calls, to stop hoarding and scalping
  • •Authorise every order read by owner, so one customer cannot read another's order by guessing an id
  • •Keep personal data (addresses, emails) minimal, encrypted and deletable within the legal retention rules

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Reserve at checkout, not at add-to-cartNo stock locked in abandoned carts, and no oversellA reservation table, an expiry to tune, and a late payer may be refunded
Cached, slightly stale product pages100,000 views a second cost the database almost nothingA badge or price can be a few seconds wrong, so checkout must re-check
A saga, not a distributed transactionWorks with an external payment service and keeps services independentMore states and compensations to design and test
One database per serviceTeams and scaling are independent, and hot stock rows do not fight catalog readsNo joins across services, so we need events and read models
Bucketed stock for hot itemsNo single row takes 5,000 updates a secondA few buyers are told sold out while another bucket still has units
Degrade optional features on a peak dayThe money path stays alive under loadA plainer site, and a decision about what counts as optional
If we had more time, we would…
  • •Marketplace sellers: stock owned by sellers, split payments and payouts, and seller-level cancellation rules
  • •Smarter warehouse allocation: split shipments, cost-based routing and regional stock balancing
  • •A rehearsed multi-region setup with a home region per customer and a fenced failover
  • •Returns, exchanges and refunds as first-class flows with their own state machine
  • •Load and chaos tests that replay a sale with real concurrency and injected payment faults
🎤
Say it out loud
“To recap: I scoped this to the product page, cart, inventory, checkout and order lifecycle, and linked search, recommendations and payments. Browsing is cached and allowed to be a few seconds stale. Stock is reserved at checkout with an expiry by one conditional update, so we never oversell and abandoned checkouts free themselves, and hot items get bucketed counters. 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 every dependency and switch off optional features first. Next I would add marketplace sellers and multi-region.”

Q&ACross-questions (28)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Scoping and prioritising

The questions an umbrella prompt invites. Show judgement about what to build first and what is hardest.

Stock and overselling

The invariant and the hot item. Say the rule first, then show what enforces it.

Checkout, payment and orders

Multi-step failures. Say what state is left behind and how you recover.

Data, search and scale

Catalog reads, sharding, consistency between services, and the big-sale day.

Curveballs and extensions

Changed requirements. They test whether you understand why the design looks the way it does.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add a marketplace with many sellersInventory 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 fairnessA 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 tooNot 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 stockSkip 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 ordersHome 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 ordersA 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 promotionsA 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 wrongTreat 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.

ScoreHow answers are judged

AreaWeakGoodGreat
ScopingTries 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.
EstimationNo 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 boundariesEverything 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.
InventoryRead, 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 failuresOne 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-offsAutoscaling 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.

AvoidCommon mistakes on this question

MistakeDo this instead
Starting to draw the whole of AmazonState 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-cartReserve at the start of checkout with an expiry, so abandoned carts do not lock stock.
Checking stock and then decrementing in two stepsOne conditional UPDATE, and check the number of changed rows.
Trusting the cached stock badge or price at checkoutRe-read price and stock from the sources of truth when the buyer checks out.
A distributed transaction across order, stock and paymentA saga with a state machine, compensations, idempotency keys and an outbox.
Treating a payment timeout as a failureKeep the order in PAYMENT_PENDING, ask the payment service by order id, and never charge twice.
One hot item on a single stock rowBucket the counter, or put a waiting room in front, and accept a few mistaken sold-out answers.
Relying on autoscaling for the sale dayQueue intake, isolate dependencies, pre-scale for known sales and degrade optional features first.

Revise60-second revision sheet

  • ✔Scope first: product page, cart, inventory, checkout, orders. Search, recommendations and payments are linked, not redesigned.
  • ✔Scale: 100,000 page views a second but only a few hundred orders. Reads are a caching problem. One hot stock row is the real risk.
  • ✔Browsing may be stale, checkout may not: re-read price and stock from the sources of truth at checkout.
  • ✔Stock invariant: reserved + sold ≤ on_hand, by one conditional UPDATE, all lines in one transaction, sorted to avoid deadlocks.
  • ✔Reserve at checkout: not at add-to-cart (locks stock) and not at payment (oversells). Expiry lives in the row.
  • ✔Hot item: bucket the counter or add a waiting room. Accept a few wrong sold-out answers.
  • ✔Checkout: a saga run by the order service, with a state machine, compensations, an idempotency key and an outbox.
  • ✔Unknown payment: stay PAYMENT_PENDING, ask by order id, never charge twice.
  • ✔Peak day: queue intake, isolate every dependency, and switch off optional features in a rehearsed order.
  • ✔One line: “Cache the browsing, reserve the stock, run the order as a saga, and never promise what the shelf cannot deliver.”

Read these topics next

Design a Payment System→

The payment step of checkout: idempotency, the ledger and unknown outcomes.

Design Ticket / Hotel Booking→

The same stock problem with holds, a waiting room and flash-sale traffic.

Design a Search Engine→

How product search is built and ranked.

Design a Content Recommendation System (YouTube/Netflix)→

The “you may also like” row that we left out.

SAGA Pattern→

The checkout flow with compensations.

Outbox Pattern→

How order and stock events are published without loss.

Idempotency→

Why a repeated checkout or reservation has no new effect.

CQRS→

The read model behind the product page and order history.

← Previous
Design a Distributed Message Queue (Kafka-like)
Next →
Design a Content Recommendation System (YouTube/Netflix)