Limited-Stock Flash Sale Platform with Zero Oversell
System DesignModel answerLast updated
Design a platform that sells a fixed number of seats or units to millions of simultaneous buyers, with no oversell, no double charge, and graceful behavior under failure.
Problem
You are designing the backend for a limited-stock sale, such as tickets for a very popular concert. Stock is fixed, for example tens of thousands of seats. When sales open, the platform may receive millions of purchase attempts per second, yet only a small fraction of buyers can succeed. The system must never sell more than exists and never charge anyone twice.
The venue has two kinds of inventory:
- General admission (GA): buyers pick a quantity, not a specific seat.
- Reserved seating: buyers pick specific seats, and a request must succeed or fail as a whole.
What to cover
- Admission control and fairness. How do you keep the stampede away from the core services? Choose a fairness model (arrival order, lottery, or a mix) and justify it. Explain how rate limiting and backpressure tie the admission rate to backend capacity.
- Preventing oversell. Explain how you guarantee zero oversell in both inventory modes. Compare holding stock temporarily with deducting it immediately, and describe expiring holds and how stock is returned after a timeout or cancellation.
- Bots and abuse. Describe your defenses and how you enforce per-person purchase limits (for example, a few tickets per account, device, or card).
- Idempotency. Make reservation and order creation safe to retry, including duplicate payment-provider callbacks.
- Hot-spot avoidance. Show how you avoid one global counter becoming the bottleneck.
- APIs. Sketch the main endpoints, idempotency headers, and error codes.
- Data model and partitioning. Name the entities and the shard or partition keys, for both the durable store and the fast in-memory allocation path.
- Read and write paths. Describe caching, how clients see live availability, and the flow from queue to hold to paid order.
- Messaging. Explain how an asynchronous bus is used, which delivery guarantees you rely on, and how consumers stay correct.
- Consistency and reconciliation. State where you need strong consistency and where eventual is acceptable, and how the fast allocator and the durable ledger are kept in agreement.
- Failure handling. Cover timeouts, retries, circuit breakers, degraded modes, and what happens when the cache, the database, or the payment provider fails.
- Capacity, SLOs, and testing. Give concrete numbers and a test plan that demonstrates zero oversell under extreme load.
- Monitoring. List the key metrics and alert thresholds.
Treat this as a generic limited-inventory design problem. State your assumptions about scale up front.
Hints
Hint 1
Start by sizing: millions of requests per second but only tens of thousands of possible sales. Most traffic should be absorbed at the edge, so the real question is how to let in only as many people as the allocator can handle.
Hint 2
Correctness should live in one place: a single atomic operation per shard (for example a Redis Lua script) that checks stock, checks the buyer's quota, and records a hold with an expiry. Everything else (queues, caches, UI) can be eventually consistent.
Hint 3
Split the stock across many sub-keys so no single key is hot, and make every step retry-safe by deriving hold IDs from the idempotency key and deduplicating payment callbacks by provider event ID.
Hint 4
Treat Redis as a fast allocator and the database as the ledger of record, then plan the unhappy paths: expired holds, late payments (refund), crashed allocator (rebuild from ledger), and a periodic reconciler that compares both.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Assumptions: 50k seats per event (a mix of GA and reserved), a cap of 4 tickets per buyer, 10M people waiting, and a peak near 2M requests/s at opening, mostly queue joins and status polls. Only about 50k orders can succeed, so more than 99% of traffic must be answered cheaply at the edge.
Targets:
- Zero oversell and zero double charge (hard guarantees).
- Availability display may be 1-2 s stale.
- Reserve p99 under 200 ms; queue status p99 under 50 ms from the edge; hold TTL of 10 minutes.
2. Architecture
Client -> CDN/WAF/bot filter -> Waiting room (edge)
-> API gateway (admission-token check, rate limit)
-> Reservation service -> Redis cluster (allocator)
-> Order service -> SQL ledger + outbox -> Kafka
-> Payment service <-> PSP webhooks
Reaper, reconciler, availability fan-out (SSE)
Principle: admission rate is set by backend capacity, not by demand.
3. Admission control and fairness
- Hybrid fairness. Users who join in a pre-sale window (say T-15 min to T0) get a random position (a lottery). Later arrivals are appended in order. Pure FIFO rewards bots, fast networks, and refresh spam; the lottery removes the incentive to stampede at T0.
- Queue state is a signed token holding the position. A global "now serving" pointer is cached on the CDN for 1-2 s; clients poll with jitter or use SSE.
- Token bucket advances the pointer at the rate the allocator can sustain (for example 5k reservations/s). An AIMD controller lowers the rate when Redis p99 or errors breach limits and raises it slowly when healthy. That is the backpressure loop.
- Admitted users receive a single-use admission token (event, user, device, 2-5 min expiry) verified statelessly at the gateway. A per-user sliding-window limit (about 5 attempts/min) stops admitted users from hammering.
4. Anti-bot and quotas
Layered: WAF and IP reputation, device fingerprinting, behavioral signals (input entropy, cadence), invisible CAPTCHA escalating to hard CAPTCHA or proof-of-work for suspicious sessions, and verified accounts (phone) before joining.
Bind the admission token to a hash of user, device, and session so it cannot be resold. Enforce the 4-ticket cap per account, device, and card: increment the quota counter inside the same Lua script that allocates, and re-check the card fingerprint with a DB unique constraint at order time.
5. No oversell
Use reserve-then-pay. Payment takes seconds to minutes, so only a hold gives the buyer a real guarantee.
- GA: a Lua script on one shard checks
stock >= qtyand quota, thenDECRBY, writes the hold hash, and adds it to an expiry ZSET. Single-shard atomicity makes negative stock impossible. - Reserved seats: each section has a bitmap plus a
seat -> holdIdhash. The script verifies all requested bits are 0 and sets them together, so holds are all-or-nothing. - Release: a reaper reads the expiry ZSET and runs a release script that restores the counter or clears bits only if the hold is still
HELD(compare-and-set against a racing payment). Cancellation uses the same script. Payment success movesHELD -> SOLDatomically. A payment arriving for an already-released hold is refunded automatically.
6. Hot-key sharding
One counter tops out around 100k ops/s. Split stock into, say, 32 sub-keys using hash tags (stock:{event:07}) so each sub-key and its holds share a slot and the script stays single-shard. Route requests to a random sub-key and retry up to 2 others on shard-level sold-out. A rebalancer moves leftovers from cold to drained shards; declare "sold out" only when all are zero. Alternatives: pre-generated token lists per shard (LPOP), and sharding reserved seats by section.
7. APIs
All mutating calls carry Idempotency-Key.
| Endpoint | Purpose |
|---|---|
POST /events/{id}/queue | Join queue |
GET /queue/{ticket} | Position, ETA, admission token |
POST /events/{id}/reservations | Create hold |
DELETE /reservations/{holdId} | Cancel |
POST /orders | Create order and payment intent |
POST /payments/webhook | Signed PSP callback |
GET /events/{id}/availability | Cached counts or seat map |
GET /orders/{id} | Order status |
Errors: 409 SOLD_OUT, 409 SEAT_TAKEN, 410 HOLD_EXPIRED, 429 RATE_LIMITED (with Retry-After), 403 QUOTA_EXCEEDED / INVALID_ADMISSION, 409 IDEMPOTENCY_CONFLICT, 503 BROWNOUT.
8. Idempotency
- Table
idempotency(user_id, key, request_hash, status, response, ttl 24h)with a unique(user_id, key). First request insertsIN_PROGRESS; retries return the stored response or 409 while in progress; a different body under the same key is a conflict. - Hold ID =
hash(user, idemKey), so a re-run of the Lua script finds the existing hold. - Use the order ID as the PSP idempotency key; dedupe webhooks in an inbox table keyed by PSP event ID.
9. Data model and partitioning
events(small, replicated).seats/skus(event_id, seat_id, section, price, status)partitioned by(event_id, section).reservations(hold_id, event_id, user_id, items, state, expires_at)partitioned byevent_id.orders,paymentspartitioned byuser_idororder_id, with a secondary index onevent_id.- Redis keys hash-tagged by
event:shard.
10. Read/write paths and messaging
- Reads: availability comes from a cache fed by events from the allocator, pushed over SSE or polled with a 1-2 s TTL. Never read the allocator for display.
- Writes: queue -> admission token -> Redis hold -> order row plus outbox row in one DB transaction -> Kafka -> payment -> webhook ->
SOLD. - Delivery: at-least-once with idempotent consumers (inbox table), transactional outbox for publishing, retry topics with backoff, and DLQs with alerts.
11. Consistency and reconciliation
Strong consistency only for allocation (atomic script on one shard). Availability reads are eventual. Redis is the allocator during the sale; the DB is the ledger of record. A reconciler periodically compares sold + held + free per event across both and flags drift. If Redis is lost, rebuild from the ledger (paid orders and unexpired holds) before reopening, failing closed in the meantime.
12. Failure handling
- Timeouts with exponential backoff and jitter; circuit breakers around the PSP and DB.
- Brownout: shut off non-essential features (recommendations, rich seat maps) and shrink the admission rate.
- Redis shard failover: replicas can lose recent writes, so on failover reconcile from the ledger and keep that shard closed until verified.
- PSP outage: keep holds alive with extended TTL, queue payment attempts, show "pending".
- Reaper crash: it is stateless and re-runs from the ZSET.
13. Capacity, testing, monitoring
- Edge absorbs 2M req/s; gateway and allocator see about 5-10k/s. With 32 shards that is under 1k ops/s per shard, leaving big headroom. Redis memory is tiny (50k holds). The DB sees about 50k orders over minutes.
- Tests: load test at 2-3x expected peak with simulated bots; property test that
sold <= capacityunder random kills of Redis, the reaper, and Kafka consumers; chaos injection of duplicate and reordered webhooks; replay tests of the reconciler. - Metrics and alerts: oversell count (page at >0), queue backlog and admission rate, hold expiry rate, p99 per endpoint (alert above SLO for 2 min), DLQ depth (>0 sustained), payment success rate (drop >5%), reconciler drift (>0), Redis CPU (>70%).
Common mistakes
- Deducting stock only at payment time, which makes holds unreliable.
- A single global counter.
- Check-then-set in application code instead of an atomic script.
- Trusting cached availability for allocation.
- Ignoring late payments after hold expiry.
- No idempotency on webhooks.