Build a Scalable Storefront for Selling Books Online
System DesignModel answerLast updated
Design a book-selling web platform covering catalog search, cart, checkout and orders, with emphasis on inventory correctness, idempotent payments, caching, and fault tolerance.
You are asked to design the backend for an online shop that sells books. Customers must be able to look through the catalog and buy items.
In your answer, cover the following:
- Requirements. Ask clarifying questions and separate functional needs from non-functional ones (latency, availability, consistency, security). State what you consider out of scope.
- Scale assumptions. Estimate traffic, order volume, catalog size and storage.
- APIs. Define endpoints for search and browsing, product detail, cart, checkout, payment, and order history.
- Data model. Cover books, authors, inventory, pricing, users, carts and orders.
- Architecture. Describe service boundaries, the choice between SQL and NoSQL for each store, search indexing, caching and CDN usage, and the main read and write paths.
- Checkout correctness. Explain how stock is reserved and kept consistent during purchase, and how order and payment creation stay idempotent.
- Cross-cutting concerns. Security and privacy, observability, capacity planning, scalability, availability and fault tolerance.
Be explicit about trade-offs and about what happens when components fail.
Hints
Hint 1
Estimate first: browsing is read-heavy (on the order of 100:1) while purchasing is rare but must be exactly right. Treat these as two different problems, caching and search for one, correctness for the other.
Hint 2
Treat checkout as a multi-step workflow with explicit states (order created, stock reserved, payment authorized, confirmed) and a compensating action for each step. Reserve stock with a single conditional atomic update, and give reservations an expiry.
Hint 3
Every write that can be retried (order creation, payment) needs a client-supplied idempotency key backed by a unique constraint. For events, write to an outbox table in the same transaction as the state change instead of writing to the DB and the message bus separately.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements
Functional
- Search and browse by title, author, ISBN and category, with filters and sorting.
- Product detail page: metadata, price, availability, images, rating summary.
- Cart for guests and signed-in users.
- Checkout with address, shipping option and payment, then confirmation.
- Order history and status.
Out of scope (state it): review authoring, recommendations, third-party sellers, e-books/DRM, returns.
Non-functional
- Read:write ratio around 100:1; browse p99 under 200 ms.
- Checkout must be correct: no overselling beyond policy, no double charge, no lost order.
- Availability: 99.99% for browse, 99.95% for checkout. Browse may degrade (stale price, re-checked at checkout).
- Security: minimize PCI scope, protect PII.
Estimates
- 10M daily users x 20 page views = 200M reads/day, about 2.3K QPS average, roughly 25K QPS at a 10x peak.
- 2% conversion gives about 200K orders/day (2-3/s average, a few hundred/s in a flash sale).
- 10M titles x 5 KB is about 50 GB of metadata, which fits in a search cluster plus cache. Images (TB scale) go to object storage behind a CDN.
- Orders: about 150 GB/year, easy for a sharded relational store.
Key insight: browse is a caching and search problem; checkout is a correctness problem.
2. APIs
GET /v1/search?q=&category=&author=&sort=&cursor=&limit=
GET /v1/books/{id}
GET /v1/books/{id}/availability (uncached)
GET /v1/cart
POST /v1/cart/items {bookId, qty}
PATCH|DELETE /v1/cart/items/{bookId}
POST /v1/checkout {cartId, addressId, shipping} Idempotency-Key header
POST /v1/orders/{id}/payment {paymentToken} Idempotency-Key header
GET /v1/orders?cursor= GET /v1/orders/{id}
- Cursor pagination, not offsets, so deep pages stay cheap and stable.
- The client obtains a payment token from the payment provider's hosted fields, so card numbers never reach our servers.
- Prices on browse pages are informational; checkout re-prices on the server.
3. Data model
- Catalog (SQL source of truth, denormalized to search and cache):
books,authors,book_authors. - Pricing:
prices(book_id, currency, list, sale, valid_from, valid_to, version). Orders store a price snapshot. - Inventory (SQL, strongly consistent):
inventory(sku, warehouse, on_hand, reserved, version); available = on_hand - reserved.reservations(id, order_id, sku, qty, status, expires_at). - Users:
users,addresses, with PII encrypted. - Cart: key-value store keyed by user ID or guest token, with a TTL for guests. Eventual consistency is fine.
- Orders (SQL, sharded by user_id):
orders(with a uniqueidempotency_key, address snapshot, totals),order_items(unit price snapshot),payments(provider reference, unique idempotency key).
4. Architecture
Client -> CDN -> API gateway (auth, rate limiting, WAF) -> services: Search (OpenSearch), Catalog (Postgres + Redis), Pricing, Inventory (SQL sharded by SKU), Cart (DynamoDB/Redis), Checkout/Order orchestrator, Payment (external provider), User. A Kafka bus carries events such as CatalogUpdated, PriceChanged and OrderPlaced to the search indexer, notifications, fulfillment and analytics.
Storage rationale
- SQL where invariants matter (inventory, orders, payments).
- Key-value for carts: high write rate, simple access, TTL.
- Search engine for full-text and facets.
- Redis for hot catalog and price reads.
Read path: the product page uses cache-aside in Redis with a 5-15 minute TTL. Catalog changes flow through change data capture to Kafka, then invalidate cache and reindex search (seconds of lag is acceptable). Availability is shown as coarse buckets ("In stock", "Only 3 left") from a short-TTL cache and is never trusted at purchase time.
5. Checkout and consistency
Model checkout as a saga: CREATED -> INVENTORY_RESERVED -> PAYMENT_AUTHORIZED -> CONFIRMED, with compensations leading to CANCELLED.
- Create order idempotently. Insert with a unique idempotency key; on conflict return the existing order. Re-price on the server and snapshot prices and address.
- Reserve stock with one conditional atomic update per SKU:
Zero rows updated means out of stock, so fail fast. Write a reservation row with a 15-minute expiry in the same transaction. For multi-item carts, lock SKUs in sorted order to avoid deadlocks and release partial reservations on failure.UPDATE inventory SET reserved = reserved + :q WHERE sku=:s AND warehouse=:w AND on_hand - reserved >= :q; - Authorize payment with the provider, passing our idempotency key so retries cannot double-charge.
- Confirm. In one transaction, mark the order confirmed, commit the reservations and insert an
OrderPlacedrow into an outbox table. A relay publishes the outbox to Kafka, which avoids the dual-write problem between DB and bus. - Capture at shipment; fulfillment then decrements
on_handandreserved.
Failure handling
- A sweeper releases expired reservations and voids authorizations for orders stuck in non-terminal states.
- On a provider timeout, query the provider by idempotency key before retrying. Never blindly re-charge.
- Provider webhooks are deduplicated by event ID and processed idempotently; consumers of Kafka events must be idempotent too.
6. Cross-cutting concerns
- Hot items (flash sales): a single inventory row becomes a hotspot. Options: split stock across several counter rows per SKU, or queue purchase attempts for that SKU. Trade-off: slightly more complexity versus fewer lock conflicts.
- Scalability: stateless services behind autoscaling; shard orders by user and inventory by SKU; read replicas for catalog; CDN for images and cacheable page fragments.
- Availability: multi-AZ databases, circuit breakers and timeouts around the payment provider, graceful degradation (serve stale catalog if the search cluster is down, hide recommendations, keep checkout isolated from browse load).
- Security: TLS everywhere, tokenized payments to keep PCI scope small, encrypted PII, rate limiting and bot protection on search and checkout, authorization checks so users only see their own orders.
- Observability: metrics on latency percentiles, cache hit rate, reservation failure rate, and payment success rate; distributed tracing keyed by order ID; alerts on orders stuck in a state longer than expected; reconciliation jobs comparing provider records to our payments table.
- Capacity: the working set (50 GB of catalog) fits in memory across a small Redis and search cluster. Size for the 25K QPS peak with headroom, and load test checkout at several times the expected flash-sale rate.
Common mistakes
- Trusting cached availability when deciding whether to sell.
- Reading stock and then writing it in separate steps (a race) instead of one conditional update.
- Charging without an idempotency key, or retrying a timed-out charge without checking the provider.
- Publishing events and writing the database as two independent operations.
- Holding reservations forever because no expiry or sweeper exists.
- Storing card data yourself and inflating PCI scope.