Design Flash Sale & Inventory Reservation
High-concurrency inventory reservation engine handling extreme traffic spikes (iPhone drops, Black Friday) with atomic stock decrements, zero oversell guarantees, and asynchronous order settlement.
1. System Requirements
- Allow hundreds of thousands of users to view product availability and reserve flash sale inventory in real time.
- Atomically decrement inventory stock with a strict zero-oversell guarantee under extreme concurrent race conditions.
- Hold temporary stock reservations (10-minute cart hold) and automatically roll back inventory if payment fails or expires.
- High throughput write path absorbing 200,000+ reservation requests/sec with P99 latency under 40ms.
- Strict data consistency: absolute zero inventory overselling (never sell N+1 items for stock of N).
- High availability with graceful degradation during sudden 50x flash sale traffic surges.
2. Scale & Resource Estimates
Throughput: 50,000 flash units sold out in under 20 seconds. Peak traffic: 250,000 reservation requests/sec.
Storage & RAM: Inventory catalog fits in memory: ~10 MB Redis hash footprint. Order reservation log: 50,000 orders * 1 KB = 50 MB per event.
3. System API Endpoints
POST /api/v1/flash-sale/reserve
Request: { item_id: "itm-ps5-pro", user_id: "usr-9921", quantity: 1, idempotency_key: "idem-773a-99b" }
Response: { reservation_id: "resv-8812", expires_at: 1783709400, status: "reserved" }
POST /api/v1/flash-sale/checkout
Request: { reservation_id: "resv-8812", payment_token: "tok-stripe-881a" }
Response: { order_id: "ord-44012", status: "confirmed" }
4. Database Schema Design
Table: inventory_items (PostgreSQL Source of Truth)
- item_id (VARCHAR - Primary Key)
- total_stock (INTEGER)
- allocated_stock (INTEGER)
- version (BIGINT - Optimistic Locking)
Table: inventory_reservations (PostgreSQL)
- reservation_id (UUID - Primary Key)
- item_id (VARCHAR)
- user_id (UUID)
- quantity (INTEGER)
- status (ENUM: PENDING, CONFIRMED, EXPIRED)
- expires_at (TIMESTAMP)
Redis Memory Key-Value Store:
- Hash: flash_stock:{item_id} -> { available: 50000, reserved: 0 }
- Set: user_reserved:{item_id} -> { usr-9921, usr-4412 }
5. Interactive High-Level Architecture
6. Scalability Deep Dive & Bottlenecks
Direct relational database writes (`UPDATE items SET stock = stock - 1 WHERE id = ... AND stock > 0`) crumble under 100K+ RPS due to row-level lock contention and connection pool exhaustion. The solution isolates the write path into an in-memory Redis Cluster executing atomic Lua scripts. The Lua script verifies the user hasn't already bought the item, checks if `stock > 0`, decrements the counter, and sets a temporary reservation key with a 10-minute TTL in a single atomic transaction. Once reserved in Redis, an event is placed into Kafka for asynchronous database persistence and payment processing (Saga pattern).
7. Production Scaling Strategies
Stock Sub-Bucketing: To avoid a single Redis node hot spot on viral flash sales, partition inventory into N virtual buckets (e.g., `stock:ps5:bucket_1` to `stock:ps5:bucket_10`). Requests randomly hash across buckets, distributing load evenly across 10 Redis nodes.
Atomic Lua Script Execution: All validation, rate limit checking, and decrement operations occur inside a single atomic Lua script on Redis, guaranteeing zero race conditions without distributed locks.
Asynchronous Order Queuing: Decouple synchronous reservations from slow database writes and payment gateway calls via Kafka. Workers process order creations in batch inserts of 500 records.
TTL Cart Reclaim Worker: Redis keys for reservations expire after 10 minutes. A background worker listens to Redis keyspace notifications or sweeps a sorted set of expiration timestamps to restore unpurchased stock.
Idempotency Enforcement: Enforce strict idempotency via unique client tokens (`idempotency_key`) stored in Redis with a 24-hour TTL, preventing duplicate charges if users hit the submit button repeatedly.
Static CDN Content Shielding: Serve product detail pages and initial stock countdown banners purely from edge CDNs. Only checkout reservation POST requests bypass the CDN and hit origin servers.
8. Runnable Production Starter Code
Scaffold