🛠️ TalentMe · System Design DISTRIBUTED ARCHITECTURE TEARDOWN

[System Design] Flash Sale Inventory: 500K QPS Burst, Zero-Oversell, & 15-Min Rollback

✍️ TalentMe Architecture Group
📅
⏱️ 6 min read
📊 1027 words
[System Design] Flash Sale Inventory: 500K QPS Burst, Zero-Oversell, & 15-Min Rollback
ARCH CHALLENGE
High-Concurrency Inventory Reservation
TARGET SCALE
500,000 QPS burst, P99 < 50ms, 99.999% availability, 0 overselling, 15-min TTL rollback
TARGET LEVEL
L5 / L6 (Senior / Staff)
CORE PILLARS
High Availability & Consistency

🧮 Back-of-the-Envelope Capacity Estimations

Traffic QPS
Read: 450K QPS (status checks); Write: 50K QPS (reservations). 90% of traffic is rejected at CDN/Edge or Redis layer.
Storage Growth
10M items * 1KB metadata = 10GB. 1B transactions * 500B = 500GB/year. Partitioned by item_id.
Memory / Cache (80/20)
Redis Cluster: 10M keys * 100B = 1GB. 80/20 rule: 20% hot items (2M keys) consume 80% of RAM. 16GB Redis instance sufficient.
Bandwidth In/Out
Ingress: 500K * 1KB = 500MB/s (4Gbps). Egress: 50K * 2KB = 100MB/s (0.8Gbps).

📐 High-Level Architecture Topology

flowchart TD
  A[Client] --> B[CDN/Edge WAF]
  B -->|Static/Rate Limit| C[403/429]
  B --> D[API Gateway]
  D --> E[Redis Cluster]
  E -->|Lua Atomic Dec| F{Stock > 0?}
  F -->|No| G[409 Conflict]
  F -->|Yes| H[Reserve ID]
  H --> I[Outbox Table]
  I --> J[MQ Kafka]
  J --> K[Order Service]
  K --> L[MySQL Optimistic Lock]
  L --> M[Payment Gateway]
    

🏛️ Architecture Deep Dive & Component Topology

Edge Gating & Rate Limiting

To survive 500K QPS, we must shed 90% of load before it hits the core. Implement a CDN-based static page for the ‘sale start’ state. Use a token bucket algorithm at the API Gateway (e.g., 10 req/sec per user) to smooth bursts. This reduces effective load to ~50K QPS for the reservation path.

Redis Atomic Pre-Decrement

Use a Redis Cluster with 16 shards. Each item ID maps to a specific shard via consistent hashing. The core logic is a Lua script executed atomically: local stock = redis.call('GET', key); if stock > 0 then redis.call('DECR', key); return 1 else return 0 end. This ensures zero overselling at the cache layer. The script returns a unique reservation ID (UUID) generated via Redis INCR on a separate counter key.

Transactional Outbox & Async Decoupling

Upon successful Redis decrement, the service writes a record to a MySQL outbox table in the same transaction as the user session update. A CDC (Change Data Capture) tool like Debezium tails the MySQL binlog and publishes events to Kafka. This guarantees exactly-once processing semantics for downstream order creation, decoupling the hot path from slow payment processing.

MySQL Optimistic Locking

The Order Service consumes Kafka events and attempts to persist the order. It uses optimistic locking: UPDATE inventory SET quantity = quantity - 1, version = version + 1 WHERE item_id = ? AND version = ?. If the update affects 0 rows, it retries with exponential backoff (max 3 times). If it fails, it triggers a compensation event to release the Redis reservation.

💾 Data Models (DDL/Schemas) & API Contracts

MySQL Schema

CREATE TABLE inventory (
  item_id BIGINT PRIMARY KEY,
  quantity INT NOT NULL,
  version INT NOT NULL DEFAULT 0,
  updated_at TIMESTAMP
);

CREATE TABLE outbox (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  event_type VARCHAR(50),
  payload JSON,
  created_at TIMESTAMP
);

Redis Keys

stock:{item_id} -> INT
res_counter:{item_id} -> INT

gRPC API

service InventoryService {
  rpc Reserve(ReserveRequest) returns (ReserveResponse);
  rpc Release(ReleaseRequest) returns (Empty);
}
message ReserveRequest {
  string item_id = 1;
  string user_id = 2;
  int32 quantity = 3;
}

🛡️ Extreme Failure Scenarios, Stampede Defense & Self-Healing

Split-Brain & Redis Failure

If a Redis shard fails, the cluster promotes a replica. During failover, there is a brief window where writes are rejected. Mitigation: Use Redis Sentinel or Cluster mode with automatic failover. If the primary is lost, the new primary may have stale data. To prevent overselling, the system must reconcile with MySQL. Implement a ‘reconciliation job’ that compares Redis stock with MySQL stock every 5 minutes and corrects discrepancies. If Redis is down for >30s, fail over to a ‘degraded mode’ where requests are rejected with 503 to protect data integrity.

Cache Stampede

When a hot item’s stock key expires or is deleted, 500K requests may hit MySQL simultaneously. Mitigation: Use a ‘mutex lock’ pattern in Redis. Only one request per item ID can proceed to MySQL to refresh the cache; others wait for a short timeout (100ms) and then retry. Alternatively, use a ‘soft TTL’ where the key is not deleted but marked as stale, allowing background refresh.

15-Minute Rollback

Unpaid reservations must be released after 15 minutes. Implement a delayed message queue (e.g., Kafka with timestamp-based partitioning or a dedicated timer service). When a reservation is created, publish a ‘release’ event with a 15-minute delay. The consumer checks if the order is paid; if not, it decrements the MySQL version and increments Redis stock. Use idempotency keys to prevent double-release.

Disaster Recovery

Multi-region active-passive setup. If the primary region fails, DNS fails over to the secondary. The secondary region must have a read-replica of MySQL and a synchronized Redis cluster. Use a global rate limiter to prevent the secondary from being overwhelmed during failover.

🎯 Interview Evaluation Rubric: L4/Senior vs L6/Staff Architect

L4 / Senior Engineer Baseline
Proposes Redis for caching and MySQL for storage. Mentions using a lock in Redis to prevent overselling. Suggests using a message queue for async processing. Does not address the atomicity of the decrement and check, nor the consistency between Redis and MySQL. May suggest a simple retry mechanism without backoff.

L6 / Staff Architect Differentiators
Identifies the need for atomic Lua scripts in Redis to ensure zero overselling. Proposes a transactional outbox pattern to ensure exactly-once processing and decouple the hot path. Addresses the 15-minute rollback with a delayed message queue and idempotency. Considers the impact of Redis failover on data consistency and proposes a reconciliation job. Optimizes for cost by using CDN gating to shed 90% of load. Discusses the trade-offs between optimistic and pessimistic locking in MySQL.

📺 YOUTUBE MASTERCLASS

🎬 Visual Teardown: Hotel Reservation: System Design Interview (Stripe & Amazon Offers)


Watch on YouTube ↗

💡 Key Study Takeaway:ByteByteGo high-frequency FAANG system design teardown of location-based services exploring GeoHash vs QuadTree.
🧭 Master FAANG System Design on TalentMe
Access 69+ production-grade algorithm breakdowns, distributed architecture simulations, and mock interviews.


🚀 Launch TalentMe Architecture Workbench →

SPONSORED PARTNER · 合作伙伴推荐
🛍️ Recommended Gear & Custom Amazon Search for This Topic🔥 4 Curated Picks + Custom Search
⚖️ AirSOTA is a participant in the Amazon Services LLC Associates Program. As an Amazon Associate, we earn from qualifying purchases at no extra cost to you.
探索更多优质技术与商业专栏
返回 💻 大厂系统设计与架构 (System Design Pulse) 专栏或浏览 AirSOTA 知识矩阵

⚡ WEEKLY SOTA DIGEST · DIRECT TO INBOX
📬 Get the AirSOTA Weekly SOTA Briefing (Zero Spam, Unsubscribe Anytime)

Join engineers, parents, and investors receiving our Friday synthesis of AI kernels, AAP baby recipes, and US real estate & S&P 500 deep dives.

🌐 AirSOTA Cross-Domain Ecosystem Synergy

Empowering North American tech talent & families with integrated decision-making across Visa, Career, Wealth, Housing & Education.


Discover more from AirSOTA – Air School Of Thoughts AtoZ

Subscribe to get the latest posts sent to your email.

🏠 首页 | ← TalentMe |