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:
- Reserve stock for the items, with an expiry (for example 10 minutes). A conditional update (
available >= qty) or a reservation row makes overselling impossible. - 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.
- 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.