Design a movie ticket booking system
hard 90 minSell the numbered seats of a cinema: choose, hold for ten minutes, pay, cancel.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
A movie ticket booking system in a low-level design round is the part that sells seats: it shows which seats of a show are free, holds some for a customer for a short time, takes the money, and gives out tickets.
Underneath it is a reservation with a deadline: a thing that exists once, a claim that ends by itself, and a payment that makes it final. Flights, hotel rooms, doctor's appointments and items in a flash sale have the same shape.
The answer is one object for each show, the seat map, with a lock and four methods. Around it stand records, a price rule, a bank behind an interface, and a front with three verbs.
Why it exists
The domain is known to everybody, and the difficulty is real: two people, one seat, a clock and a bank, all at the same moment.
It separates candidates who draw nouns from those who look for the rule. Theater, hall, movie and user fill a board and decide nothing.
It also introduces a distinction that large systems live from: reading may be old (the map on the screen), selling must be strict (the hold).
A short history
1933
The first drive-in theater under Hollingshead's patent opens in New Jersey on 6 June. A place in the field is the ticket.
1960
The first experimental system of SABRE, made by American Airlines with IBM for seat reservations, goes online. The full system follows in 1964.
1976
Ticketmaster is founded on 2 October in Phoenix, Arizona.
1989
Moviefone is founded in the United States: cinema times by telephone.
1994
The QR code is invented at Denso Wave in Japan, for car parts. Cinema doors came later.
2000
MovieTickets.com is founded: cinema tickets on the web.
Words to know
- Show
- A film in a room at a time.
- Seat of a show
- The pair that is sold. Also called show seat.
- Seat map
- Who has which seat of one show.
- Hold
- A claim with an end. Here: a pending booking.
- All or nothing
- Either every seat of the wish or none.
- Lazy expiry
- An old claim is ignored when somebody looks, and not removed by a timer.
- Paying
- The state between our promise and the bank's answer.
- Idempotency key
- A name for a charge. The same name twice is one charge.
- Settle
- Ask the bank what became of a charge without an answer.
- Optimistic locking
- Change only if the version is still the one that was read.
- Fencing token
- A growing number that lets the store refuse a holder whose time is over.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Seats are held. One to six seats of a show, all or none, until a time
Understand it
Start here
Cushions and clothes pegs
An open-air cinema has eight numbered cushions. Whoever wants some gets a clothes peg for each, clipped on at once. The pegs are old: after ten minutes they fall off by themselves. Nobody runs about with a list.
Hold, pay, or fall off. The rest of this page is about doing it when a thousand people point at the same cushion.
What an interviewer looks for here
Where is the state?
Not in the chair. In the pair of show and chair.
All or nothing
Three friends want three seats. Two seats are no answer.
Time
A hold ends although no code runs. And a payment can outlast it.
Money
Charged once, or not at all, whatever breaks.
The life of a booking
Words
Six nouns, and the one that matters
| Word | It is | Changes? | Example |
|---|---|---|---|
| Movie | A film | No | Nosferatu |
| Screen | A room with seats | When it is rebuilt | Garden, 8 seats |
| Seat | A place in a room | No | B3, premium |
| Show | A film in a room at a time | Hardly | Nosferatu, Garden, Saturday 22:00 |
| Seat of a show | The thing that is sold | Free, held, sold | B3 on Saturday at 22:00 |
| Booking | Seats of a show for one customer | Pending to confirmed | 3: B3 and B4, Lee, 3600 |
show_seat.Questions
Six questions, and what each answer changes
| Ask | If yes | If no |
|---|---|---|
| Numbered seats? | A map of seats for each show | A counter: much easier |
| Hold while paying? | A state with an end | Whoever pays first wins, and pays in vain |
| Several seats at once? | All or nothing | One lock for each seat would do |
| Do prices vary? | A price rule, and the price stored in the booking | A constant |
| Can it be cancelled? | A refund rule, seats free again | Confirmed is the end |
| One process or many? | Many: the database is the referee | One: a lock for each show |
Design, first try
The design most people draw first
It copies the prompt: a seat has a status and locks itself. It even has a version number for optimistic locking. Then the second show of the evening begins.
The design to avoid: the state sits in the chair
1/5One class for everything
Search, booking, payment, mail and timers. And because there is one instance, every test shares it.
owns (dies together)useshas (lives on)
for (String id : seatIds) { Seat seat = show.getSeat(id); if (seat == null) throw new SeatNotFound(id); // seats taken so far stay reserved if (!seat.tryReserve()) { taken.forEach(Seat::release); // release() frees whoever holds it now throw new SeatNotAvailable(id); } taken.add(seat);}release does not check who holds the seat now.Design, better
The design to reach
The design to reach: one seat map for each show
1/5One door
BoxOffice has three verbs: hold, pay, cancel. And one question: which seats are free.
usesimplementsowns (dies together)has (lives on)
booking = office.hold("S1", ["B3", "B4"], "lee") # both or Refused, with the seats that are goneoffice.pay(booking.id, "lee") # charged once, however often you pressoffice.cancel(booking.id, "lee") # cents that come backlock, release or expire.Hold, then pay
Roles
What each class owns
| Class | Knows | Does | Does not |
|---|---|---|---|
| BoxOffice | Shows, bookings, the rules around | Orders the steps of hold, pay, cancel | Decide who has a seat |
| SeatMap | Who has which seat of one show, the lock | Takes, gives back, changes the status | Charge, print, know prices |
| Booking | Seats, customer, cents, until, status | Nothing. It is a record | Run a timer |
| Show, Seat | Facts | Nothing | Change |
| Pricing | Rates | Cents for a seat in a show | Know who buys |
| Payments | A bank | Charge and refund by key | Know seats |
The hard part
Two people, one seat
Ann and Ben see A1 free on their screens. Both click. A check followed by a change has a gap, and in the gap there is room for another thread.
The gap
from threading import Barrier, Threadseats = {"A1": "free"}gate = Barrier(2)sure = []def book(who): if seats["A1"] == "free": # check gate.wait() # the unlucky moment, on purpose seats["A1"] = who # act sure.append(who)threads = [Thread(target=book, args=(w,)) for w in ("ann", "ben")][t.start() for t in threads][t.join() for t in threads]print(sorted(sure), "both think they have A1")With a lock for the show
What do you lock?
BreaksNothing, the screen shows what is free
- How
- Trust the map the customer saw.
- Limit
- The map is seconds old.
- Choose when
- Never.
WorksEach seat
- How
- Lock the seats one by one, in sorted order.
- Limit
- Order, undo, many locks. Gains little: the work under the lock is a few map lookups.
- Choose when
- Huge halls, measured.
StrongEach show
- How
- One lock in each seat map.
- Limit
- People who want different seats of one show wait microseconds.
- Choose when
- Here. Shows do not disturb each other.
Time
A hold that ends by itself
| Way | Good | Trouble |
|---|---|---|
| A timer for each booking | Exact | Lost on restart. Races with the payment. 10,000 timers |
| A job every minute | Simple | Seats stay blocked up to a minute too long |
| Compare when somebody looks | Always right, nothing to run | Screens are not told. A sweeper can do that |
How long?
| Minutes | Customer | Cinema |
|---|---|---|
| 2 | Cannot find the card | Few empty seats |
| 5 to 10 | Comfortable | The usual agreement |
| 30 | Goes for a walk | The best row looks sold and is not |
Money
Prices, refunds, whole cents
| Seats | Base | Saturday, plus 20% | Back 49 h before | Back 3 h before |
|---|---|---|---|---|
| B3, B4 premium | 3000 | 3600 | 3600 | 1800 |
| A1 vip | 2000 | 2400 | 2400 | 1200 |
| B1 premium and A4 vip | 3500 | 4200 | 4200 | 2100 |
Holds up
- Integer cents, stored in the booking
- One key for each charge:
booking-3 - Look before you charge
- Refund by a rule, after the seats are given back
Breaks
- Price from the browser
- A new key for each try
- Charge, then find out that the hold is over
int totalAmount: rupees, cents?
Summary
The whole topic in one minute.
The state belongs to the seat of a show. One map and one lock for each show; check all seats, then write all. A hold is a pending booking with an end, and expired is a comparison with the clock, so no timer can write it at the wrong moment.
Paying has three steps: look and mark PAYING under the lock, charge outside it with the key of the booking, record the answer under it. Declined goes back with the old deadline. Silence stays PAYING until a job has asked the bank.
- The state belongs to the pair of show and seat, not to the chair.
- One lock for each show. Check all seats, then write all: all or nothing without an undo.
- A hold is a booking with an end. Expired is a comparison, not a stored state.
- PAYING keeps the seats while the bank thinks. Look before you charge.
- The key of a charge is the booking. No answer means ask again with the same key.
- Prices and ways to pay are interfaces. The price is fixed at the hold.
- Many servers: the same rules as one conditional update in a database.
Sources
- PostgreSQL: explicit locking and deadlocks
- PostgreSQL: transaction isolation
- Redis: distributed locks
- Stripe: idempotent requests
- Stripe: managing limited inventory
- Stripe: place a hold on a payment method
- pretix API: cart positions
- pretix API: seats
- pretix API: check-in lists
- seats.io: booking and holding objects
- Jakarta Persistence: Version
- Java: DelayQueue
- Caffeine: refresh