Design a Flash Sale System with Virtual Waiting Room
System DesignModel answerLast updated
Architect a high-concurrency item drop system using edge-cached waiting queues, zero-oversell inventory reservation, and idempotent payment processing.
Scenario
A high-demand ticketing and merchandise platform frequently releases limited-edition inventory—such as opening-day theme park passes, exclusive concert packages, and drop-style physical collectibles. Millions of shoppers hit the purchase page within seconds of an event going live.
You are tasked with designing an end-to-end flash-sale system capable of absorbing massive initial traffic spikes, metering shopper access through a virtual waiting queue, maintaining strict zero-oversell inventory holds, and providing idempotent checkout processing.
Requirements
Functional Requirements
- Virtual Waiting Room: When incoming traffic exceeds backend capacity, divert shoppers into a waiting queue displaying their current position and estimated wait time.
- Controlled Admission: Admit queued shoppers into the checkout flow at a rate matched to backend database processing limits using cryptographically signed access tokens.
- Exact Inventory Reservation: Grant admitted users a temporary hold on an item (e.g., 10 minutes). Overselling must be impossible.
- Hold Expiration & Rollback: Automatically return reserved items to the available inventory pool if a user abandons their session or fails to complete payment before the hold window expires.
- Idempotent Checkout: Ensure network retries, browser refreshes, or repeated payment webhooks never result in duplicate charges or duplicate order fulfillment.
Non-Functional Requirements
- Strict Inventory Consistency: Zero tolerance for overselling under any node failure, network partition, or concurrent execution state.
- High Ingress Availability: The edge queue and position check endpoints must remain fully available (99.99%) during extreme traffic spikes.
- Fault Tolerance: Worker crashes or payment provider timeouts must never leak item holds or leave orders stuck in an indeterminate state.
- Abuse Mitigation: Protect against queue manipulation, token forgery, replay attacks, and script-based bot hoarding.
System Scale & Constraints
- Peak Ingress Load: 2,000,000 concurrent users waiting at drop time.
- Total Catalog Inventory: 25,000 units per flash-sale event.
- Admission Throughput: 500 to 1,000 users per second admitted to the reservation stage.
- Hold Duration (TTL): 10 minutes.
- Latency Targets: Under 200 ms for status checks and reservation attempts.
Key Discussion Areas
- High-Level System Architecture: Responsibilities of the CDN/Edge layer, queue service, gatekeeper API, inventory management service, payment flow, and background workers.
- Virtual Queue & Access Control: Monotonic counter sequence vs. sorted sets for queue management, cryptographically signed access tokens (JWTs), and API gateway validation.
- Inventory Management & Locking: Concurrency control strategies (pre-materialized inventory rows, database locks using
SKIP LOCKED, Redis fast-path pre-filters), and deterministic hold expiration. - Idempotent Payment & Order Completion: End-to-end checkout protocol with idempotency keys, handling asynchronous PSP webhooks, and ensuring transactional durability via the Transactional Outbox pattern.
Hints
Hint 1
Isolate high-volume read traffic (queue polling) from transactional write traffic by using edge caching for global queue progress counters.
Hint 2
Pre-create individual inventory rows in a relational database and select them with SELECT ... FOR UPDATE SKIP LOCKED to prevent row-lock contention across concurrent connections.
Hint 3
Treat Redis as an optimistic pre-filter to reject requests fast when stock is zero, but use relational database primary keys and unique indexes as the single source of truth for exact accounting.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Scale Flash Sale & Virtual Queue Architecture
1. Capacity Estimation & Traffic Isolation
A core requirement of flash-sale design is decoupling high-volume ingress polling from transactional write operations:
2M Waiters ──► [ CDN Edge Cache ] ── (Cached Status JSON: ~1 RPS to origin)
│
Admitted Users (500–1,000/s)
│
▼
[ Transactional DB Core ] ── (Capped at <= 1,000 TPS)
Ingress Polling Load
- Concurrent Waiters: 2,000,000 active sessions.
- Polling Interval: If clients request position updates every 5 seconds: $$\text{RPS} = \frac{2,000,000}{5} = 400,000 \text{ requests/sec}$$
- Strategy: Serving 400,000 requests/sec directly from application servers or databases will cause outage. This path must be served strictly at the CDN edge via edge caching and static payloads.
Admission Strategy & Database Load
- Total Units: 25,000 available.
- Target Admission Rate: 500 to 1,000 admissions/sec.
- Overbooking Factor: Assuming a $30\text{–}50%$ cart abandonment rate, admitting $1.5\times \text{inventory}$ ($\sim 37,500$ users total over time) ensures all inventory is sold without exhausting the queue prematurely.
- Database Write Target: At 1,000 admissions/sec, write throughput maxes out at $\le 1,000 \text{ TPS}$, a load easily handled by a single primary PostgreSQL instance.
2. System Architecture
[ Incoming Traffic Spike ]
│
▼
┌───────────────────────────────┐
│ Edge / CDN Layer & WAF │
│ (Bot check, status caching) │
└───────────────┬───────────────┘
│
▼
┌───────────────────────────────┐
│ Waiting Room Service │
│ (Assigns global sequence IDs) │
└───────────────┬───────────────┘
│
(Admission Token)
│
▼
┌───────────────────────────────┐
│ API Gateway / Access Control │
│ (Token & replay validation) │
└───────────────┬───────────────┘
│
┌──────────────────┴──────────────────┐
▼ ▼
┌──────────────────────────┐ ┌──────────────────────────┐
│ Inventory Service │ ────────►│ PostgreSQL (Primary DB) │
│ (Redis Lua + SQL Locks) │ │ (SKIP LOCKED rows) │
└────────────┬─────────────┘ └────────────┬─────────────┘
│ │
▼ ▼
┌──────────────────────────┐ ┌──────────────────────────┐
│ Checkout Service │ ────────►│ External Payment Gateway │
└──────────────────────────┘ └──────────────────────────┘
The system operates across two isolated layers:
- The Ingress & Queue Layer: Horizontally scalable, edge-cached, operating at 400K+ RPS using lightweight counter increments and static edge responses.
- The Transactional Core: Isolated and rate-capped at $\le 1,000 \text{ TPS}$ for relational database guarantees.
3. APIs
Public Endpoints
POST /api/v1/queue/join
Header: Authorization: Bearer <session_token>
Payload: { "event_id": "evt_9981" }
Response: 200 OK { "queue_ticket": "jwt_token_string", "user_sequence": 142050 }
GET /api/v1/queue/status?event_id=evt_9981
Response: 200 OK (Cache-Control: public, max-age=1)
{
"event_id": "evt_9981",
"current_serving_seq": 135000,
"admission_rate_per_sec": 750,
"status": "ACTIVE"
}
POST /api/v1/reservations
Header: Authorization: Bearer <admission_jwt>
Payload: { "sku_id": "SKU-VIP-PASS", "idempotency_key": "uuid_v4" }
Response: 201 Created { "reservation_id": "res_8831", "expires_at": "2026-03-30T10:15:00Z" }
POST /api/v1/checkout
Header: Authorization: Bearer <user_token>
Payload: { "reservation_id": "res_8831", "idempotency_key": "res_8831" }
Response: 200 OK { "order_id": "ord_5512", "payment_client_secret": "psp_secret_xxx" }
4. Virtual Queue & Admission Implementation
Counter Sequence vs. Sorted Set (ZSET)
Using a Redis Sorted Set (ZSET) where $2,000,000$ members execute ZRANK on every poll incurs $O(\log N)$ CPU overhead per request, failing under 400,000 RPS.
Instead, we use a Monotonic Global Counter:
-
Queue Registration:
INCR event:evt_9981:global_sequenceA per-user key check (
SETNX event:evt_9981:user:<user_id> <seq>) prevents a user from claiming multiple sequence numbers. The service returns a signed token containing{ user_id, user_sequence, event_id }. -
Edge-Cached Position Evaluation: Clients poll
/queue/status. The CDN caches the response for 1 second.- Origin hits: Reduced from 400,000 RPS to $\sim 1\text{ RPS per CDN POP}$.
- Client derives position locally: $$\text{Position} = \text{user_sequence} - \text{current_serving_seq}$$ $$\text{Wait Time (seconds)} = \frac{\text{Position}}{\text{admission_rate_per_sec}}$$
-
Issuing Admission Tokens: When $\text{user_sequence} \le \text{current_serving_seq}$, the client exchanges its ticket for a cryptographically signed Admission JWT:
{ "sub": "usr_4401", "event_id": "evt_9981", "jti": "unique_token_uuid", "exp": 1774868100 } -
Token Validation at Gateway: The API gateway validates the HMAC/RSA signature statelessly. Replay attacks are blocked by issuing a fast Redis check on the token identifier (
SETNX replay:jti:<uuid> EX 900).
5. Zero-Oversell Inventory Management
To guarantee zero overselling despite node crashes or concurrency, relational database state is the single source of truth.
Schema Design (PostgreSQL)
CREATE TYPE item_status AS ENUM ('AVAILABLE', 'HELD', 'PAYING', 'SOLD');
CREATE TABLE inventory_units (
unit_id BIGSERIAL PRIMARY KEY,
sku_id VARCHAR(64) NOT NULL,
status item_status NOT NULL DEFAULT 'AVAILABLE',
reservation_id UUID NULL,
version INT NOT NULL DEFAULT 0
);
CREATE TABLE reservations (
reservation_id UUID PRIMARY KEY,
user_id BIGINT NOT NULL,
sku_id VARCHAR(64) NOT NULL,
unit_id BIGINT UNIQUE REFERENCES inventory_units(unit_id),
expires_at TIMESTAMPTZ NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'HELD',
CONSTRAINT unique_active_user_hold UNIQUE (user_id, sku_id)
);
CREATE INDEX idx_inventory_alloc
ON inventory_units (sku_id, status)
WHERE status = 'AVAILABLE';
Pre-Materialization & Non-Blocking Reservation
Updating a central counter row (UPDATE products SET count = count - 1) creates severe lock contention. Instead, all 25,000 inventory items are pre-materialized as distinct database rows.
When an admitted user requests a reservation:
BEGIN;
-- Lock the next available inventory item without waiting on other concurrent transactions
SELECT unit_id
FROM inventory_units
WHERE sku_id = 'SKU-VIP-PASS' AND status = 'AVAILABLE'
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- Assign selected unit to the user's reservation
UPDATE inventory_units
SET status = 'HELD', reservation_id = 'c56a8f10-...'
WHERE unit_id = :selected_unit_id;
INSERT INTO reservations (reservation_id, user_id, sku_id, unit_id, expires_at)
VALUES ('c56a8f10-...', :user_id, 'SKU-VIP-PASS', :selected_unit_id, NOW() + INTERVAL '10 minutes');
-- Record outbox event for async processing
INSERT INTO outbox_events (aggregate_type, aggregate_id, event_type, payload)
VALUES ('RESERVATION', 'c56a8f10-...', 'RESERVATION_CREATED', '{"sku_id":"SKU-VIP-PASS"}');
COMMIT;
Significance of FOR UPDATE SKIP LOCKED
Without SKIP LOCKED, concurrent threads attempting to lock an available item block behind one another, leading to lock wait timeouts. SKIP LOCKED skips rows currently locked by other transactions, causing each worker to lock a distinct unit instantly.
Redis Fast-Path Pre-Filter
To shield PostgreSQL when stock is fully reserved, Redis stores an optimistic stock count:
-- Lua execution on reservation request
local stock = redis.call('GET', KEYS[1])
if not stock or tonumber(stock) <= 0 then
return 0
else
redis.call('DECR', KEYS[1])
return 1
end
If the script returns 0, the service rejects the request immediately. If it returns 1, the request proceeds to the SQL transaction. If SQL fails to find a unit (due to drift), the system handles it gracefully and increments the Redis counter back up.
6. Reservation Expiration & Hold Reclaim
Reservations expire after 10 minutes if unpaid. To return inventory to the pool deterministically:
Background Sweeper Worker
A distributed background worker runs every few seconds to clean expired holds:
BEGIN;
WITH expired_holds AS (
SELECT reservation_id, unit_id
FROM reservations
WHERE status = 'HELD' AND expires_at < NOW()
LIMIT 500
FOR UPDATE SKIP LOCKED
)
UPDATE inventory_units
SET status = 'AVAILABLE', reservation_id = NULL
WHERE unit_id IN (SELECT unit_id FROM expired_holds);
UPDATE reservations
SET status = 'EXPIRED'
WHERE reservation_id IN (SELECT reservation_id FROM expired_holds);
COMMIT;
Upon committing, an outbox worker reads the expired events and increments the Redis pre-filter counter (INCR event:SKU-VIP-PASS:redis_stock), allowing the admission controller to admit additional waiters.
7. Idempotent Checkout & Payment Integration
User Checkout Service Postgres Payment Provider (PSP)
│ │ │ │
├─ POST /checkout ──────►│ │ │
│ (res_id) ├─ Trans: HELD->PAYING ─►│ │
│ │ Insert Outbox Event │ │
│ │ │ │
│ ├─ Call Authorize ───────────────────────────────►│
│ │ (Idempotency-Key=order_id) │
│ │◄─ Authorize OK ─────────────────────────────────┤
│ │ │
│ ├─ Trans: PAYING->SOLD ─►│ │
│ │ Commit Order │ │
│◄─ 200 OK (Confirmed) ──┤ │ │
│ │ │ │
│ │◄── Async Webhook Event ─────────────────────────┤
│ │ (provider_event_id) │
│ ├─ Deduplicate & Capture │
1. State Transition & Grace Period
When the user clicks "Pay", the system executes a state transition:
- Update
reservationsandinventory_unitsstatus fromHELDtoPAYING. - Extend
expires_atby a 2-minute grace period to account for network latency with the Payment Service Provider (PSP).
2. Transactional Outbox Pattern
To guarantee consistency without two-phase commit (2PC) protocols across external APIs, outbox records are created in the same database transaction as business state changes:
CREATE TABLE outbox_events (
event_id BIGSERIAL PRIMARY KEY,
aggregate_type VARCHAR(64) NOT NULL,
aggregate_id VARCHAR(64) NOT NULL,
event_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed AT TIMESTAMPTZ NULL
);
An independent relay process (e.g., Debezium CDC or an outbox worker) reads outbox_events and dispatches messages to Kafka/RabbitMQ or PSP payment interfaces.
3. Payment Processing & Webhook Idempotency
- Authorization: The service passes
order_idas the payment provider’s idempotency key. Network retries return the original authorization state without double-charging. - Webhook Processing: Webhooks from the PSP are written to a
payment_eventstable using the provider's event ID as a primary key:
IfINSERT INTO payment_events (provider_event_id, payload, processed_at) VALUES ('evt_psp_109283', '...', NOW()) ON CONFLICT (provider_event_id) DO NOTHING;ON CONFLICTtriggers, the webhook was already processed, preventing duplicate processing.
8. Failure Modes & Edge Case Handling
| Failure Scenario | Mitigation & System Behavior |
|---|---|
| Worker Crashes Mid-Reservation | Transaction rolls back automatically via database session termination. No inventory is locked. |
| User Abandons Cart After Admission | The 10-minute TTL expires; the background sweeper reclaims the unit_id into AVAILABLE status and updates Redis stock counters. |
| PSP Webhook Is Lost or Delayed | A fallback reconciler queries the payment gateway periodically for pending PAYING orders. If authorized, it finalizes the order; if failed, it releases inventory. |
| Redis Crash or Invalidation | Redis is a non-authoritative fast filter. If Redis flushes, it is repopulated by running COUNT(*) WHERE status = 'AVAILABLE' on PostgreSQL. |
| Database Primary Failover | Pre-materialized inventory rows with primary keys and UNIQUE constraints enforce state integrity. Post-failover, duplicate writes fail constraints safely. |
Key Trade-Offs
- Relational Database vs. Redis-Only Inventory:
- Redis-Only: Extremely fast (100K+ TPS), but risks inventory leaks or overselling during un-synced failovers or AOF rewrite delays.
- Relational DB (Chosen): Bottlenecked at lower throughput ($\sim 1\text{--}5\text{K TPS}$), but guarantees $100%$ inventory exactness via transactional invariants and explicit row locks.
- Global Monotonic Counter vs. Sorted Set (ZSET) Queue:
- ZSET Queue: Supports explicit individual node deletion and dynamic re-ordering, but scales poorly ($O(\log N)$) under massive status polling read spikes.
- Monotonic Counter (Chosen): Scales to millions of waiters via static edge caching ($O(1)$), trading off individual queue position re-ordering capabilities.