E-commerce
What we are building
Section titled “What we are building”An online shop sells physical goods. A shopper browses a catalog, puts items in a cart and checks out. Behind the checkout the shop must set aside the stock, take the payment and record the order. The difficulty is not any one of these steps. It is that they touch different data, at different speeds, and that a failure between them must not leave an item sold twice or a payment taken for nothing.
Functional requirements. Browse and view products. Add, change and remove cart items. Check out: reserve the stock, charge the payment, create the order. See the order. Search, recommendations, reviews, shipping, tax, coupons and returns are real features and are left out, so that the lesson stays on the core.
Non-functional requirements. These are targets we choose, not figures from a real shop. A product page answers in under 200 ms at the 99th percentile. Browsing is available 99.9% of the time. An item is never sold more times than there is stock. A payment is never taken without an order, and an order is never confirmed without a payment. Checkout may take a second or two.
Scale. 100 million product views, 5 million cart changes and 500,000 checkouts a day. The busiest moments are 5 times the average.
Mental model. An online shop is two systems with the same front door. Browsing is a huge read-mostly system that a cache can carry. Checkout is a small, careful, write-heavy system where the cost of a mistake is money. Scale the first with copies, and make the second correct before you make it fast.
Estimate before you design
Section titled “Estimate before you design”The requests per second lesson gives the method. The assumptions are in the table, so that you can change them and see what moves.
| Quantity | Working | Result |
|---|---|---|
| Product views per second, on average | 100 million ÷ 86,400 | about 1,160 |
| Cart changes per second, on average | 5 million ÷ 86,400 | about 58 |
| Checkouts per second, on average | 500,000 ÷ 86,400 | about 5.8 |
| Peak, assuming 5 times the average | 1,160 × 5, 58 × 5 and 5.8 × 5 | about 5,800 views, 290 cart changes and 29 checkouts per second, 6,100 in all |
| Catalog size | 10 million products × about 5 KB | about 50 GB |
| Live carts | 2 million carts × about 2 KB | about 4 GB |
| Orders | 500,000 a day × about 2 KB | about 1 GB a day, 365 GB a year |
| Stock holds alive at the peak | 30 checkouts a second × 600 seconds of hold | at most 18,000 |
| Checkouts in flight | 30 a second × 0.4 s each (Little’s law) | 12 |
The 5 for the peak, the sizes and the 400 ms of a checkout are assumptions. The lab designs for 6,000 requests per second: 95% product views, 4.5% cart changes and 0.5% checkouts, which is 5,700, 270 and 30 per second. Three things follow whatever the exact values. Browsing is 95% of the requests and almost none of the risk. Storage is modest: the whole catalog is 50 GB, and the part people look at is far smaller. And checkout is only 30 requests per second, yet each checkout is several writes and a call to a payment provider that takes hundreds of milliseconds, and Little’s law says that 30 a second at 0.4 s is 12 checkouts in flight at any moment. The design effort goes to those 12.
The API and the data
Section titled “The API and the data”GET /products/{sku} 200 OK {"sku": "…", "name": "…", "price": 1999}PUT /carts/{cartId}/items/{sku} {"quantity": 2}POST /checkout Idempotency-Key: 7c1e… {"cartId": "…", "paymentMethod": "…"}202 Accepted {"orderId": "…", "status": "pending"}GET /orders/{orderId} {"status": "confirmed"}A checkout answers 202 Accepted with an order in the pending state, because the work finishes after the answer (the last two stages show why). The client sends an idempotency key so that a double click or a retry after a timeout returns the same order and does not make a second one.
| Data | Shape | Where |
|---|---|---|
| Product | sku, name, price, description |
The shop database, cached by sku |
| Cart | One small document per cartId, with an expiry |
A key-value store, not the database |
| Stock | sku, on_hand, reserved |
The inventory service |
| Reservation | reservation_id, order_id, sku, qty, status (held, confirmed, released), expires_at |
The inventory service |
| Order | order_id, user, status, total, unique idempotency_key |
The orders database |
| Payment | order_id, provider reference, status |
The orders database |
A cart is separate from the order on purpose. A cart is read and rewritten all the time and can be thrown away; the Dynamo paper uses the shopping cart as its leading example of data that must stay writable. An order is a record the business must keep.
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab starts with the simplest design that works and adds one thing at a time. Each stage is designed for a load, and the slider raises the load to 3 times and 10 times that, which shows where the stage runs out. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.
An online shop where shoppers browse a catalog, fill a cart and check out. Browsing dominates, carts change all the time, and a checkout must neither sell the last item twice nor lose a payment. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.
Start simple: one application and one database
Design load of this stage: 700 req/s
- What we add
- API servers answer every request from one database that holds the catalog, the carts, the stock and the orders. A checkout runs in one database transaction, so the stock check, the stock decrement, the order and the payment record commit together or not at all.
- Why: the number that forced it
- At 700 requests per second (665 product views, 31.5 cart changes and 3.5 checkouts) the average request costs 1.06 queries, so the database answers 742 queries per second against its 1,600 (8 at a time, about 5 ms each): 46%.
- What it costs
- One application, one database, and a transaction that keeps stock and orders consistent for free. The price is that browsing, carts and checkouts all compete for the same database.
- What breaks next
- At 3 times the load, 2,100 requests per second, the database is asked for 2,226 queries per second against its 1,600: it is at 139% and 30% of the requests fail.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- Shop databaseHealthy46% of its capacity
- p95, whole request
- 17 ms
- p99, whole request
- 24 ms
- Requests served
- 100%700 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Browsers and apps | Healthy | <1% | 700 | 700 | 0 | 0 ms | 0 ms | 0 ms |
| API servers | Healthy | 1% | 700 | 700 | 0 | 0.35 ms | 1.5 ms | 2.3 ms |
| Shop database | Healthy | 46% | 742 | 742 | 0 | 3.5 ms | 15 ms | 23 ms |
- Traffic
- 700 req/s
- Successful
- 700 req/s
- Error rate
- 0%
- Mean latency
- 6.5 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: one application and one database | 700 req/s | 700 req/sShop database: 46%none fail | 2.1K req/sShop database: 139%30% fail | 7K req/sShop database: 464%80% fail |
| 2. Cache the catalog | 6K req/s | 6K req/sShop database: 45%none fail | 18K req/sShop database: 134%3.1% fail | 60K req/sShop database: 448%9.2% fail |
| 3. Keep carts in a key-value store | 6K req/s | 6K req/sShop database: 11%none fail | 18K req/sShop database: 33%none fail | 60K req/sShop database: 111%0.3% fail |
| 4. Give stock its own service, with reservations | 6K req/s | 6K req/sCheckout service: 9%none fail | 18K req/sCheckout service: 28%none fail | 60K req/sCheckout service: 94%none fail |
| 5. Run the checkout as a saga | 6K req/s | 6K req/sInventory service: 9%none fail | 18K req/sInventory service: 27%none fail | 60K req/sInventory service: 90%none fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- The mix is 95% product views, 4.5% cart changes and 0.5% checkouts. The shares are teaching figures, not measurements of a real shop.
- A product view costs one query, a cart change two (read the cart, write it back) and a checkout four (stock check, stock decrement, order, payment record), each about 5 ms. The counts are illustrative.
- Every number (service times, capacities, the 99% catalog hit ratio, the 400 ms of a synchronous checkout, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, cache, server or payment provider.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A flash sale, a cold cache warming up and a deploy are not modelled.
- The stock of a product is modelled as one pool of identical capacity. When every buyer wants the same product, their updates queue on one record; the lesson works that out by hand.
- A request thread held across several calls and a saga in flight are two different costs: the first holds a slot for the whole 400 ms (8 servers, 16 slots each), the second is a saved record (4 orchestrator instances, 200 in flight each). The two sizes are illustrative.
- Search, recommendations, images, shipping, tax, coupons, returns and failures of the payment provider are not modelled; the lesson covers the failures.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, one application and one database. The database holds the catalog, the carts, the stock and the orders, and a checkout is one database transaction, so stock and order stay consistent for free. A product view costs 1 query, a cart change 2 and a checkout 4, so 700 requests per second cost 742 queries per second against the database’s 1,600, which is 46%. At 3 times the load it is asked for 2,226 queries and is at 139%: 30% of the requests fail.
Stage 2, cache the catalog. The stage is designed for 6,000 requests per second, where the database alone would be asked for 6,360 queries per second. A product page changes rarely, so a cache answers 99% of the views and only 57 per second reach the database. With the 540 for cart changes and 120 for checkouts, that is 717 queries per second, 45%. At 3 times the load the cache is at 21%, but carts and checkouts, which a cache cannot absorb, ask for 2,151 queries and the database is at 134%: 3% of the requests fail.
Stage 3, carts in a key-value store. Cart changes were 540 of the 717 queries per second. In a store built for small documents with an expiry, 1,620 operations per second (at 3 times the load) are 3% of its 53,333, and the database keeps 531 queries per second, 33%. At 10 times the load, 60,000 requests per second, the 57,000 views are 71% of the cache, and the database is at 111%: 1,200 queries per second from the checkouts alone (300 checkouts of 4 queries each) and 570 from cache misses.
Stage 4, an inventory service with reservations. Two of the four queries of a checkout are the stock check and the stock decrement. They move to a service that owns the stock and works with reservations. The database falls to 1,170 queries per second at 10 times the load, 73%, and the inventory service takes 600 operations per second, two per checkout, 90% of its 667. The checkout is now a chain: reserve, charge, confirm. A checkout service makes the calls in one request and holds a slot for the 400 ms the chain takes. At 10 times the load that is 120 checkouts in flight against the 128 slots of 8 servers, and the checkout service is at 94%.
Stage 5, a checkout saga. The checkout service saves the order as pending and answers at once. A saga orchestrator runs the steps and keeps its state after each one. The 120 checkouts in flight are now 120 saved records out of room for 800, so the orchestrator is at 15% and the checkout service at 5%. At 10 times the load nothing is overloaded. The inventory service is the first to saturate, at 90%, because every buyer of a popular product reserves the same stock record, and the payment provider is at 75%.
Reserving stock
Section titled “Reserving stock”The invariant is that units sold plus units held never exceed units in stock. The way to keep it is to let the database check it in the same statement that changes it.
UPDATE inventorySET reserved = reserved + :qtyWHERE sku = :sku AND on_hand - reserved >= :qty;-- one row changed: the units are held for you. Zero rows: not enough stock.Reading the stock, comparing it in the application and writing it back are three steps in which two buyers can both read “1 left”. The single statement leaves no gap. When two of them run at once on one row, the database makes the second wait for the first, then evaluates the condition on the row as the first left it. The PostgreSQL documentation describes this for its default isolation level, and the locks and MVCC lesson explains the waiting.
A reservation is a hold. It has an expiry, here 10 minutes, so that a shopper who walks away does not keep units for ever. When the payment succeeds the hold is confirmed: on_hand and reserved both fall. When it fails, or when the hold expires, it is released: reserved falls and the units are available again. To make release safe to repeat, change the reservation’s status and the counter in one transaction, and only when the status was held. A second release finds nothing to change.
The checkout as a saga
Section titled “The checkout as a saga”With the stock, the orders and the payment in three places, no transaction covers a checkout. A saga replaces it by a sequence of local steps, each with an action that undoes it.
| Step | Action | If a later step fails |
|---|---|---|
| 1 | Save the order as pending | Mark it cancelled |
| 2 | Reserve the stock | Release the reservation |
| 3 | Charge the payment, with the order id as idempotency key | Refund |
| 4 | Confirm the reservation and the order | Retry: the money is taken, so go forward |
If step 2 finds no stock, the saga cancels the order and nothing else needs undoing. If step 3 is declined, it releases the stock and cancels. If step 4 fails after the charge, the right move is to retry it, since the shopper has paid; only if the hold has expired and the units are gone does the saga refund. Every step and every compensation is idempotent, because the orchestrator retries after a crash or a timeout. The orchestrator saves its state after each step, so a new instance can pick up the sagas of one that crashed.
Between steps, other readers see an intermediate state: stock held, order not paid. That is why the order has a pending status and why the shopper is told “processing”. The saga lesson calls this the lack of isolation between steps. Helland’s paper describes the same idea, work that is tentative until it is confirmed or cancelled, as the way to live without distributed transactions.
When everybody wants the same item
Section titled “When everybody wants the same item”The lab treats stock as a pool. A flash sale is the case where it is not. If 50,000 shoppers press buy in a minute for 100 units, they update one row. Suppose each update holds the row for 5 ms. One row serialises about 1 ÷ 0.005 = 200 updates per second, and 50,000 attempts take 50,000 ÷ 200 = 250 seconds to get through, though the 100 units are gone in half a second. After the 100th unit, each attempt changes no row, but it still waits its turn.
The remedies take attempts off the row. A “sold out” flag in a cache answers most of them without a query. A waiting room admits buyers a few hundred at a time. Splitting the stock into several counters, for example 10 counters of 10 units, spreads the updates over 10 rows, at the price that one counter can say “sold out” while another still has units. This is the hot key of the caching module again, in a database row instead of a cache entry.
What happens if the payment provider does not answer
Section titled “What happens if the payment provider does not answer”The charge call times out. The shop does not know whether the money was taken. Releasing the stock now could sell the units twice, and retrying without care could charge twice. The idempotency key resolves it: a retry with the same key returns the original result instead of charging again, as Stripe’s API reference describes for its API, and the saga can ask the provider for the outcome. Until it knows, the order stays pending and the hold stays held. At 10 times the load the lab’s provider is at 75% of its capacity, so an outage or a limit on the provider’s side is what a retry storm would meet.
What happens if the hold expires during the payment
Section titled “What happens if the hold expires during the payment”A slow payment can outlast the hold. Another shopper then reserves the units. When the payment succeeds, the confirm step finds the hold released, and if the stock is gone the saga must refund. Two protections help: extend the hold when the payment starts, and make the confirm step check before it counts. Both cost little compared with a refund and an apology.
What happens if the inventory service is down
Section titled “What happens if the inventory service is down”A checkout cannot reserve stock, so the saga cancels the order and the shopper is told to try again. Browsing and carts are unaffected: in the lab the view and cart paths do not touch the inventory service. This is the benefit of splitting by what each part needs. The service that must be exact is small and can fail on its own; the large read path stays up.
Trade-offs
Section titled “Trade-offs”Each row is a decision in the lab, written with what it buys, what it costs and when the other choice is better.
| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| Cache the catalog | The database drops from 6,360 to 717 queries per second | Stale prices for a short time, and a cache to run | When the catalog is small enough to serve from the database, or a price must never be stale |
| Carts in a key-value store | 1,620 operations per second leave the database | A second store, and a cart that is not durable like an order | When carts are few: one database is simpler |
| Reserve stock with an expiring hold | No overselling, and abandoned carts give units back | A service to run, expiry to manage, units tied up during a hold | When stock is plentiful: decrement at the end and handle the rare shortage |
| Run the checkout as a saga | 120 checkouts in flight cost 15% of the orchestrator, not 94% of the request slots | Pending orders, compensations, intermediate states | When all the data fits in one database: use one transaction |
| Reserve at the start of checkout, not at “add to cart” | Only shoppers about to pay hold stock, so few holds are abandoned | An item in the cart can be gone when the shopper checks out | For scarce goods such as tickets, hold early and accept the many abandoned holds |
Defend your design
Section titled “Defend your design”An interviewer asks for a shop in 45 minutes and then asks about the last item. A good answer starts with the numbers (browsing is the load, checkout is the risk), builds the stages in the order the numbers force them, and says out loud what each one costs. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
A shop sells 100 units of one product in a flash sale, and 50,000 shoppers press ‘buy’ in the same minute. How do you make sure you never sell more than 100, and what happens to a shopper who reserves an item and then does not pay?
Assume the stock is one record in an inventory service, a payment takes about 300 ms at the payment provider, and a reservation can be held for 10 minutes.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 60 characters written to unlock the strong answer
- At the peak, about 5,800 views, 290 cart changes and 29 checkouts per second: browsing is 95% of the requests and checkout is the part that needs care. 30 checkouts a second at 0.4 s are 12 in flight.
- One database is at 46% at 700 requests per second and at 139% at 3 times that. A catalog cache cuts 6,360 queries per second to 717 at 6,000 requests per second.
- Carts, which a cache cannot absorb, go to a key-value store: 1,620 operations per second leave the database and it drops from 134% to 33% at 3 times the load.
- One conditional statement reserves stock without a gap, and a reservation with an expiry is confirmed on payment and released on failure. A checkout across services is a saga of steps with compensations, each idempotent.
- A synchronous checkout holds 120 of 128 slots at 10 times the load (94%). As a saga it uses 15% of the orchestrator. Then the inventory service saturates at 90%, because a popular product is one record.
Next: Payment system, where the hard parts are idempotency, a ledger and reconciliation.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.