Designing a Flash-Sale Ticketing Platform That Never Double-Sells
System DesignModel answerLast updated
Design a ticketing platform that survives a sudden surge when sales open, holds seats during checkout, and guarantees no ticket is ever sold to two buyers.
You are building the backend for selling tickets to very popular events. Sales open at a publicly announced time, and the number of people trying to buy greatly exceeds the number of tickets. A buyer picks tickets, keeps them reserved for a short period while paying, and receives them once payment succeeds.
Your design should address two main difficulties:
- The sudden burst of traffic the instant sales open.
- Inventory and concurrency control, so that one ticket can never end up with two owners, including how a cache and a database cooperate under heavy contention.
The numbers are not given. Ask about them or state your own assumptions (event size, number of concurrent buyers, peak request rate, hold duration, per-user ticket limit, seated vs. general admission, fairness expectations, bot concerns).
Reserved tickets that are not paid for within the time limit must be released back to sale.
Part 1: Core flow and data model
Describe the main components, the APIs, and the data model. Walk through one purchase from viewing the event page to holding a confirmed ticket. Cover:
- Entities for events, inventory, holds, orders, and payments
- APIs for checking availability, placing a hold, paying, and confirming
- The lifecycle of a ticket from available to held to sold or released
- Idempotency of hold and payment calls under retries and double clicks
Part 2: The traffic spike at sale open
Explain how you prevent a flood of simultaneous requests from overwhelming services and the database. Consider CDNs and caching, load balancing and pre-scaling, a waiting room or queue, and rate limiting and bot defense.
Part 3: Inventory and concurrency control
Explain how you guarantee no ticket is sold twice. Cover how inventory is decremented, how holds work during payment, how they are released on timeout, and how cache and database stay consistent. Address hot rows and the race between a late payment and an expired hold.
Hints
Hint 1
Separate the read path (event pages, availability display) from the write path (holds and purchases). The read path can be cached heavily and be slightly stale; the write path must be strictly correct.
Hint 2
Treat the database as the single source of truth for the no-oversell invariant, using a conditional atomic update. Use caches or counters only to reject obviously hopeless requests early, never as the final authority.
Hint 3
Model a hold as a row with an expiry time and a state machine. Think about what happens when the payment callback arrives after the expiry, and make every step idempotent with a client-supplied key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- A large event: 50,000 tickets, about 1 million users arriving in the first minute, with peaks of roughly 100k requests per second at the front door.
- Hold duration of 5 to 10 minutes, with a limit of 4 tickets per user.
- Both seated and general-admission inventory are supported. I will design for seats and note that GA is simply a counter.
- A short waiting room is acceptable if it makes the sale fairer.
Part 1: Core flow and data model
Services: an edge layer (CDN, WAF), an API gateway, an Event/Catalog service, a Queue/Admission service, a Booking service (holds and orders), a Payment service integrating with an external provider, and a background Expiry worker.
Data model (relational, sharded by event):
events(id, name, on_sale_at, ...)tickets(event_id, ticket_id, section, price, status, hold_id, version), where status isAVAILABLE,HELD, orSOLDholds(hold_id, user_id, event_id, status, expires_at, idempotency_key)with statusACTIVE,CONFIRMED,EXPIRED,CANCELLEDorders(order_id, hold_id, user_id, amount, status)payments(payment_id, order_id, provider_ref, status), unique onprovider_ref
APIs:
GET /events/{id}/availabilityis cached and approximate.POST /holdswith{ticket_ids, Idempotency-Key}returns a hold and its expiry.POST /holds/{id}/paycreates a payment intent and returns a client token.POST /payments/webhookis called by the provider. It is idempotent onprovider_ref.GET /orders/{id}shows the result.
Lifecycle: AVAILABLE, then HELD (hold created), then SOLD (payment confirmed before expiry). If the hold expires or is cancelled, the ticket returns to AVAILABLE.
Idempotency: the client sends an idempotency key with each hold and payment call. A unique index on (user_id, idempotency_key) makes a retry or double click return the original hold instead of creating a second one.
Part 2: Surviving the spike
- Offload reads. Event pages, images, and seat maps are served from a CDN. Availability is served from a cache or a push channel with a few seconds of staleness. This removes most of the traffic from the core.
- Pre-scale. The spike is predictable, so scale stateless services and warm connection pools and caches ahead of time. Autoscaling reacts too slowly for a spike that lasts seconds.
- Waiting room. Before the on-sale time, users join a queue and receive a position, ideally randomized among everyone who arrived before the opening to avoid rewarding the fastest connection. The admission service issues signed, short-lived tokens at a rate the booking path can sustain (for example, a few thousand per second, tuned from load tests). Only token holders can call
POST /holds. The queue state lives in Redis or a similar store, and the user watches progress via polling or WebSocket. - Rate limiting. Apply limits per user, per IP, and globally at the gateway (token bucket). Reject excess requests quickly with a 429 and a retry hint. Bot defense includes CAPTCHA or challenge before queue entry, device and account reputation, and per-account ticket limits.
- Degrade gracefully. If the booking path is saturated, the waiting room slows admission instead of letting requests fail. Sold-out events return a cheap cached response.
Part 3: Inventory and concurrency control
Atomic reserve on the source of truth. A hold is created in one transaction using a conditional update:
UPDATE tickets
SET status = 'HELD', hold_id = :h
WHERE event_id = :e AND ticket_id IN (:ids) AND status = 'AVAILABLE';
-- succeed only if affected rows == number of requested tickets, else roll back
The database enforces the invariant, so two concurrent requests cannot both win a row. This is optimistic concurrency, and it is better than pessimistic SELECT ... FOR UPDATE here because losers fail fast instead of piling up on locks. For multi-seat requests, always touch ids in sorted order to avoid deadlocks.
Hold expiry. Each hold has expires_at. Two mechanisms work together:
- Lazy: any reserve treats a ticket as available if its hold is
ACTIVEbut pastexpires_at, or the reserve first expires it. - Active: a worker (or a delay queue / Redis sorted set) sweeps expired holds and sets tickets back to AVAILABLE and the hold to EXPIRED, each with a conditional update on current status.
Late payment vs. expired hold. Confirmation runs in a transaction: UPDATE holds SET status='CONFIRMED' WHERE hold_id=:h AND status='ACTIVE' AND expires_at > now(), followed by marking the tickets SOLD. If the payment webhook arrives after the hold expired and the tickets were resold, the confirmation fails and the system automatically refunds or voids the authorization. To reduce this, authorize the payment only after confirming the hold is live, and extend the hold slightly while a payment is in flight (a "payment pending" state with a bounded grace period).
Cache and counters. For GA tiers, a Redis counter with an atomic Lua script (if stock >= n then stock -= n) rejects most requests when sold out, without touching the database. Rules:
- The cache is a gate and never the authority. A request that passes the cache still has to win the database update.
- If the cache decrements but the database reserve fails, increment the counter back. Periodic reconciliation recomputes counters from the database.
- On cache loss, rebuild from the database before reopening admission, or fall back to the database alone at reduced throughput.
- Seat maps are updated through events published after commit (outbox pattern), so caches converge within seconds.
Hot rows. For GA, one counter row becomes a hotspot. Split inventory into N buckets (for example, 50 sub-counters each holding a slice) and have each request pick a bucket, falling through to others if one is empty. Alternatively, route all requests for an event to a single partition or actor that serializes them in memory with a write-ahead log. Throughput of one partition can reach tens of thousands of operations per second, which is enough when the waiting room controls arrival.
Failure handling.
- Booking service crashes mid-purchase: the hold has an expiry, so state self-heals.
- Payment provider outage: holds stay valid until expiry; show errors, and the waiting room slows admission.
- Duplicate webhooks: handled by the unique
provider_refand idempotent state transitions.
Trade-offs
- A waiting room costs some user experience but protects correctness and gives fairness.
- Optimistic updates favor throughput; pessimistic locks are simpler but create queues on hot rows.
- Short holds recycle inventory faster but increase abandoned-payment frustration.
Common mistakes
- Relying on a cache counter alone to prevent overselling.
- Check-then-update in application code without an atomic conditional write.
- No handling of the payment-after-expiry race.
- Non-idempotent hold or payment endpoints.
- Scaling reactively instead of pre-scaling and queueing.
- Skipping bot protection and per-user limits.