System Design HLD-19.16
Design a ticket booking system (BookMyShow)
Design ticket booking: seat holds with expiry, preventing double booking with locks or version checks, and a virtual waiting room for flash sales.
The problem
A cinema seat or a concert ticket is a unique thing. Two people can read the same news post, but only one person can sit in seat G12 at the 7 pm show. A booking system must let thousands of people browse, pick seats and pay, and guarantee that each seat is sold at most once, even when hundreds of them click the same seat in the same second.
Most days the load is gentle. Then a famous band announces a tour and two million fans arrive at 10:00:00 for 50,000 seats. The system faces two problems at once: correctness under contention on a small set of rows, and a traffic spike far larger than the inventory can ever satisfy. The first is solved in the database; the second, mostly in front of it.
Requirements
Functional
- Browse events, shows and a seat map with live availability.
- Select seats and hold them for a few minutes while paying.
- Confirm the booking after payment; release seats if payment fails or time runs out.
- Cancel and refund under the event's rules.
Non-functional
- Correctness: a seat is never sold twice; a paid customer always has a seat.
- Scale: normal days are modest; on-sale events bring millions of users in minutes.
- Fairness: during flash sales, people who arrived earlier get their turn earlier; bots are throttled.
- Availability of browsing even when booking is saturated.
Out of scope
- Dynamic pricing, resale marketplaces, and the payment system internals ( Design a payment system ).
Estimates
- Flash sale demand: 2 million fans arriving within the first minute is about 33,000 new users a second, each loading pages and polling seat maps.
- Supply: 50,000 seats at about 2.5 tickets per order is 20,000 orders. If the booking path can complete 1,000 orders a minute, the sale takes about 20 minutes, and at most 20,000 of the 2 million fans can ever succeed. Admitting everyone at once would only produce errors.
- Hot rows: all those orders compete for 50,000 seat rows in one event, with the best sections attracting far more attempts than the rest.
- Holds: a hold lasts about 10 minutes. With 1,000 orders a minute, about 10,000 orders are in their hold window at any time.
API
GET /v1/shows/{show_id}/seats -> { seats: [{ id, section, price, status }] }
POST /v1/shows/{show_id}/holds { seat_ids, idempotency_key }
-> 201 { hold_id, expires_at } or 409 { unavailable: [...] }
POST /v1/holds/{hold_id}/confirm { payment_token } -> { booking_id }
DELETE /v1/holds/{hold_id}
GET /v1/queue/{event_id}/status -> { position, estimated_wait, admitted }
A hold is all-or-nothing: if any requested seat is taken, the whole request fails and the client shows fresh availability.
Data model
- Seats (relational, partitioned by show):
show_id, seat_id, status (available, held, booked), hold_id, hold_expires_at, booking_id, version. One row per seat per show is the single source of truth for inventory. - Holds:
hold_id, user_id, show_id, seat_ids, expires_at, status. - Bookings:
booking_id, user_id, show_id, seat_ids, payment_id, status. - Waiting room (fast in-memory store):
event_id -> ordered queue of visitor tokens, plus the admission rate.
High-level design
- Queue path At on-sale time, fans land on a waiting room page served from the CDN. Each gets a queue position; the queue admits a fixed number per minute with a signed, short-lived token that the booking service requires.
- Hold path An admitted user picks seats. The booking service runs one conditional update that changes all of them from available to held with a 10-minute expiry. If any seat was already taken, nothing changes and the user picks again.
- Confirm path The user pays. On success the held seats become booked, again only if the hold is still theirs and unexpired. A sweeper releases expired holds so abandoned seats return to sale.
Deep dives
Deep dive 1: Preventing double booking
The classic bug is check-then-act: read the seat, see it is available, then write that it is yours. Between the read and the write another request does the same, and both succeed. The sample races 200 fans for 30 seats, with other requests running between each fan's read and write:
# 200 fans race for 30 seats. Each request reads a seat, then writes it a
# moment later; other requests run in between. Compare a plain
# read-then-write with a conditional write that checks the version it read.
import random
def sale(conditional, seed=5):
rnd = random.Random(seed)
seats = {s: {"owner": None, "version": 0} for s in range(30)}
# each fan wants one seat; low numbers (front rows) are most popular
wants = [min(int(rnd.expovariate(1 / 8)), 29) for _ in range(200)]
steps = [(f, op) for f in range(200) for op in ("read", "write")]
rnd.shuffle(steps)
seen = {}
confirmed, conflicts = [], 0
for fan, op in steps:
seat = seats[wants[fan]]
if op == "read":
seen[fan] = (seat["owner"], seat["version"])
continue
if fan not in seen: # write came first: read now
seen[fan] = (seat["owner"], seat["version"])
owner, version = seen[fan]
if owner is not None:
continue # looked taken: the fan picks again
if conditional and seat["version"] != version:
conflicts += 1 # someone wrote since we read
continue
seat["owner"], seat["version"] = fan, seat["version"] + 1
confirmed.append((fan, wants[fan]))
sold = len({s for _, s in confirmed})
return len(confirmed), sold, conflicts
for conditional in (False, True):
told, sold, conflicts = sale(conditional)
name = "conditional write" if conditional else "read then write"
print(f"{name:17}: {told:2} fans told 'you got it' for {sold} seats")
print(f" {told - sold} double-sold, {conflicts} conflicts rejected")Output
read then write : 37 fans told 'you got it' for 29 seats
8 double-sold, 0 conflicts rejected
conditional write: 29 fans told 'you got it' for 29 seats
0 double-sold, 8 conflicts rejected With a plain read-then-write, 37 fans were told they got a seat, but only 29 distinct seats were sold: 8 fans were promised seats that someone else was also promised, and each later write silently replaced the earlier owner. With a conditional write that checks the version it read, every overlap was caught as a conflict, and exactly one fan got each seat. The losers saw "seat no longer available" and picked again, which is the right experience.
Three ways to get that guarantee, all inside the database ( Transactions and ACID ):
- Pessimistic locking:
SELECT ... FOR UPDATEon the seat rows, then update, then commit. Simple and correct; concurrent requests for the same seats wait in line. Lock seats in a consistent order (by seat id) to avoid deadlocks. - Optimistic concurrency:
UPDATE seats SET status = 'held', version = version + 1 WHERE seat_id IN (...) AND status = 'available'and check that the number of updated rows equals the number of seats requested; if not, roll back. No waiting; the loser retries with fresh data. This works well when most requests target different seats. - Atomic operations in a fast store: for extreme contention (general admission tickets with no seat numbers), keep a counter in an in-memory store and decrement it atomically, then write the booking durably.
A distributed lock outside the database ( Distributed locks and fencing tokens ) is unnecessary here: the seat row in the database is the single source of truth, and the database's own concurrency control is the strongest guarantee you can get.
Deep dive 2: Holds with expiry
Payment takes minutes, and people abandon checkout. Booking seats only after payment would let two people pay for the same seat; booking before payment would lock seats forever when people walk away. A hold is the middle ground: a reservation with a deadline.
- The hold sets
status = 'held', hold_expires_at = now + 10 minutes. - Confirm succeeds only
WHERE hold_id = :id AND hold_expires_at > now, so a late payment cannot claim a seat that was released and resold. If that happens, the payment is refunded automatically. - Expired holds are released two ways: lazily (a hold attempt treats
heldwith a past expiry as available) and by a sweeper job that resets them so the seat map is accurate.
Short holds increase throughput during a sale; long holds are kinder to slow payers. Many sites show a visible countdown so users know the deal.
Deep dive 3: The virtual waiting room
When 2 million people want 20,000 orders, the job is not to serve everyone quickly; it is to fail most of them gracefully and fairly and serve the rest well. A waiting room does this:
- Before on-sale, traffic goes to a static waiting page served from the CDN, which can absorb almost any load.
- At on-sale, each visitor gets a random or arrival-ordered position. A queue service admits a fixed number per minute ( Rate limiting algorithms ), matching what the booking path can complete.
- Admitted users get a signed, short-lived token. The booking service rejects requests without one, so bots cannot skip the queue by calling the API directly.
- When inventory runs out, the queue tells everyone still waiting at once, instead of letting them discover it one error at a time.
The admission rate is a dial: too low and seats sit unsold while people wait; too high and the hold path becomes a hot spot of conflicts and timeouts. It is the queueing lesson ( Why async? Queues explained ) applied to people.
Try it
Think of messages as fans and workers as the booking path's capacity.
Try this:
- Choose the spike. How long is the wait for someone who arrives at the peak, with the current number of workers?
- Double the workers. The wait shrinks, but in the booking system what is the cost of admitting fans faster than the inventory database can handle?
- Our sale has 20,000 orders for 2 million fans. At what point should the waiting room stop admitting and tell everyone the sale is over?
Bottlenecks and failure modes
| Failure | Impact | Mitigation |
|---|---|---|
| Check-then-act race | Seat sold twice | Row locks or conditional updates on the seat rows |
| Stampede at on-sale | Database overload, errors for everyone | CDN waiting room, admission at a fixed rate |
| Bots | Real fans lose out | Signed queue tokens, rate limits per account and device |
| Abandoned checkouts | Seats locked and unsold | Holds with expiry; lazy release plus sweeper |
| Payment after hold expired | Paid but no seat | Confirm checks expiry; automatic refund |
| Hot sections | Many conflicts on the best seats | Best-available assignment by the server instead of everyone clicking the same seat |
Trade-offs we made
| Option | Wins when | Loses when |
|---|---|---|
| Optimistic conditional updates (chosen) | No waiting; conflicts are rare for distinct seats | Retries under heavy contention on the same seats |
| Pessimistic row locks | Simple reasoning; no retries | Requests queue behind locks on hot seats |
| Holds with a 10-minute expiry (chosen) | Users can pay without losing seats | Seats unavailable while held, even if abandoned |
| Virtual waiting room (chosen) | Protects inventory; fair and calm user experience | Users wait; extra infrastructure that only matters on big days |
Extensions
- Best available: the server assigns the best free seats in a section, which spreads contention.
- Partial holds: hold 3 of 4 requested seats and offer alternatives.
- Multiple shows and venues with seat maps cached at the edge.
- Anti-scalping: identity checks, per-person limits, and non-transferable tickets.
In the wild
Where you will see this: cinema, concert and sports ticketing, airline and train seat selection, hotel room inventory and restaurant table booking. The shared pattern is a small, contended inventory with a single source of truth, short holds while the customer pays, and a queue in front when demand vastly exceeds supply.
Check yourself
-
Why does read-then-write sell some seats twice?
Show answer
B. Two requests can both read 'available' before either writes Check-then-act leaves a gap between the check and the act; the database must do both atomically.
-
An UPDATE ... WHERE status = 'available' changes 3 rows when 4 seats were requested. What should happen?
Show answer
B. Roll back the transaction and tell the user one seat is gone Holds are all-or-nothing; a partial update means a conflict.
-
Why do holds expire?
Show answer
B. So abandoned checkouts return seats to sale Without expiry, every abandoned checkout would lock seats forever.
-
What is the main job of a virtual waiting room?
Show answer
B. To admit users at the rate the booking path can handle, fairly, while the CDN absorbs the rest Demand far exceeds supply; the room turns a stampede into a steady, fair stream.
Recap
- Each seat row is the single source of truth; every transition is one atomic, conditional write.
- Check-then-act double-sells; use row locks or optimistic version checks inside the database.
- Holds with an expiry let users pay safely; confirm only if the hold is still valid.
- A virtual waiting room at the edge admits users at the rate the booking path can serve.
- Signed queue tokens and rate limits keep bots from skipping the line.
Next up
- Crack the system design round learning path