Build an E-Commerce Book Marketplace Backend
System DesignModel answerLast updated
Architect a scalable platform for browsing, purchasing, and tracking book orders with high-availability search and transactional inventory correctness.
Problem
You're building the backend for a large-scale book marketplace. Customers need to browse a massive catalog, search for titles, manage shopping carts, complete purchases, and track their orders. The platform must handle heavy read traffic while guaranteeing that no book is oversold and no customer is charged twice.
Functional Scope
Your system must support:
- Discovery and catalog browsing: Search by title, author, genre, or ISBN. Display book metadata, pricing, reviews, and current availability.
- Shopping cart and checkout: Let users build a cart, temporarily hold inventory while they complete payment, and finalize orders.
- Payment processing: Integrate with external payment providers, handle callbacks, and confirm transactions.
- Order management: Track orders through their lifecycle—created, paid, being prepared, shipped, delivered, or cancelled.
Non-Functional Requirements
- Partition tolerance: Catalog browsing and search should remain available even during partial outages; purchasing flows require strong consistency.
- Performance: Search responses in under 100 ms at p95; checkout completion within 500 ms at p95.
- Reliability: Prevent duplicate charges, duplicate orders, and inventory races. Recover gracefully when payment providers are slow or unavailable.
Expected Scale
- 50 million book titles in the catalog
- 10 million daily active users
- 25,000 search queries per second on average, spiking to 50,000 QPS
- 500 orders per second normally, up to 2,000 orders per second during peak events
What to Address
- API surface: Sketch the key endpoints for search, checkout, payment callbacks, and order status.
- Data layer: Choose storage technologies and design schemas for books, inventory, carts, and orders. Discuss relational vs. document/search trade-offs.
- Inventory correctness: Explain how to reserve stock during checkout without holding database locks for minutes or allowing overselling.
- Order orchestration: Describe the workflow from checkout initiation through payment to fulfillment, and how to handle partial failures.
- Search synchronization: Keep the search index fresh as inventory and catalog change.
- Fault handling: Address idempotency, retries, dead-letter queues, and monitoring for failures in the checkout pipeline.
Hints
Hint 1
Separate read-heavy catalog browsing from write-heavy transactional purchasing; eventual consistency is acceptable for search but not for inventory updates.
Hint 2
Use optimistic concurrency or conditional updates to reserve inventory atomically without long-lived locks; a version column or compare-and-set prevents race conditions.
Hint 3
Model order processing as a saga with compensating actions rather than distributed two-phase commit, since external payment APIs cannot participate in 2PC and holding locks across network calls is brittle.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements and Capacity Planning
The central challenge is reconciling two conflicting needs: catalog exploration demands low latency and high availability, while purchasing requires strict consistency to prevent overbooking and double billing. This tension informs every architectural choice.
Capacity estimates:
| Metric | Value | Design Impact |
|---|---|---|
| Catalog size | 50M titles, ~5 KB each | ~250 GB indexed data; shard across 20–30 nodes with replication |
| Search load | 50K QPS peak | Distribute across 10–15 query nodes per replica, cache hot queries at the edge |
| Order volume | 2K/s peak, ~43M orders daily | ~5–8 database writes per order (reservation, order row, line items, payment record, event log) = ~15K writes/s |
| Order data | ~2 KB per order | ~90 GB daily; partition by order ID, archive older data to cold storage |
| Read/write ratio | Roughly 25:1 | Use CQRS: dedicated read replicas and derived indexes separate from transactional stores |
2. API Design
GET /v1/search?q=&author=&genre=&isbn=&page=&size= → {items[], nextPage}
GET /v1/books/{id} → metadata + real-time stock
PUT /v1/cart/items {bookId, quantity}
POST /v1/orders Idempotency-Key: <uuid>
{cartId, address, paymentToken} → {orderId, status, ttl}
POST /v1/webhooks/payment (signed by provider; deduplicated by eventId)
GET /v1/orders/{orderId} → {status, timeline[], shipment}
POST /v1/orders/{orderId}/cancel
Key decisions:
POST /v1/ordersreturns immediately withstatus=PENDING_PAYMENTto meet the 500 ms p95 target. Payment completes asynchronously; clients poll or subscribe to updates.- Every state-changing request requires an idempotency key to make retries safe.
3. Data Storage Design
Primary transactional store (PostgreSQL, Aurora, or CockroachDB for horizontal scale):
books(id PK, isbn UNIQUE, title, author_list, genre, price_cents, version, updated_at)
inventory(book_id, warehouse_id, on_hand, reserved, version,
PK(book_id, warehouse_id),
CHECK(reserved <= on_hand AND on_hand >= 0))
reservations(id PK, order_id, book_id, warehouse_id, qty,
state ENUM(HELD, COMMITTED, RELEASED), expires_at, created_at)
orders(id PK, user_id, state ENUM(...), total_cents,
idempotency_key, version, created_at,
UNIQUE(user_id, idempotency_key))
order_lines(order_id, book_id, qty, unit_price_cents)
payments(id PK, order_id UNIQUE, provider_txn_id, state, amount_cents, retries)
order_history(order_id, seq, from_state, to_state, timestamp)
outbox(id PK, aggregate_id, event_type, payload_json, published_at)
webhook_dedup(provider_event_id PK, processed_at)
Auxiliary stores:
- Carts: Redis or DynamoDB keyed by user ID, with a 30-minute TTL. Loss is tolerable.
- Search index: Elasticsearch or OpenSearch holding denormalized documents with title, author, genre, ISBN, price, rating, and a coarse availability indicator ("in stock" vs. "low stock" vs. "out of stock"). This is a projection, never authoritative for checkout.
Trade-off: The search index trades consistency for speed. Checkout always validates live inventory from the primary database.
4. Architecture Overview
Client → CDN → API Gateway (authentication, rate limiting)
├─ Search Service → Elasticsearch cluster + Redis query cache
├─ Catalog Service → PostgreSQL read replicas + Redis object cache
├─ Cart Service → Redis cluster
└─ Order Service → Orders database
└─ Orchestration engine (Temporal or Step Functions):
Inventory Service → Inventory DB
Payment Service → Stripe/Adyen API
Fulfillment Service → Warehouse/shipping APIs
Change data capture (Debezium) or transactional outbox → Kafka
→ Search Indexer, Push Notifications, Analytics, Data Warehouse
5. Critical Design Details
Inventory Reservation Without Blocking
Never hold a row lock during user think-time. Instead, use a single atomic update:
UPDATE inventory
SET reserved = reserved + :qty, version = version + 1
WHERE book_id = :book AND warehouse_id = :wh
AND on_hand - reserved >= :qty
RETURNING version;
If rows_affected = 1, insert a reservation row with state=HELD and expires_at = now() + 10 minutes. If zero rows affected, stock is insufficient.
Completion paths:
- Payment succeeds → set reservation to
COMMITTED, thenUPDATE inventory SET on_hand = on_hand - :qty, reserved = reserved - :qty. - Payment fails or expires → set reservation to
RELEASED, thenUPDATE inventory SET reserved = reserved - :qty.
Multi-item carts: Reserve all books in a single transaction, locking rows in ascending book_id order to avoid deadlocks.
Hot items: For bestsellers that sell thousands per second, place a Redis counter in front as an admission control layer using DECRBY in a Lua script. The database remains authoritative.
Order Workflow Using Saga Pattern
Avoid distributed two-phase commit. Payment providers cannot participate in 2PC, and holding database locks across network I/O is fragile.
Instead, model the order as a state machine:
CREATED → INVENTORY_RESERVED → PENDING_PAYMENT → PAID → FULFILLING → SHIPPED → DELIVERED
Compensations:
- Payment declined → release reservations → transition to
CANCELLED. - User cancels after payment → initiate refund, release or restock inventory.
Safety mechanisms:
- Every state transition is a conditional update:
UPDATE orders SET state='PAID' WHERE id=? AND state='PENDING_PAYMENT'. Duplicate events become no-ops. - Write state changes and domain events atomically using the transactional outbox pattern to avoid dual-write inconsistencies.
- Use Temporal or a similar workflow engine for durable timers (reservation expiry), automatic retries with exponential backoff, and visibility into stalled workflows.
End-to-End Idempotency
- Client → Order Service: The unique constraint on
(user_id, idempotency_key)ensures retries return the existing order. - Order Service → Payment Provider: Send
order_idas the provider's idempotency token. Duplicate requests will not create multiple charges. - Payment Webhook → Order Service: Verify the cryptographic signature, then insert
provider_event_idintowebhook_dedupwithin the same transaction as the state update. Duplicates receive a 200 response with no side effects.
Search Index Synchronization
Writes flow to PostgreSQL. A CDC pipeline (Debezium) or outbox consumer publishes events to Kafka, which feeds the search indexer. The indexer updates Elasticsearch asynchronously.
Reads for search hit Elasticsearch backed by a Redis cache (60-second TTL) for popular queries. Detail pages and cart overlays fetch live stock counts from the inventory service or cache, so staleness in the search index only affects list-view badges.
6. Monitoring and Failure Handling
Key metrics:
- Checkout funnel completion rate by step
- Payment provider latency and error rate
- Reservation expiration rate (signals friction in checkout UX)
- Saga duration (workflows stuck in
PENDING_PAYMENT> 15 minutes indicate a problem) - Kafka consumer lag and indexing delay
- Database connection pool saturation
Alerts:
- Checkout failure rate exceeds baseline by 3 standard deviations
- Payment errors above 5%
- Dead-letter queue depth > 0 for critical topics
- Inventory reservation wait time p99 > 200 ms
Failure recovery:
- Dead-letter queues: Poison messages land in a DLQ after retry exhaustion. Operators inspect and replay manually. Idempotent handlers make replay safe.
- Payment provider outage: Circuit breaker opens after repeated failures. Return a user-friendly error and queue the order for retry. Notify the customer when payment succeeds.
- Database replica lag: Route checkout reads to the primary or use quorum reads to avoid reading stale reservation state.
Common Mistakes
- Using
SELECT ... FOR UPDATEand holding the lock during checkout, which causes timeouts and contention under load. - Skipping idempotency keys and relying on "best effort," which guarantees duplicate charges during network retries.
- Treating the search index as authoritative for stock levels, leading to checkout failures and poor user experience.
- Attempting two-phase commit across databases and external APIs, which is unimplementable and blocks under failure.
- Ignoring the transactional outbox, causing lost or duplicated events when publishing fails after a database commit.
Complexity: Storage is O(books + orders), dominated by historical order data. Search and checkout scale horizontally by sharding.