Design a Flash-Sale Resilient Inventory Engine
System DesignModel answerLast updated
Design a multi-warehouse e-commerce inventory system handling flash sales without overselling, focusing on high availability, concurrency control, and idempotency.
Design an enterprise-grade inventory engine for an e-commerce platform operating across multiple regional fulfillment centers.
Core Functional Requirements
- Stock Lifecycle: Support
Reserve(hold stock temporarily for checkout),Release(cancel hold or handle expiration), andPurchase(permanently decrement stock upon successful payment). - Catalog & Warehouse Breakdown: Allow clients to query aggregate stock availability for a SKU as well as stock breakdown per fulfillment center.
- Idempotency & Reliability: Guarantee at-least-once downstream event publishing (order created, inventory reserved) and ensure all state-mutating APIs support idempotent retries.
Key Technical Challenges & Constraints
- Absolute Invariant: Zero overselling. Under no circumstances may aggregate reservations exceed available physical stock.
- High Throughput & Spikes: System must handle flash sales driving 50,000 read requests per second and 5,000 write operations per second, often concentrated on a tiny fraction of hot SKUs.
- High Availability: Target 99.99% operational uptime across regional network degrades and partial service outages.
Expectations
Walk through the architectural design, detailing:
- System components, API interfaces, and relational schema.
- Concurrency strategies to avoid race conditions under extreme contention.
- Scaling paradigms (CQRS, read caching, sharding strategies, and hot-key counter techniques).
- Reliability patterns (saga orchestration, outbox pattern, rate-limiting, and disaster recovery).
Hints
Hint 1
Reads can tolerate slight event-driven staleness, but reserve writes require strict linearizability at the database row level. Avoid read-modify-write patterns in application code.
Hint 2
For hot SKUs receiving thousands of updates per second on a single row, consider counter-splitting or pre-filtering traffic with atomic Redis operations.
Hint 3
To safely bridge the database write and Kafka message delivery without two-phase commit overhead, implement the Transactional Outbox pattern with CDC.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Overview & Key Invariants
The primary mandate of an inventory service is correctness under extreme concurrency. While product catalog updates and availability reads can tolerate eventual consistency, inventory allocations (Reserve, Release, Purchase) require strict linearizability for specific SKU-warehouse combinations.
+------------------------+
| API Gateway / Ingress |
| (Rate Limiting, Auth) |
+-----------+------------+
|
v
+------------------------------+
| Inventory Command Service | (Stateless)
+--------------+---------------+
|
+---------------+---------------+
| |
v v
+--------------------+ +-------------------+
| Redis Admission | | Distributed DB |
| (Hot-SKU Gate) | | (Spanner / Vitess)|
+--------------------+ +---------+---------+
|
v
+-------------------+
| Outbox CDC Relay | (Debezium)
+---------+---------+
|
v
+-------------------+
| Kafka Event Bus |
+---------+---------+
|
v
+-------------------+
| Read Projection | (CQRS Redis View)
+-------------------+
Scale Requirements & Envelope Calculations
- Read Workload: 50,000 RPS.
- Write Workload: 5,000 RPS.
- Data Footprint: 10M SKUs across 200 warehouses ≈ 2 Billion potential stock records. At ~100 bytes per record, total active inventory data is ~200 GB.
- The Bottleneck: While 5,000 total write RPS across 200 GB of sharded data is trivial, 5,000 write RPS concentrated on a single hot SKU during a flash sale causes extreme database row lock contention.
2. API Specifications
POST /v1/reservations
Request:
{
"idempotency_key": "uuid-v4-string",
"order_id": "ord_88392",
"ttl_seconds": 900,
"items": [
{ "sku": "SKU-IPHONE15-BLK", "quantity": 1, "warehouse_id": "wh-east-1" }
]
}
Response (201 Created):
{
"reservation_id": "res_99201",
"status": "HELD",
"expires_at": "2024-10-24T12:15:00Z",
"allocations": [
{ "sku": "SKU-IPHONE15-BLK", "warehouse_id": "wh-east-1", "quantity": 1 }
]
}
POST /v1/reservations/{reservation_id}/purchase
Request:
{
"idempotency_key": "uuid-v4-string",
"payment_reference": "pay_tx_90123"
}
Response (200 OK):
{ "status": "PURCHASED" }
POST /v1/reservations/{reservation_id}/release
Request:
{
"idempotency_key": "uuid-v4-string"
}
Response (200 OK):
{ "status": "RELEASED" }
GET /v1/availability/{sku}
Response (200 OK):
{
"sku": "SKU-IPHONE15-BLK",
"total_available": 1420,
"as_of": "2024-10-24T12:00:01.002Z"
}
3. Data Schema & Core Storage Model
To maintain consistency and transactional integrity, use a sharded relational database (e.g., CockroachDB, Spanner, or Vitess on PostgreSQL). The schema is partitioned by sku.
-- Represents physical stock at a warehouse.
CREATE TABLE inventory_item (
sku VARCHAR(64) NOT NULL,
warehouse_id VARCHAR(32) NOT NULL,
on_hand INT NOT NULL CHECK (on_hand >= 0),
reserved INT NOT NULL CHECK (reserved >= 0 AND reserved <= on_hand),
version BIGINT NOT NULL DEFAULT 1,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (sku, warehouse_id)
);
-- Tracks active stock reservations tied to checkouts.
CREATE TABLE reservation (
reservation_id VARCHAR(64) PRIMARY KEY,
order_id VARCHAR(64) UNIQUE NOT NULL,
status VARCHAR(16) NOT NULL CHECK (status IN ('HELD', 'PURCHASED', 'RELEASED', 'EXPIRED')),
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE reservation_item (
reservation_id VARCHAR(64) REFERENCES reservation(reservation_id),
sku VARCHAR(64) NOT NULL,
warehouse_id VARCHAR(32) NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
PRIMARY KEY (reservation_id, sku, warehouse_id)
);
-- Idempotency store guaranteeing safe operational retries.
CREATE TABLE idempotency_record (
client_id VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(64) NOT NULL,
request_hash VARCHAR(64) NOT NULL,
response_body JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (client_id, idempotency_key)
);
-- Transactional Outbox for CDC dispatch.
CREATE TABLE outbox_event (
event_id VARCHAR(64) PRIMARY KEY,
aggregate_type VARCHAR(32) NOT NULL,
aggregate_id VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
4. Concurrency Control & Race Condition Prevention
1. Atomic Conditional Updates (Hot Path)
Never execute a SELECT ... followed by an UPDATE ... in application code. This introduces classic check-then-act race conditions. Instead, execute conditional atomic updates directly in SQL:
-- Atomic Reservation Execution
UPDATE inventory_item
SET reserved = reserved + :qty,
version = version + 1,
updated_at = NOW()
WHERE sku = :sku
AND warehouse_id = :warehouse_id
AND (on_hand - reserved) >= :qty;
If affected_rows == 0, the transaction aborts due to insufficient available stock.
2. State Machine Transition Safeguards
To resolve races between an expiring background job and a late-arriving user purchase attempt, bind status changes to explicit state conditions:
-- Finalizing Purchase
UPDATE reservation
SET status = 'PURCHASED'
WHERE reservation_id = :res_id
AND status = 'HELD'
AND expires_at > NOW();
If the status update returns 0 affected rows, the reservation either expired or was already processed. The application returns an appropriate conflict response (e.g., 409 Conflict), triggering a compensation step if needed.
3. Distributed Transactions & Multi-SKU Orders
When an order includes multiple SKUs across different storage shards, avoid expensive Two-Phase Commit (2PC) protocols across database nodes. Instead:
- Lock/reserve SKUs in deterministic order (e.g., lexicographical sorting by SKU ID) to prevent database deadlocks.
- Use a Saga Orchestrator: attempt line-item reservations sequentially or in parallel. If any item fails, issue compensating
Releaseoperations for previously reserved items.
5. Flash Sale Strategies (Handling Extreme Hot Keys)
When 5,000 write requests per second hit a single SKU's database row, row-level locking becomes the primary bottleneck. Two main techniques mitigate this issue:
[ Incoming Reserve Requests ]
|
v
+--------------------+
| Redis Token Gate | ---> (Reject immediately if token pool empty)
+---------+----------+
|
v (Admitted Traffic)
+--------------------+
| Sub-Bucket Router | ---> Picks bucket (e.g., Bucket 3 of SKU-A)
+---------+----------+
|
v
+--------------------+
| Database Execution | ---> Runs Atomic SQL Update on Bucket 3
+--------------------+
Strategy A: Virtual Counter Splitting (Database Tier)
Divide physical stock for high-demand SKUs into $N$ virtual sub-buckets inside inventory_item:
- Instead of one row with 10,000 units, store 10 rows with 1,000 units each (e.g.,
SKU-A#1,SKU-A#2, ...SKU-A#10). - incoming reservations randomly select a bucket index $i \in [1, N]$.
- If bucket $i$ is exhausted, fallback to sequential probing ($i+1 \pmod N$).
- This reduces single-row lock contention by a factor of $N$.
Strategy B: Redis In-Memory Admission Control (Filter Layer)
Place a high-speed Redis admission gate in front of the database:
- On sale initialization, load stock counts into Redis atomic counters (
DECRBY). - Execute stock holds via atomic Lua script:
local current = redis.call('get', KEYS[1]) if current and tonumber(current) >= tonumber(ARGV[1]) then return redis.call('decrby', KEYS[1], ARGV[1]) else return -1 end - If Redis returns
-1, reject the request immediately at the ingress edge. - If Redis succeeds, pass the transaction through to the database layer.
- Note: The relational database remains the ultimate source of truth. Redis acts purely as a fast rejection filter to protect downstream database resources from load spikes.
6. Microservice Architecture & Eventual Consistency (CQRS)
[Write Side] [Event Bus] [Read Side]
Command API ---> DB Writes ---> Debezium CDC ---> Kafka Topic ---> CQRS Consumer ---> Redis Read Cache
- Transactional Outbox Pattern:
State changes and event generation occur within the same local database transaction. An outbox worker or Change Data Capture (CDC) engine (e.g., Debezium) streams changes from
outbox_eventdirectly to Kafka. - CQRS Projection Layer:
A dedicated Read Projection service consumes Kafka events and maintains an updated view in Redis for read operations (
GET /v1/availability/{sku}). - Read Cache Eviction & Invalidation:
- Key Structure:
cache:avail:{sku}(Stores aggregate JSON object),cache:wh:{sku}:{warehouse_id}(Hash of warehouse breakdown). - Cache TTL: Short default TTL (e.g., 5 seconds) to handle unexpected drift.
- Proactive Updates: CDC consumers execute atomic update scripts on cache keys upon receiving
InventoryReservedorInventoryRestockedevents.
- Key Structure:
7. Edge Cases, Failure Modes & Reliability
| Failure Scenario | Mitigation Strategy |
|---|---|
| Client Retries / Network Drops | Clients must pass an idempotency_key. The service executes the request and writes the result to idempotency_record in the same SQL transaction. Duplicate requests immediately return the cached payload. |
| Orchestrator Crashes mid-Checkout | Expired reservations are cleaned up by a distributed background task scanning expires_at < NOW() AND status = 'HELD'. Expired holds automatically return stock via compensating updates. |
| Outbox Relay Lag | Availability reads may temporarily display stale data. However, the command path relies strictly on transactional DB state, preventing overselling even under high read lag. |
| Hot SKU Database Deadlock | Sort target SKUs deterministically before executing multi-item reservation queries. |
8. Summary Architecture Check
- Absolute Invariant: Safe atomic database updates (
WHERE on_hand - reserved >= qty) eliminate overselling bugs. - Flash Sale Scale: Combined Redis admission gates and counter splitting protect database nodes from single-row bottlenecking.
- High Throughput Reads: CQRS projection decouples 50,000 RPS availability queries from core write operations.
- Reliability: Idempotency tracking and Transactional Outbox event publishing guarantee at-least-once downstream updates and safe client retries.