Backend Architecture for High-Traffic Online Retail Platform
System DesignModel answerLast updated
Design a scalable backend for an online retail platform that handles concurrent purchases, prevents overselling, and serves millions of browsing users.
Problem Statement
You need to architect the backend for a large-scale online retail platform that serves millions of shoppers daily and experiences traffic surges during promotional events.
Core Features
Your system must support:
- Product browsing and detail viewing
- Shopping cart management
- Order checkout that accurately tracks inventory
Critical Constraints
- Inventory Accuracy: Stock levels must remain non-negative; selling more units than available is unacceptable
- Scale: The platform must accommodate traffic spikes that are 10x normal load
- Correctness: Users must not be charged multiple times for a single purchase attempt
What to Provide
- Describe the overall system architecture, identifying major components (load distribution, API layer, services, storage)
- Define how you would structure storage for products, stock quantities, and purchase records
- Explain your approach to the concurrent purchase problem: when thousands of shoppers simultaneously attempt to buy a limited-stock item
- Walk through the complete flow for processing a purchase, including your strategy for preventing duplicate orders
Hints
Hint 1
Consider separating read-heavy operations from write-heavy operations in your architecture
Hint 2
Think about what guarantees you need from your database when decrementing inventory
Hint 3
Client-generated unique identifiers can help ensure operations are processed exactly once
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Backend Architecture for High-Traffic Online Retail Platform: Model Answer
1. Establish Scale and Traffic Patterns
Begin by quantifying the system's demands:
| Dimension | Estimate |
|---|---|
| Total users / daily active | 100M / 10M |
| Product SKUs | 50M |
| Browse traffic (typical / peak) | 50K requests/sec / 500K requests/sec |
| Purchase rate (typical / peak) | ~12/sec (~1M daily) / ~5K/sec |
| Contention scenario | 100K concurrent attempts for 1,000 available units |
Key observations:
- Read-to-write ratio is roughly 100:1. Product browsing should be cacheable and served from the edge.
- Write volume is manageable, but concentrated. The challenge is handling simultaneous updates to the same inventory record, not total throughput.
Correctness is non-negotiable for inventory and payment, but catalog data and displayed stock can tolerate slight staleness.
2. API Contract
GET /products?q=&page= -> product list (cacheable)
GET /products/{id} -> product details + stock estimate
POST /cart/items {sku, quantity}
DELETE /cart/items/{sku}
POST /orders Idempotency-Token: <uuid>
{cartId, shippingAddress, paymentInfo}
-> 202 {orderId, status: "processing"}
GET /orders/{id} -> order state
The POST /orders endpoint returns 202 Accepted because payment and fulfillment happen asynchronously. The order is acknowledged immediately but not yet finalized.
3. System Architecture Overview
Users -> CDN (static assets, cached product pages)
-> Load Balancer -> API Gateway (authentication, rate limits)
|
|-- Product Service -> Redis -> Product DB (read replicas)
| -> Elasticsearch (search index, updated via CDC)
|
|-- Cart Service -> Redis (user sessions) / DynamoDB
|
|-- Order Service -> Order DB (Postgres, partitioned by user_id)
| |
| |-- Event Stream (Kafka) -> Payment Worker
| -> Fulfillment Worker
| -> Notification Worker
|
|-- Inventory Service -> Inventory DB (Postgres, partitioned by sku_id)
-> Redis (hot item counters)
All services are horizontally scalable and stateless. The API Gateway enforces per-user rate limits and per-SKU throttling. During flash sales, it can implement a virtual queue that controls admission rates.
4. Storage Design
Product Catalog tolerates eventual consistency and has varied attributes. Use a document store or Postgres with JSONB columns, fronted by Redis and CDN caching.
products(id, name, description, attributes, price_cents, last_modified)
Inventory requires strong consistency and atomic updates. Use a relational database with constraints:
inventory(sku_id PRIMARY KEY,
available INTEGER CHECK (available >= 0),
reserved INTEGER,
version BIGINT)
Orders need ACID transactions and an audit trail. Relational storage, sharded by user_id:
orders(id PRIMARY KEY, user_id, state, amount_cents, created_at)
order_lines(order_id, sku_id, quantity, price_cents)
idempotency_registry(user_id, token, order_id, response_snapshot, created_at,
PRIMARY KEY (user_id, token))
event_outbox(id PRIMARY KEY, aggregate_id, event_type, payload, published BOOL)
Shopping Carts have high churn and losing one is acceptable. Store in Redis with persistence or DynamoDB.
Why relational for inventory? NoSQL provides horizontal scaling but typically offers only single-item atomic operations, making multi-SKU checkouts awkward. Relational databases provide CHECK constraints and multi-row transactions. Since inventory partitions cleanly by SKU, sharded Postgres scales adequately. DynamoDB with conditional writes is viable if you accept single-item atomicity limitations.
5. Order Processing Flow and Duplicate Prevention
-
Client generates a UUID Idempotency-Token for each checkout attempt and includes it on all retries.
-
Order Service attempts to insert
(user_id, token)into the idempotency registry.- On unique constraint violation, return the previously stored response.
- This prevents creating multiple orders for the same user action.
-
Atomic inventory reservation:
UPDATE inventory SET available = available - ?, reserved = reserved + ? WHERE sku_id = ? AND available >= ?- If zero rows updated, the item is out of stock. Abort and return failure.
- For multi-item carts, lock rows in deterministic order (by SKU) to prevent deadlocks.
-
Within the same database transaction, create the order record (state:
PROCESSING) and append an event to the outbox table. -
Return
202 {orderId}immediately. -
A separate worker consumes the outbox (via polling or CDC) and publishes to Kafka.
-
Payment Worker picks up the event and calls the payment provider, using the orderId as the provider's idempotency key. This prevents duplicate charges even if the event is redelivered.
-
On payment success, transition inventory from reserved to sold and mark order as
CONFIRMED. On failure, run compensation logic to release the reservation.
Idempotency at every layer. Kafka consumers dedupe by event ID since Kafka guarantees at-least-once delivery. Inventory reservations carry a TTL; abandoned checkouts automatically return stock after expiration.
6. Handling Concurrent Purchases of Limited Inventory
When 100K users compete for 1,000 units, naive approaches create lock contention that degrades database performance. Use layered defenses:
1. Pre-filter with Redis
- Preload
inventory:{sku} = 1000in Redis - Use a Lua script for atomic check-and-decrement:
local stock = redis.call('GET', KEYS[1]) if tonumber(stock) >= tonumber(ARGV[1]) then return redis.call('DECRBY', KEYS[1], ARGV[1]) else return -1 end - Requests receiving a token proceed to the database; others get immediate "sold out" responses
- Database now sees ~1,000 writes instead of 100K
- Database remains the source of truth; the conditional SQL prevents overselling even if Redis over-admits
2. Partition the counter
- Split stock across N buckets (
sku#0throughsku#N-1, each holding stock/N units) - Requests select a random bucket and retry other buckets on exhaustion
- Multiplies throughput by approximately N
3. Queue-based serialization
- Partition Kafka by
sku_idso one consumer handles each SKU sequentially - Eliminates lock contention entirely
- Users receive "processing" status and get notified of the outcome
4. Edge-layer protection
- Virtual waiting room controls admission rates
- Per-user purchase quantity limits
- CAPTCHA or bot detection
- Cache
sold_outflags to disable "Buy" buttons without database queries
Avoid distributed locks like Redlock for this use case. They add latency per request and have correctness concerns under clock skew or GC pauses. Atomic decrements are simpler and faster.
7. Key Trade-offs
-
When to reserve stock: Reserving at cart addition lets users hoard inventory. Reserve at checkout with a TTL to release abandoned purchases.
-
Synchronous vs. asynchronous confirmation: Async processing absorbs traffic spikes and enables retries but requires polling or webhooks for status. Synchronous processing is simpler but fails under load spikes.
-
Strict vs. approximate stock display: Showing exact counts requires real-time queries. Showing approximate counts (refreshed every few seconds) enables aggressive caching. For hot items, hide exact counts and show "Limited stock" instead.
-
SQL vs. NoSQL for inventory: SQL provides transactions and constraints but requires careful sharding. NoSQL scales more easily but offers weaker consistency guarantees. Choose based on whether you need multi-item atomic operations.
8. Common Pitfalls
- Forgetting idempotency: Network failures cause retries. Without idempotency, users get charged multiple times.
- Race conditions in stock checks: Checking availability in one query and decrementing in another creates a race. Use atomic conditional updates.
- Ignoring reservation cleanup: Unreleased reservations from abandoned carts permanently reduce available inventory.
- Over-optimizing for the hot item case: Most purchases don't involve contention. Don't add complexity that slows down the common path.
Complexity: The architecture has O(1) latency for reads (cache hit) and O(n) for checkout where n is the number of items in the cart (due to inventory updates). Storage scales horizontally through partitioning by user_id and sku_id.