Scalable Backend for a High-Traffic Book Retail Platform
System DesignModel answerLast updated
Design the backend of a book-selling website that survives flash sales, with fast search, no overselling of stock, and safe recovery when payment and inventory steps fail partway.
Build the Backend for a Book Retail Website
You are asked to design the server side of a web store that sells books to millions of shoppers. Traffic is normally steady but spikes sharply during promotions, and the system must stay up when individual components break.
What the product must do
- Shoppers find books by title, author, or genre.
- Shoppers open a book page showing details, price, and whether it is in stock.
- Shoppers fill a cart and check out.
- Staff can change stock counts and prices.
Quality goals
- Availability: a failing component should not take down the whole store.
- Elasticity: sudden surges, such as a limited-time sale, must be absorbed.
- Consistency: stock counts must never allow selling more copies than exist. Search results may trail the truth by a few seconds.
Please address
- Service boundaries: which services exist and what each owns.
- Storage choices: for the catalog, user accounts, and order history, with reasons.
- Search: how books are indexed and kept up to date to support fast, flexible queries.
- Concurrent purchases: how you stop many buyers of the same title from corrupting the stock count.
- Partial failures: what happens when, for example, the card is charged but the stock update fails, and how the system recovers.
State your traffic assumptions with numbers before you design.
Hints
Hint 1
Split the system into a read-heavy browse/search side that tolerates staleness and a write-heavy checkout side that must be exactly right, and spend most of your effort on the second.
Hint 2
For stock, compare locking approaches. A single conditional UPDATE (decrement only if enough remains) avoids both long locks and retry storms. Pair it with time-limited reservations so no lock is held while calling the payment provider.
Hint 3
For failures, think saga plus idempotency: each step has a compensating action, requests carry an idempotency key, and a reconciliation job repairs anything left half-finished (for example, a charge with no committed stock).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Treat the system as two halves. The browse/search path is read-heavy and can be cached and eventually consistent. The checkout/inventory path is write-heavy, contended, and must be correct. Most of the design effort belongs in the second.
1. Assumptions and scale
- 50M registered users, 10M daily active, about 20 page views or searches each: roughly 200M reads/day, about 2.3K QPS average. A 20x flash-sale peak gives about 50K read QPS.
- 1M orders/day (about 12/s), but a flash sale may reach several thousand orders/s concentrated on a few hot titles.
- Catalog of 20M titles at about 5 KB is about 100 GB, which fits in one sharded store. Orders at about 2 KB each add roughly 750 GB/year.
- Payments go through an external provider that supports authorize then capture.
2. Services and storage
| Service | Owns | Storage |
|---|---|---|
| Gateway | Auth, rate limiting, load shedding | none |
| Catalog | Metadata, prices | PostgreSQL, fronted by Redis and a CDN |
| Search | Queries | Elasticsearch/OpenSearch |
| User | Accounts, addresses | PostgreSQL sharded by user_id |
| Cart | Temporary carts | Redis with TTL and periodic durable snapshot |
| Inventory | Stock, reservations | ACID relational DB sharded by SKU |
| Order | Order lifecycle, saga coordinator | PostgreSQL sharded by user_id |
| Payment | Provider wrapper, idempotent ledger | PostgreSQL |
Kafka carries events (BookUpdated, OrderPlaced, PaymentAuthorized, InventoryReserved). Each service owns its data; no shared databases. Order items copy the unit price at purchase time so later price edits never rewrite history. Orders are sharded by user so "my orders" hits one shard; old orders move to cold storage.
3. Search
- Index title (analyzed, plus n-gram subfield for typeahead), authors, genres (keyword for facets), price, popularity, and an
in_stockflag. - About 5 primary shards hold 20M documents; add replicas for read throughput.
- Pipeline: change data capture on the catalog DB, into Kafka, into an indexer that upserts using the row
versionas an external version so out-of-order events cannot overwrite newer data. Lag of a few seconds is acceptable. - Rank with BM25 plus a popularity boost; use aggregations for facets.
in_stockin search is only a hint; the authoritative check happens at reservation time.- Rebuild by creating a new index and swapping an alias atomically.
4. Concurrent purchases
Goal: 10,000 buyers racing for 500 copies produce exactly 500 successes.
- Pessimistic lock (
SELECT ... FOR UPDATE): correct, but serializes buyers and is dangerous if held across a payment call. - Optimistic versioning: great at low contention, but on a hot title nearly everyone conflicts and retries, causing a retry storm.
- Atomic conditional decrement (recommended):
UPDATE inventory
SET available = available - :qty, reserved = reserved + :qty
WHERE sku = :sku AND available >= :qty;
One row updated means reserved; zero means sold out. The lock lasts microseconds and there is no read-modify-write race. In the same transaction insert a reservation with expires_at = now() + 15 min.
Lifecycle: payment success marks the reservation committed; failure or expiry releases it, with a sweeper returning expired stock. This separates holding stock from taking money, so no lock spans a network call.
Hot titles: one row still tops out at a few thousand updates/s. Mitigations:
- A Redis counter gate (Lua script, decrement only if it stays at or above zero) rejects excess buyers cheaply; the DB remains the source of truth.
- Split stock across several rows (buckets) and pick one at random.
- A virtual waiting room at the gateway to meter admissions.
5. Failure handling
Use an orchestrated saga run by the Order service, with each step idempotent and compensatable:
- Create order as
PENDING(unique idempotency key). - Reserve stock (conditional decrement).
- Authorize payment.
- Commit reservation, capture payment, mark order
CONFIRMED.
Compensations: if authorization fails, release the reservation and cancel the order. If capture or commit fails after authorization, void the authorization or refund, then release stock.
The "paid but stock update failed" case: because we reserve before charging and only authorize (not capture) until stock is committed, this case mostly becomes a voidable authorization. If it still occurs, a reconciliation job compares the payment ledger against orders and reservations and either completes the order or refunds.
Supporting mechanisms:
- Idempotency keys on order placement and on every provider call, so client or service retries never duplicate orders or charges.
- Transactional outbox: write the state change and its event in one local transaction, then publish, to avoid lost or phantom events.
- Saga state persisted so a crashed orchestrator resumes where it left off.
- Timeouts, retries with backoff and jitter, circuit breakers, and graceful degradation (serve cached catalog if search is down).
- Multi-AZ deployment, replicated databases with automatic failover, autoscaled stateless services.
Trade-offs
- Strong consistency for stock costs throughput on hot items, which is why the gate and bucketing exist.
- Eventual consistency in search keeps it fast but can briefly show stale stock or prices; the checkout check corrects this.
- Reservations can hold stock from abandoned checkouts; a short TTL balances fairness and sell-through.
Common mistakes
- Holding a database lock or transaction open while calling the payment provider.
- Read-then-write stock updates without a conditional guard.
- Skipping idempotency, producing duplicate orders on retry.
- Sharing one database among services.
- Treating search stock status as authoritative.
- Using distributed two-phase commit across the payment provider instead of a saga.