E-Commerce Catalog and Inventory Management System Design
System DesignModel answerLast updated
Build a scalable service handling product information, pricing logic, and stock management with high read throughput and strong checkout consistency.
Problem Context
You need to architect a backend service for an online retail platform that manages three interconnected domains: product catalog data, pricing information, and stock levels. This service powers both customer-facing browsing experiences and critical checkout operations.
Shoppers view thousands of product pages per minute, checking descriptions and availability. Meanwhile, a separate order processing system coordinates with your service during purchase flows to lock inventory and validate prices. Behind the scenes, merchandising teams and automated repricing systems continuously adjust prices and promotional offers.
What You Must Support
Your design should handle:
- Product Information Retrieval: Return product descriptions, current pricing, and stock status for display on browse and search pages
- Price Modifications: Allow authorized systems to change prices with full audit trails and version tracking
- Stock Operations: Support atomic inventory checks and holds during checkout, with rollback capability if transactions fail
Scale and Performance Targets
- Catalog scope: 20 million distinct products
- Read load: Peak traffic reaches 100,000 requests/second
- Write load: 2,000 inventory or pricing changes/second normally, but individual products can see bursts of 10,000 requests/second during promotional events
- Latency requirements: Browse requests should complete within 25ms at the 99th percentile
- Consistency model:
- Browsing can tolerate multi-second staleness for inventory counts
- Checkout must enforce strict consistency—no overselling or price manipulation
- Access control: All write operations require authentication and role-based authorization
Design Areas to Address
- API contracts: Specify endpoints for reading product data, changing prices, and managing inventory reservations, including mechanisms to prevent duplicate operations
- Storage architecture: Choose appropriate database technologies for each data type and explain partitioning strategies for product metadata, pricing records, and inventory ledgers
- Performance optimization: Design caching layers and explain cache invalidation approaches; address how to handle extreme concurrency on popular items through locking strategies or alternative patterns
- Transactional integrity: Describe the interaction flow between your service and checkout systems to ensure displayed prices match charged prices and that abandoned carts properly release held inventory
Hints
Hint 1
Consider separating concerns by data volatility—catalog metadata changes infrequently while inventory fluctuates constantly
Hint 2
Flash sale scenarios create hotspot contention; evaluate whether traditional row locks suffice or if you need reservation queues
Hint 3
Design the checkout flow around immutable price quotes with expiration times to prevent exploitation of stale cached prices
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
1. Requirements Analysis and Capacity Planning
The first step is recognizing that this single service encompasses three domains with fundamentally different characteristics:
| Data Type | Change Frequency | Consistency Needs | Write Volume |
|---|---|---|---|
| Product metadata | Rare | Eventual consistency acceptable | Low, batch-oriented |
| Pricing data | Moderate | Eventual for display, strict at purchase | Bursty from algorithms |
| Inventory counts | Constant | Eventual for badges, strict for reservations | 2K/s baseline, 10K/s spikes |
Capacity estimates:
- Storage: 20M products × 2KB metadata ≈ 40GB; prices at ~200B each ≈ 4GB; inventory per warehouse adds minimal overhead
- Read path: With CDN offloading 90% of static content, origin handles ~10K QPS; Redis lookups at sub-millisecond latency easily meet the 25ms budget
- Write path: 2K/s distributes well across database shards
- Hotspot challenge: 10K concurrent writes to a single inventory row exceeds typical relational database row-lock throughput (1-3K/s), requiring special handling
2. API Design
# Customer-facing reads
GET /products/{sku}
GET /products/batch?ids={sku1,sku2,...}
# Administrative writes
POST /prices/{sku}
Body: { price, currency, promotion_id, effective_date, expected_version, change_reason }
Header: X-Idempotency-Key
# Checkout coordination (service-to-service)
POST /checkout/price-quotes
Body: { cart_id, items: [{sku, quantity}] }
Returns: { quote_id, line_items, expiration_timestamp }
POST /inventory/holds
Body: { order_id, quote_id, items: [{sku, quantity, warehouse}], timeout_seconds }
Header: X-Idempotency-Key
Returns: { hold_id, status, expiration_timestamp }
POST /inventory/holds/{id}/finalize
POST /inventory/holds/{id}/cancel
POST /inventory/{sku}/adjustments
Body: { delta, warehouse, reason, operator_id }
Key patterns:
- Idempotency: Every mutating operation requires a client-generated idempotency key stored with a unique constraint, ensuring retries return cached results rather than duplicating effects
- Optimistic concurrency: Price updates include an
expected_versionfield; mismatches reject the operation and force the caller to refresh and retry - State machines: Inventory holds transition through defined states (PENDING → HELD → COMMITTED/RELEASED) with validation preventing invalid transitions
- Authorization: All writes validate JWT scopes against role requirements; pricing engines receive limited permissions (e.g., maximum 20% price changes)
3. Storage Design
Partition by access pattern:
Product Catalog → Document database (MongoDB, DynamoDB)
- Variable schemas across product categories make document storage natural
- Partition key:
sku - Each product is self-contained; no cross-document transactions needed
- Change Data Capture feeds search indexing pipeline
Pricing → Relational database (PostgreSQL, Aurora), sharded by hash(sku)
- Table:
pricing_history(sku, version, amount, currency, valid_from, valid_until, promotion_id, audit_data) - Append-only design provides automatic versioning and audit trail
- Active price query:
WHERE valid_from <= NOW() ORDER BY version DESC LIMIT 1 - Shard co-location with inventory enables local transactions
Inventory → Relational database, sharded by hash(sku) matching pricing shards
- Table:
stock_levels(sku, warehouse, on_hand, reserved, version) - Computed availability:
on_hand - reserved - Table:
holds(id, order_id, sku, warehouse, quantity, state, expires_at, idempotency_key UNIQUE) - Co-location enables transactional hold creation with balance checks
Why SQL for money and inventory: These domains demand ACID transactions (atomically creating holds while updating balances), referential integrity, and audit requirements that relational databases handle naturally.
4. System Architecture
User → CDN (product images, metadata; 5-15 min TTL)
→ Load Balancer → API Gateway (auth, rate limits)
→ Product Service
→ Redis Cluster (metadata cache, price cache, availability cache)
→ Read Replicas (fallback queries)
Order Service → Quote Service (primary DB reads for pricing)
→ Inventory Service (primary DB writes for holds)
Primary DBs → Change Data Capture (Debezium/Kafka)
→ Cache Warmer (updates Redis)
→ Search Indexer (updates Elasticsearch)
→ Analytics Pipeline
Background: Hold Expiration Worker (scans expired holds, releases inventory)
Caching strategy:
- Metadata cache: CDN serves with 10-minute TTL; merchandising updates trigger cache purges via surrogate keys
- Price cache: Redis stores
price:{sku}with version metadata, updated via CDC to prevent stale writes; browsing reads from cache, checkout reads from primary - Availability cache: Redis stores bucketed indicators ("In Stock", "Low Stock", "Out of Stock") updated via CDC; coarse bucketing reduces invalidation frequency
- Cache warming: Predictive pre-loading of trending products during traffic spikes
5. Concurrency Control for Inventory
Standard case: Conditional update within local transaction
BEGIN TRANSACTION;
-- Idempotent insert (duplicate key returns existing record)
INSERT INTO holds (id, order_id, sku, warehouse, quantity, state, expires_at, idempotency_key)
VALUES (:id, :order, :sku, :wh, :qty, 'HELD', NOW() + INTERVAL '10 minutes', :idem_key);
-- Atomic check-and-reserve
UPDATE stock_levels
SET reserved = reserved + :qty, version = version + 1
WHERE sku = :sku
AND warehouse = :wh
AND (on_hand - reserved) >= :qty;
-- Check affected rows; if zero, abort with OUT_OF_STOCK
COMMIT;
The WHERE clause predicate makes overselling impossible regardless of concurrency level.
Hot item optimization:
For flash-sale scenarios exceeding database row-lock capacity:
- In-memory reservation queue: Route high-traffic SKUs to Redis-based atomic counters (
DECRBY available_count) that gate database writes - Write batching: Accumulate reservations and flush to database in micro-batches (50-100ms windows)
- Pre-allocation: For scheduled sales, reserve inventory blocks to in-memory pools before the event starts
Hold lifecycle:
- Creation: Reserve quantity, set expiration (typically 10-15 minutes)
- Finalization: Deduct from
on_hand, subtract fromreserved, mark hold COMMITTED - Cancellation: Subtract from
reserved, mark hold RELEASED - Expiration: Background worker periodically scans expired holds and auto-cancels
6. Checkout Flow and Price Protection
Two-phase approach prevents price exploitation:
Phase 1 - Quote Generation:
- Order service sends cart to quote endpoint
- Quote service reads current prices from primary database
- Generates cryptographically signed token containing:
{cart_id, [{sku, quantity, unit_price, price_version}], issued_at, expires_at} - Quote valid for 15 minutes
Phase 2 - Inventory Hold:
- Order service presents quote token with hold request
- Inventory service validates signature and expiration
- Creates holds with conditional updates (above)
- Returns hold IDs to order service
Phase 3 - Payment & Finalization:
- Order service processes payment
- On success: calls finalize endpoints, transitioning holds to COMMITTED
- On failure: calls cancel endpoints, returning inventory to available pool
Why this works:
- Cached/stale prices shown during browsing are never directly used at checkout
- Quote signature prevents tampering with prices
- Quote expiration bounds the window for price changes between quote and purchase
- Multi-SKU carts handle partial failures via compensating transactions (saga pattern, not 2PC)
7. Monitoring and Failure Modes
Key metrics:
- Cache hit ratios per layer (target: >95% for metadata)
- p50/p99/p999 latency distributions
- Hold expiration rate (high values indicate payment gateway issues)
- Version conflict rate on price updates
- Per-SKU reservation throughput to identify hotspots early
Failure handling:
- Database failures: Degrade to read-replica serving with stale-data warnings
- Cache failures: Query databases directly with circuit breakers
- Orphaned holds: Automatic expiration worker provides eventual consistency
- Cascading failures: Aggressive rate limiting and queue-based admission control
Common Pitfalls
- Dual writes: Updating database and cache simultaneously creates race conditions; use CDC for cache invalidation
- Distributed locks: Avoid cross-service locks for inventory; conditional updates within single-database transactions suffice
- Unbounded hold duration: Always expire holds to prevent inventory deadlock from abandoned carts
- Trusting client prices: Always recalculate prices server-side during checkout
- Synchronous saga coordination: Multi-SKU reservations should fail fast and compensate, not block waiting for distributed agreement
Complexity: Storage O(products × warehouses), read latency O(1) with caching, write latency O(1) per shard with conditional updates providing linearizable inventory semantics.