Design: ticket booking

In one sentence

Hold seats with one atomic conditional write that expires after ~10 minutes, charge with an idempotency key, then confirm only if the hold is still yours; a virtual waiting room meters the spike.

The waiting room meters arrivals; one conditional write decides each seat, and the sale confirms only while the hold is live.

How it works

  • Scope (assumed): a 50k-seat on-sale with 2M fans in the first hour; never sell a seat twice.
  • Hold seats with one conditional UPDATE; zero rows affected means another buyer got there first.
  • Holds carry an expiry (~10 min): expired holds count as available, so no timers are needed.
  • Pay with an idempotency key, then flip HELD to SOLD only if the hold is still yours.
  • A virtual waiting room admits buyers at a fixed rate, so the database sees steady load, not the spike.

Check yourself

Answer to mark it learned; your answers aren't scored.

Load tests sell 0.3% of seats twice. The booking code runs SELECT status FROM seats WHERE …, and if it reads AVAILABLE, runs UPDATE seats SET status='HELD' …. What's the right fix?

Go deeper

Do this round in 45 minutes System design round
Full explanation

Requirements

Functional: browse events and seat maps, hold seats while the buyer pays, confirm and issue tickets. Non-functional: never sell a seat twice; holds expire so abandoned carts free their seats; survive on-sales where demand dwarfs inventory (assume a 50k-seat stadium and 2M fans in the first hour). Seat maps may lag by seconds; writes to a seat must be strongly consistent.

API and data model

  • POST /events/{id}/holds {seat_ids} → hold_id, expires_at
  • POST /holds/{id}/purchase {payment, idempotency_key}
  • seats(event_id, seat_id, status, hold_id, hold_expires_at, order_id), partitioned by event_id

Architecture

A CDN and a seat-map cache absorb browsing. A virtual waiting room in front of checkout admits buyers at a fixed rate with a signed token. The booking service writes holds to a relational DB. Payment carries an Idempotency key; once it is authorized, the seats flip from HELD to SOLD.

The hard parts

Contention. Two buyers click the same seat. Never read-then-write in app code: run one conditional write, UPDATE … SET status='HELD' WHERE status='AVAILABLE' OR (status='HELD' AND hold_expires_at < now()), and check rows affected. The loser gets 0 rows and picks another seat. That is the optimistic style: detect the conflict at write time. Pessimistic SELECT … FOR UPDATE locks rows first; held across a buyer's checkout, it queues everyone behind hot seats.

Expiry. Holds expire lazily: the predicate treats an expired hold as free, so there is no timer per hold, and a sweeper only tidies the seat map. The purchase confirms only if the hold is still yours; otherwise it voids the payment.

Code Hold and confirm seats with conditional writes
sqlHold and confirm seats with conditional writes
-- Hold: one atomic conditional write. No read-then-write gap for a rival to slip into.
BEGIN;
UPDATE seats
SET    status = 'HELD', hold_id = :hold_id,
       hold_expires_at = now() + interval '10 minutes'
WHERE  event_id = :event_id
  AND  seat_id = ANY(:seat_ids)
  AND  (status = 'AVAILABLE'
        OR (status = 'HELD' AND hold_expires_at < now()));  -- expired hold = free
-- App: rows affected < len(seat_ids) -> ROLLBACK (all or nothing), show "seat taken".
COMMIT;

-- Confirm, after the payment is AUTHORIZED: only if the hold is still ours and live.
BEGIN;
UPDATE seats
SET    status = 'SOLD', order_id = :order_id
WHERE  event_id = :event_id
  AND  hold_id = :hold_id
  AND  status = 'HELD'
  AND  hold_expires_at > now();
-- rows affected < seat count -> ROLLBACK, void the authorization, apologize.
COMMIT;

-- Pessimistic alternative: lock first, decide later. Fail fast instead of queueing.
SELECT seat_id, status FROM seats
WHERE  event_id = :event_id AND seat_id = ANY(:seat_ids)
ORDER  BY seat_id            -- same lock order for everyone: no deadlocks
FOR UPDATE NOWAIT;
Real example

A 50k-seat stadium opens sales at 10:00 with ~2M fans queued (assumed). The waiting room admits 2k users/min, in random order among everyone who arrived before 10:00. Maya gets in at 10:07 and picks F12–F13: her hold UPDATE affects 2 rows, expiring at 10:17. A rival's UPDATE on F12 a millisecond later affects 0 rows, and he sees nearby seats instead. Maya's card is authorized at 10:12; the confirm UPDATE matches her hold_id and the seats become SOLD. By ~10:40 the inventory is gone, and the room tells the ~1.9M still waiting.

Trade-offs +3 · −3

+ You gain

  • A seat can never sell twice: correctness rests on one conditional write, not on app-level checks.
  • Write load stays tiny (~21 orders/s); the waiting room turns the spike into a steady stream.
  • Expiring holds recycle abandoned carts with no timer per hold.

− You pay

  • Fans queue for tickets that may sell out before their turn.
  • One event's partition is a hot spot; general-admission counters need bucketing.
  • Hold TTL is a compromise: too short fails slow payers, too long hoards seats.

Use it when

Any fixed inventory sold under contention: concert and sports seats, flights, hotel rooms, limited product drops, appointment slots.

Avoid it when

Plentiful or restockable inventory (digital goods, everyday e-commerce): skip holds and waiting rooms; a stock decrement, with a rare oversell refunded, is cheaper.

Numbers to know 5
  • Demand (assumed): 2M fans for 50k seats = 40 fans per seat; at ~4 seats per order, ~99% leave without tickets.
  • Orders: 50k seats ÷ ~4 per order ≈ 12.5k orders; selling out in 10 min is only ~21 orders/s.
  • Waiting room (assumed 2k admits/min): the last of 2M fans would wait ~1,000 min (~17 h), so announce sold-out early.
  • Ticketmaster, Eras Tour presale (Nov 2022): 3.5B system requests, 4× its previous peak; 2M+ tickets sold that day.
  • Cloudflare Waiting Room has two main knobs: total active users and new users per minute (checked Nov 2026).
Common pitfalls 4
  • Read-then-write in app code (SELECT the status, then UPDATE): two buyers both see AVAILABLE and both win.
  • An expiry predicate like OR hold_expires_at < now() without status='HELD': sold seats with an old expiry get resold.
  • Confirming SOLD without checking the hold is still yours: an expired, re-held seat is sold twice.
  • Serving seat-map reads from the primary DB: browsing traffic, not purchases, takes it down.
Interview questions 3

Answer out loud first, then reveal.

Two users click the same seat in the same millisecond. What happens?Show answer

Both run the same conditional UPDATE: set HELD where the seat is available or its hold expired. The database serializes them on the row: the first commits and affects 1 row; the second re-checks the predicate, affects 0 rows and gets "seat taken" plus nearby alternatives. No app-level lock, no read-then-write gap. I'd avoid SELECT FOR UPDATE held across the buyer's checkout: it queues everyone behind hot seats.

How would you sell 20k general-admission tickets with no seat numbers?Show answer

Without seat rows, one remaining counter becomes the hot row every buyer updates. I'd split inventory into buckets, say 20 of 1k, and send each buyer to a random non-empty bucket, decrementing with WHERE remaining >= n. Holds still expire and return to their bucket. An alternative is pre-minting 20k tokens into a queue and popping one per buyer. Either way the waiting room keeps the arrival rate sane.

Why a waiting room? Why not just autoscale the booking service?Show answer

Because the bottleneck is inventory, not servers. With 2M fans for 50k seats, ~99% leave empty-handed whatever I scale; more capacity just sends more concurrent writes at the same hot rows. The waiting room admits buyers at the rate checkout can serve, randomizes early arrivals so bots don't win on speed, and announces sold-out early. I'd still autoscale the stateless edge that serves the queue page.

Deep dive 3

Optimistic vs pessimistic locking

Pessimistic: SELECT … FOR UPDATE locks the rows, then you decide and write. Safe, but locks held across a network round trip queue buyers, and multi-seat transactions that lock in different orders deadlock; lock in seat order and add NOWAIT to fail fast. Optimistic: read freely, then write only if nothing changed (a version column or a status predicate) and check rows affected. Under contention optimistic usually means retries, but a lost seat is never retried: the buyer picks another, so it fits booking well. General admission has no seat rows: one remaining counter becomes a hot row. Split it into buckets (say 20 × 1k) and decrement a random non-empty one WHERE remaining >= n.

Holds, expiry and the payment race

A hold is a row state with a deadline, not a lock: HELD plus hold_expires_at. ~10 minutes (assumed) is long enough to pay and short enough to recycle abandoned carts during the on-sale. The race: the payment succeeds just after the hold expired and someone else grabbed the seat. So authorize the card first, then confirm with UPDATE … SET status='SOLD' WHERE hold_id = :mine AND hold_expires_at > now(); 0 rows means void the authorization and apologize. Extending the hold by a minute or two when payment starts makes this rare. Retries of the purchase reuse the same idempotency key, so a double click never charges twice.

The virtual waiting room

The bottleneck is fixed inventory, not servers: with 2M fans for 50k seats, most leave empty-handed however much you scale. The waiting room sits at the edge (your CDN or a product such as Cloudflare Waiting Room), gives each visitor a signed, expiring token with a queue position, and admits new users at the rate checkout can serve. Randomizing everyone who arrived before the open means the fastest bot doesn't win. Pair it with presale codes, and show sold-out the moment inventory is gone. Ticketmaster's Eras Tour presale (Nov 2022) saw 3.5B system requests, 4× its previous peak, which it attributed to bots and fans without codes.