Course contents

17. Real-World System Design Lesson 18 of 20

E-Commerce Platform

Design a shop end to end: cached catalog and search, a keyed cart, checkout as a saga with reservations and an outbox, and flash-sale admission control.

25 minAdvanced10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Reads outnumber writes by orders of magnitude: serve them from a CDN, caches and derived stores.
  • A search index fed by change events lags the catalog; checkout always reprices from the source of truth.
  • Carts are keyed documents with expiry, a good fit for a key-value store.
  • Checkout is a saga: reserve with a TTL, authorize with an idempotency key, commit order and outbox together, compensate on failure.
  • A flash sale concentrates writes on one row; admission control (rate limit or waiting room) keeps it healthy.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An e-commerce platform lets people browse a catalog, search it, keep a cart, and buy: pay, reserve stock and get the order shipped. As a design exercise it is useful because it has two very different halves. Browsing is a huge, read-only, latency-sensitive workload where slightly stale data is fine. Checkout is a small write workload where mistakes cost money: overselling stock or charging a card twice.

Why it exists

The design question is how to give each half what it needs without one hurting the other. If every page view queries the same database that checkout writes, a busy browsing day slows down orders, and a flash sale on one product can take the whole shop down. Splitting the read path, the cart and the checkout path, each with its own storage and failure handling, is what makes the system both fast and correct.

How it works

Requirements and estimates. Functional: browse, search, cart, checkout, order history. Non-functional: browsing highly available and fast (p95 in the low hundreds of ms); checkout correct (no overselling, no double charges) and durable. An illustrative estimate: 10 million daily users × 20 page views ≈ 200 million views a day, about 2,300 req/s on average and a peak several times higher. At a 2% conversion that is 200 thousand orders a day, a few per second on average, but sales concentrate them. Reads outnumber writes by roughly three orders of magnitude. These numbers are illustrative; what matters is the ratio and the peak factor.

Read path. Static assets (images, scripts, styles) are served by a CDN and never reach the origin. Product pages read the catalog through a cache-aside cache: hit, answer; miss, read the database and fill the cache. Invalidate or update cache entries when a product changes, and keep a TTL as a safety net. Search ("red running shoes under 100", with facets) runs on a dedicated search index. The index is a derived store: product changes leave the catalog database as events, through a transactional outbox or change-data capture from the database log, and an indexer applies them. The index therefore lags the catalog by the pipeline delay.

Cart. A cart is read and written by one key (user id, or session id for guests), is small, changes often and should expire when abandoned. A key-value store with a TTL fits. When a guest logs in, the guest cart is merged into the user cart. The cart stores product ids and quantities, not prices; prices are taken again at checkout.

Checkout as a saga. Inventory, payment and orders live in different services, and the payment provider (PSP) is external, so there is no single transaction. Checkout is a saga of local steps:

  1. Reserve stock for the items, with an expiry (for example 10 minutes). A conditional update (available >= qty) or a reservation row makes overselling impossible.
  2. Authorize the payment, passing an idempotency key derived from the checkout id. If the call times out, retry with the same key; the PSP returns the original result instead of charging again. Capture usually happens at shipment.
  3. Commit the order and an outbox row (OrderPlaced) in one database transaction, then answer the shopper.

A relay publishes outbox rows to a topic; fulfilment, email and analytics consume them, ideally as idempotent consumers, since the relay delivers at least once. If a step fails, the saga runs compensations in reverse: a declined payment releases the reservation and the shopper gets an error. If checkout crashes mid-saga, the reservation TTL releases the stock anyway, and a recovery job can resume or compensate sagas from their persisted state.

Flash sales. A limited drop sends a burst of buyers at one product. Every checkout writes the same stock row, and writes to one row serialise on its lock, so that row's write rate caps successful checkouts no matter how many servers call it. Without protection, requests queue for connections, time out, fill the servers and are rejected: latency and errors rise for everyone. Two forms of admission control fix it:

  • Rate limiting (a token bucket at the edge) admits what the row can sustain and answers the rest immediately with 429. Fast and simple, but it refuses buyers at random.
  • A waiting room (a queue-based virtual line) answers every buyer at once with a place in line and admits them at the sustainable rate. No errors and a fair order, at the cost of waiting. Cap the line near the available stock, and enforce per-account limits and bot checks at ticket time.

Sharding the stock counter (for example ten sub-counters of 200 units each) raises the write ceiling further, at the cost of more complex "sold out" detection.

When to use it

This shape fits most retail, ticketing and marketplace systems: a read-heavy catalog with search, per-user carts, and a checkout that touches inventory and an external payment provider. The flash-sale techniques apply to any burst against a scarce resource: concert tickets, sneaker drops, limited reservations, vaccine appointment slots.

When not to

  • A small shop with modest traffic is well served by one relational database and a hosted storefront; caches, search clusters and sagas are operational cost you do not need yet.
  • If stock is effectively unlimited (digital goods), reservations and waiting rooms are unnecessary; payment idempotency still matters.
  • A single modular application with one database can run checkout in one local transaction; a saga is the answer only once inventory, orders and payment are separate services or stores.

Trade-offs

Choice You gain You pay
Cache + CDN on the read path Database relief, low latency Staleness and invalidation work
Search index fed asynchronously Fast faceted search, catalog DB untouched Results lag; reprice at checkout
Reservation with TTL No overselling Stock held by abandoned checkouts; TTL tuning
Saga instead of distributed transaction Services stay independent and available Compensations, intermediate states visible
Rate limit during a sale Simple, protects the bottleneck Random refusals, retry storms
Waiting room during a sale No errors, fair order Waiting time, extra component, line cap logic
Strict reservation vs accepted overselling Never disappoint a paying buyer Lower conversion; some retailers oversell slightly and apologise for non-scarce items

Alternatives

  • Hosted commerce platforms take most of this off your hands, with less control over checkout and sale behaviour.
  • Two-phase commit across inventory, orders and payment is not available with external PSPs and couples availability; sagas are the usual choice.
  • Pre-allocation for drops: run a lottery or registration before the sale and sell only to winners, avoiding the burst entirely.
  • CQRS read models generalise the search index idea: denormalised views per query shape, fed by events.

Failure modes

  • Cache stampede after a popular product's entry expires or the cache restarts empty: coalesce misses and add TTL jitter.
  • Search shows stale prices or stock: expected; checkout must not trust it.
  • Double charge from retrying a payment call without an idempotency key.
  • Lost or phantom events from writing the order and publishing the event separately (dual write); the outbox removes this.
  • Reservations never released because a compensation failed and no TTL exists.
  • Hot-row meltdown in a flash sale: servers fill with requests waiting on one lock and reject everyone, including buyers who could have been served.
  • Retry storms after 429s if clients retry without backoff.

In production

Keep the browsing path independent of checkout so a sale cannot slow browsing. Monitor cache hit ratio, index lag, reservation expiries and saga states stuck between steps. Load-test the sale path against the real stock-row write rate. Payment providers publish idempotency-key semantics and retention windows; design retries within them. Reconcile orders, payments and stock daily: sagas plus at-least-once delivery mean you need a way to find and fix the rare inconsistency.

Common misconceptions

  • "More checkout servers handle a bigger sale." Not when every checkout writes one row; they only add waiters for the same lock.
  • "An idempotency key prevents all duplicates." It prevents duplicate effects for requests with the same key within the provider's retention window; you still need idempotent consumers downstream.
  • "A rate limit is fair." It is fair to the system, not to buyers: who gets through is largely chance.
  • "Search can be the source of truth for price and stock." It is a derived, lagging copy.

Interview angle

Start with requirements and a quick estimate, and say what the read:write ratio implies. Draw the read path (CDN, cache, search fed by events) and the checkout path separately. Interviewers then probe checkout: how you prevent overselling (reservation, conditional update), how you avoid double charges (idempotency keys), how order and event stay consistent (outbox), and what happens when payment fails (compensation, TTL). Finish with the flash sale: identify the hot row as the bottleneck, and compare rate limiting with a waiting room, including the line cap and bot protection.

Model assumptions

The browse path, flash sale, rate limit and waiting room run in the simulation; it is a simplified model, not a benchmark. The browse path runs a scaled-down 200 req/s with Poisson arrivals; catalog servers have 16 workers and 10 ms of work; the catalog database has 12 connections and 40 ms reads (lognormal, cv 0.4); the cache answers a fixed 90% of reads. In the flash sale, the inventory database has 4 connections and 20 ms writes with a 300 ms pool timeout, standing in for one hot row (about 200 writes per second); the checkout server has 64 workers and room for 100 waiting requests. The rate limit is a token bucket of 150 per second with bursts of 20. In the waiting room, the queue answers buyers as soon as they are stored, and checkout workers (4 at 20 ms) drain it at about 170 per second; the engine's workers do not call the database, so their service time stands for the inventory write. Search, cart, the checkout saga and the payment failure are scripted illustrations: the engine does not model change-data capture, payment providers or compensations. Network hops take fixed 1–25 ms. All numbers, including the traffic estimate, are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements and a first estimate

    We design a shop: browse and search a catalog, keep a cart, check out and pay. Non-functional: browsing must be fast and always up; checkout must never oversell and never charge twice.

    Illustrative estimate: 10 M daily users × 20 page views = 200 M views a day, about 2,300 req/s on average and perhaps 5× that at peak. At a 2% conversion that is 200 k orders a day, about 2–3 per second. Reads outnumber writes by roughly a thousand to one, so the read path and the checkout path get different designs.

    The simulation runs a scaled-down peak of 200 req/s: two catalog servers behind a gateway, every page reading the catalog database. The database is about two-thirds busy.

    Scene: Shoppers send 200 requests per second to an API gateway, which spreads them over two catalog servers. Every request reads the catalog database, which is about two-thirds busy. Nothing fails.

    Key idea: Estimate first: the read:write ratio tells you to optimise reads and to protect writes.

  2. 2. Cache the catalog, push assets to a CDN

    Product pages change rarely and are read constantly. Two layers take the load off the database:

    - A CDN serves images, scripts and styles from the edge. Those requests never reach the gateway (the animated packets). - A cache-aside cache in front of the catalog database answers about 90% of product reads. On a miss the server reads the database and fills the cache.

    The database drops from about two-thirds busy to under 15%. Median latency falls by roughly the query time. P95 falls less: the slowest 10% are still cache misses that query the database.

    Scene: A cache now sits between the catalog servers and the database and answers about 90% of reads; the database is under 15% busy. A CDN serves static assets directly to shoppers.

    Key idea: Serve the read-heavy path from caches; the database handles misses and writes.

  3. 3. Search runs on its own index

    "Red running shoes under 100" is a full-text, faceted query that a relational catalog answers badly. Search gets a search index built for it.

    The index is fed asynchronously: when a product changes, a change event leaves the catalog database (through a transactional outbox or change-data capture), goes onto a feed, and an indexer writes it into the index. Search queries are then answered by the index alone and never touch the catalog database.

    The price: the index lags the database by the pipeline delay, so a just-changed price can show its old value in results for a moment. Product pages read the catalog (via the cache), and checkout always reprices from the source of truth.

    This step is a scripted illustration; browsing traffic is turned down to 60 req/s so the packets are easy to follow.

    Scene: A price change leaves the catalog database as an event, passes through a change feed and an indexer into the search index. Then a search query goes shopper, gateway, catalog server, search index and back, without touching the catalog database. Scripted illustration.

    Key idea: Give each query shape the store built for it, and feed derived stores asynchronously from the source of truth.

  4. 4. The cart is a keyed document

    A cart is read and written by one key: the user id, or a session id for guests. It is small, changes often, and an abandoned cart should simply expire.

    That fits a key-value store with a TTL (cart:{session} → items, expires after 30 days of inactivity) better than the catalog database. The cart service owns it, so cart writes never compete with catalog reads. When a guest logs in, their guest cart is merged into the user cart.

    The cart stores product ids and quantities, not prices: prices are taken again at checkout. Scripted illustration: add an item, then read the cart.

    Scene: A cart service with its own key-value store appears below the catalog. Adding an item writes one keyed record; reading the cart reads it back. Neither touches the catalog database. Scripted illustration.

    Key idea: Access pattern picks the store: one-key reads and writes with expiry → key-value store.

  5. 5. Checkout as a saga

    Checkout spans services that cannot share one transaction: inventory, an external payment provider (PSP) and orders. It runs as a saga, a sequence of local steps:

    1. Reserve the stock, with a TTL (say 10 minutes) so a crashed checkout cannot hold it forever. 2. Authorize the payment, sending an Idempotency-Key derived from the checkout id, so a retried call cannot charge twice. Capture happens later, at shipping. 3. Commit the order and an outbox row in one database transaction.

    The shopper gets the answer right after the commit. An outbox relay then reads the row and publishes OrderPlaced; fulfilment and email consume it afterwards. The event exists if and only if the order does. Scripted illustration.

    Scene: A checkout request reserves stock in the inventory database, authorizes the payment at the payment provider, then commits the order and an outbox row in the orders database. The shopper gets the answer; afterwards the outbox relay publishes an order event that fulfilment consumes. Scripted illustration.

    Key idea: Reserve → authorize → commit with outbox. Each step is local, idempotent and has a way back.

  6. 6. Payment fails: compensate

    The payment provider does not answer in time. Checkout retries with the same Idempotency-Key: if the first call had actually gone through, the provider returns that result instead of charging again. This time the card is declined.

    The saga cannot roll back the reservation with a database transaction, so it runs a compensating step: release the reserved stock. Only then does the shopper get the error. No order row and no outbox row are written, so fulfilment never hears about it.

    If checkout itself crashed mid-saga, the reservation’s TTL would release the stock anyway. Scripted illustration.

    Scene: Checkout reserves stock, the payment call times out and is retried with the same idempotency key, and the card is declined. Checkout then releases the reservation and returns an error. The orders database, relay and fulfilment receive nothing. Scripted illustration.

    Key idea: Sagas undo with compensations, not rollbacks; idempotency keys make retries safe.

  7. 7. A flash sale hits checkout

    Now the engine runs checkout. Every checkout writes the same hot stock row, so writers queue behind its lock: the inventory database manages about 200 checkouts per second however many servers call it. Browsing is paused here so the tiles show checkout alone.

    Buyers start at 40 per second. One second in, a limited drop goes live and 400 buyers per second hit checkout. Writes queue for a connection (some give up after 300 ms), the checkout server fills up with requests waiting on them, and then it rejects new ones outright. P95 explodes and errors pile up, for the buyers who could have been served too.

    Scene: Buyers call checkout, which writes the inventory database. At 40 buyers per second everything succeeds; when the sale opens at 400 per second, writes queue for a connection, the checkout server fills up and rejects most new requests, and P95 latency climbs sharply.

    Key idea: A flash sale concentrates writes on one row: the bottleneck is the inventory write, not the servers.

  8. 8. Option 1: rate-limit at the gate

    A token bucket at a gate in front of checkout admits 150 checkouts per second (bursts of 20) and answers the rest at once with 429 Too Many Requests.

    The inventory database now runs below its limit: admitted buyers check out quickly, with low P95, and nothing times out. The rejected buyers get a fast, honest answer instead of a slow failure.

    But more than half of all attempts are refused, and buyers will hammer refresh. A rate limit protects the system; it does not decide who gets the product fairly.

    Scene: A sale gate with a token bucket admits 150 checkouts per second and rejects the rest immediately with 429. Admitted checkouts succeed quickly and the inventory database is no longer saturated.

    Key idea: Rate limiting sheds excess load fast and keeps the bottleneck healthy, at the cost of turning buyers away.

  9. 9. Option 2: a queue-based waiting room

    Instead of refusing buyers, put them in line. A buyer’s request goes onto a waiting-room queue and is answered immediately with a ticket ("you are number 812"). Checkout workers take buyers from the line at the pace the inventory write sustains, about 170 per second.

    The sale has been running for a few seconds, so the line already holds hundreds of buyers. Two seconds in, the rush falls back to 40 per second. The line peaks above a thousand and then drains within about ten seconds; nobody gets an error.

    The line should be capped at about the available stock: once 2,000 units are spoken for, telling buyer 50,000 to wait is cruel. Tickets are also where you enforce one purchase per account and keep bots out.

    Scene: Buyers enter a waiting-room queue and get a ticket at once. Checkout workers drain the line at about 170 per second. The line grows past a thousand during the rush, then empties after traffic falls to 40 per second. No request fails.

    Key idea: Queue-based admission turns a spike into a line served at the bottleneck’s pace: no errors, but waiting time.

  10. 10. The design and its trade-offs

    The read path is cached and denormalised: CDN, catalog cache, a search index that lags by the pipeline delay. The cart is a keyed document with a TTL. Checkout is a saga with a reservation TTL, idempotent payment calls and an outbox, so events match orders exactly. During a sale, admission control protects the one hot row.

    Trade-offs to say out loud: stale prices in search (always reprice at checkout); reservation TTL length (too long hides stock, too short expires during slow payments); rate limit vs waiting room (fast refusal vs fair waiting); and whether to oversell a little and apologise, which some retailers accept for non-scarce items, versus strict reservation.

    Scene: The full design: CDN, gateway, catalog servers with cache and search index, cart service with its store, and checkout fed by a waiting-room queue, with inventory, payment provider, orders database, outbox relay and fulfilment.

    Key idea: Optimise reads with derived copies; make the money path correct with sagas, idempotency and an outbox; protect hot writes with admission control.