Case Study: Ticket Booking (Race Condition)

BookMyShow-style ticketing: seat locking, high-contention inventory, payment timeouts, and the flash-sale rush.

Advanced9 min read
Language
Theme

EP 04: Ramayana Ki Aakhri Ticket, 2 Log 1 Seat

Availableselect (SET NX)Held (Redis)TTL 5 minpayment OKBookedDB + tickettimeout / failPayment gateway webhook = source of truth, never the browser redirectRush control: waiting room queue + seat map in cache + idempotent payments
Key idea at a glance

The problem, stated properly

Design a ticket booking system (BookMyShow, Ticketmaster): users browse events and seat maps, select seats, pay, and receive a confirmed ticket. It looks like a simple CRUD app until you add the two facts that make it one of the hardest interview problems: inventory cannot oversell (one seat, one owner, ever), and demand is brutally spiky (a Coldplay on-sale does 10x normal traffic in 90 seconds, almost all of it hammering the same few thousand seats).

Scale first

  • Normal traffic: browsing dominates, maybe 50K QPS of event/seat-map reads against a few hundred bookings/sec. Read-heavy, cacheable.
  • On-sale traffic: a stadium concert releases ~50K seats to ~2 million simultaneous users. That is a 40:1 contention ratio on inventory, with everyone querying the same seat map at once. Reads spike to millions of QPS; writes must stay strictly serialized per seat.
  • The invariant: for N seats there must never be more than N confirmed tickets, under any combination of retries, double-clicks, payment timeouts, and server crashes.

The core mechanism: the seat-hold state machine

Seats move through states, and every transition is atomic:

  1. AVAILABLE: anyone can see it on the seat map.
  2. HELD (soft lock): a user selects it. The seat is held for a fixed window (typically 5-10 minutes) while they pay. If payment never completes, the hold expires and the seat returns to AVAILABLE automatically. Holds are usually stored in Redis: SET seat:12345 user:789 NX EX 600, one atomic command that both checks availability and writes the hold. The TTL is the expiry mechanism, so a crashed payment flow can never strand a seat forever.
  3. BOOKED (hard lock): payment succeeded. The hold converts into a permanent booking row in the database, written transactionally: only if the seat is currently held by this same user.

The money path must be idempotent end to end: payment webhooks retry, users double-click, networks drop. Every booking carries a client-generated idempotency key; a duplicate submission returns the original booking instead of charging twice.

Why optimistic concurrency wins here (and where it loses)

Two ways to stop double-booking:

  • Pessimistic locking (SELECT FOR UPDATE): lock the seat row during the whole purchase. Safe but deadly at on-sale scale: thousands of users queue on the same rows, lock wait times explode, and a user who abandons checkout holds a lock until timeout. Fine for low-contention inventory, wrong for hot seats.
  • Optimistic with Redis holds: the atomic SET NX does the mutual exclusion in memory, the DB only sees one final writer per seat, and contention evaporates. This is the standard production answer. The database still enforces the invariant last: a unique constraint on (event_id, seat_id) on the bookings table means even if every layer above it has a bug, the storage layer cannot oversell. Defense in depth is the point.

Surviving the on-sale: the waiting room

You cannot let 2 million browsers hammer your seat map. Real systems put a virtual waiting room in front: users join a queue at the edge (a CDN-level or gateway-level token dispenser), and the system admits users at the rate the booking backend can actually serve (say 2,000 sessions/sec). Everyone else sees "you are 14,203rd in line" with an ETA. This converts an unbounded thundering herd into a bounded, measurable flow. Fairness details matter: queue positions are assigned by lottery after an initial grace window (kills bot speed advantage), tokens are single-use, and admitted sessions are fingerprinted to slow scalpers.

Reads at on-sale scale

The seat map is the hottest read in the building and it changes constantly (every hold and booking grays out seats). Serving it from the DB is impossible. The standard shape: the seat map renders from a cached snapshot (CDN or Redis), refreshed every few seconds from the authoritative store, and the client re-validates the specific seats it wants at selection time. Users tolerate "these seats were just taken" at checkout; they do not tolerate a spinning seat map. Eventual consistency on the display, strong consistency on the write: that split is the whole design in one sentence.

Production failure modes

  • Orphaned holds: user closes the tab mid-payment. The Redis TTL recovers the seat, but if you implemented holds without TTLs (a common bug), inventory leaks permanently.
  • Payment succeeded, booking failed: charge went through, DB write crashed. You need a reconciliation job that matches payment records to bookings and auto-refunds or auto-completes. Money and inventory must reconcile to zero diff every night.
  • Race between hold-expiry and payment-complete: payment lands at second 601 of a 600-second hold. Policy decision: extend holds while a payment is in-flight, or reject and refund. Pick one explicitly; discovering your accidental choice in production is how you end up on Twitter.
  • Bots and scalpers: on-sales are adversarial. Rate limits per IP/account/device fingerprint, CAPTCHAs at admission, and resale restrictions are part of the system, not an afterthought.

Common interview traps

  • Letting the payment call happen inside a database transaction. Network calls inside transactions hold locks for hundreds of milliseconds and collapse throughput.
  • Designing holds without expiry. Every soft state needs a TTL or a janitor.
  • Forgetting idempotency on the booking endpoint. Retries are guaranteed; double charges are optional.
  • Claiming strong consistency for the seat map display. Millions of readers do not need, and cannot have, up-to-the-millisecond accuracy.

Interview Q&A

Q: Walk me through exactly what happens when two users click the same seat at the same instant.
A: Both requests hit Redis. The seat hold is one atomic command: SET seat:42 user:A NX EX 600. Redis executes commands sequentially, so exactly one of the two SETs returns OK; the other returns nil and that user instantly sees "seat just taken." The winner pays, and the booking write carries a unique (event, seat) constraint, so even a hypothetical Redis failure cannot produce two confirmed tickets. One atomic primitive in memory, one unique constraint on disk, and the invariant holds.

Q: How does the waiting room decide the admission rate?
A: Work backwards from booking capacity. If payment + booking completes in ~2 seconds end to end and you can run 1,000 concurrent purchase flows safely, admit ~500 new users per second (leaving headroom for retries). Monitor downstream latency and error rate and close the valve when they rise: the queue length is your buffer, the admission rate is your throttle. This is just a token bucket applied to humans.

Key takeaways

Interview pointer

Structure the answer around the seat's lifecycle: available -> held -> booked, with expiry bringing it back. Walk through the two failure cases (payment timeout, lock expiry mid-payment) and you have covered what interviewers actually dig into.