CS Fundamentals Trainer · Guides
Design a ticket booking system: seats, holds and contention
A case study in correctness under contention: modelling events, seats and orders, why double-selling is the central risk, temporary holds with expiry, database locking and constraints that make a double sale impossible, handling the flash-crowd moment with a waiting room, payments that fail, and what can be cached safely.
5 min read
The problem. A popular concert goes on sale. A million people arrive within a minute for 50,000 seats. Each seat may be sold at most once, a user who is paying should not lose the seat halfway, and the site must survive the stampede. This looks like a CRUD application until you account for contention: many users competing for the same few rows at the same moment.
Requirements and numbers
Browse events, see seat availability, select seats, pay, receive tickets, and cancel. Non-functional: never sell the same seat twice, fairness, and availability under a sudden peak. Normal traffic is low; the peak is the design point. 1,000,000 users in 60 seconds is about 17,000 requests per second to the seat map, but only 50,000 purchases can ever succeed, and actual payments occur at a few hundred per second at most. So read traffic is high and cacheable; the write path is small and must be exactly right.
Data model
events(id, name, starts_at, venue_id)
seats(event_id, seat_id, section, price_cents, status, hold_expires_at, order_id)
-- status: available | held | sold
orders(id, user_id, event_id, state, expires_at, total_cents)
payments(id, order_id, idempotency_key, state, ...)
A seat is a row, and its status is the single source of truth for "is it free".
The core risk: double selling
Two users click the same seat at the same millisecond. A naive flow reads status = 'available', then writes sold; both see "available" before either writes. The fix must make the check and the write one atomic step, in the database, because application-level checks race.
Options:
- Conditional update (optimistic): ``
sql UPDATE seats SET status = 'held', order_id = $1, hold_expires_at = now() + interval '10 minutes' WHERE event_id = $2 AND seat_id = $3 AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));`` If the statement affects one row, you got the seat; if zero rows, someone else did. The database serialises concurrent updates to the same row, so only one wins, with no explicit locks held by the application. - Pessimistic lock:
SELECT … FOR UPDATEon the seat rows inside a transaction. It is simple and correct; it queues contenders and holds locks while the transaction lasts, so keep the transaction short and lock rows in a consistent order (to avoid deadlocks when users pick several seats). - A unique constraint as a last line of defence: for example a
tickets(event_id, seat_id)table with a unique key, so that a bug in the logic cannot insert two tickets for the same seat. Constraints beat careful code.
Choose the conditional update plus the constraint: no long locks, cheap, and the database is the arbiter.
Holds with expiry
Users need time to pay. When they select seats the system places a hold: the seats become held with an expiry (typically 5 to 10 minutes), the order is pending, and the user sees a countdown. Then:
- On successful payment the order becomes
paidand seatssold, in one transaction. - On timeout or cancellation the seats return to
available. Do not rely only on a timer that might die: the conditional update above already treats aheldseat with a past expiry as free, and a sweeper job cleans up in the background (and fires events such as "seats released" for waiting users). Expiry in the data, not in memory, survives restarts.
Payment interaction
The order of operations matters: hold first, then take payment, then confirm. Use idempotency keys with the payment provider (see the payment-system case study). If payment succeeds after the hold expired and the seat was given to someone else, you have to refund automatically and apologise; extend the hold while a payment is in progress to make that rare, and handle it explicitly in the state machine.
Surviving the flash crowd
- Waiting room / virtual queue. Put users in a queue before they reach the booking pages and let them in at a rate the backend can handle (for example 1,000 a minute), by random draw or order of arrival, so the system never sees the full spike. This is also fairer, and is how real ticketing sites survive big releases.
- Cache the seat map. The picture of what is available can be a few seconds stale; serve it from a cache or CDN and refresh every second or two, or push updates over a WebSocket or server-sent events. The truth is checked at hold time, so stale reads only cost an occasional "sorry, just taken" message.
- Rate-limit and bot-protect: per-IP and per-account limits, CAPTCHA or proof-of-work, one active session per user, and a cap on tickets per order. Bots are a large part of the load.
- Isolate the hot event. Give a major event its own database partition or even cluster, so it cannot take other events down; shard by event id.
- Scale reads horizontally with replicas, and keep writes for one event on one primary, because the contention is on those rows anyway.
Choosing seats
"Best available" assignment (any 2 adjacent seats) is a search problem: keep an index of free seats by section and row, find a contiguous block, then try to hold exactly those seats with the conditional update; if one was lost in between, search again. General admission (no seat numbers) is simpler: a counter available_count decremented atomically with UPDATE … SET available = available - n WHERE available >= n.
Trade-offs
Pessimistic against optimistic concurrency, strong consistency for inventory with cached reads for browsing, hold length (long holds frustrate other buyers, short ones frustrate payers), and fairness against throughput in the waiting room.
Sources
- Alex Xu, System Design Interview Vol. 2, chapter "Hotel Reservation System" (same inventory-and-hold problem).
- PostgreSQL documentation: Explicit locking (row-level locks, SELECT FOR UPDATE).
- Martin Kleppmann, Designing Data-Intensive Applications, chapter 7 (Transactions) — write skew and phantoms.
Practise this topic: System Design System Design › Case studies