AlgoViz

Design a movie ticket booking system

hard 90 min

Sell the numbered seats of a cinema: choose, hold for ten minutes, pay, cancel.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:35

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

  1. 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.

  2. 1960

    The first experimental system of SABRE, made by American Airlines with IBM for seat reservations, goes online. The full system follows in 1964.

  3. 1976

    Ticketmaster is founded on 2 October in Phoenix, Arizona.

  4. 1989

    Moviefone is founded in the United States: cinema times by telephone.

  5. 1994

    The QR code is invented at Denso Wave in Japan, for car parts. Cinema doors came later.

  6. 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.

Step 1 of 3

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.

An evening at the open-air cinema
Film at 9:008:00A1A2A3A4B1B2B3B4Pegs hold10 minutes

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

Paying has no arrow called ran out. While the bank is thinking, the seats stay taken.

Words

Six nouns, and the one that matters

WordIt isChanges?Example
MovieA filmNoNosferatu
ScreenA room with seatsWhen it is rebuiltGarden, 8 seats
SeatA place in a roomNoB3, premium
ShowA film in a room at a timeHardlyNosferatu, Garden, Saturday 22:00
Seat of a showThe thing that is soldFree, held, soldB3 on Saturday at 22:00
BookingSeats of a show for one customerPending to confirmed3: B3 and B4, Lee, 3600
The fifth row has no class of its own in our design: it is an entry in the seat map of the show. In a database it is a table, show_seat.

Questions

Six questions, and what each answer changes

AskIf yesIf no
Numbered seats?A map of seats for each showA counter: much easier
Hold while paying?A state with an endWhoever pays first wins, and pays in vain
Several seats at once?All or nothingOne lock for each seat would do
Do prices vary?A price rule, and the price stored in the bookingA constant
Can it be cancelled?A refund rule, seats free againConfirmed is the end
One process or many?Many: the database is the refereeOne: 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

BookingSystem- instance- movies, shows: List- seats: List<Seat>+ search(), book()+ pay(), refund()+ sendEmail()+ startTimer(booking)

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)

Java
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);}
Reserving seat by seat needs an undo, and this undo has two holes: an unknown seat leaves the first ones reserved, and 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

BoxOffice- maps: Map<show, SeatMap>- bookings: Map<id, Booking>+ hold(show, seats, who): Booking+ pay(booking, who): Booking+ cancel(booking, who): cents+ seats(show): Map

1/5One door

BoxOffice has three verbs: hold, pay, cancel. And one question: which seats are free.

usesimplementsowns (dies together)has (lives on)

Cinema, hall and city are words in the show until something is asked of them.
Python
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 back
Three verbs. The customer never says lock, release or expire.

Hold, then pay

Two short steps under the lock, and the slow one between them without it.

Roles

What each class owns

ClassKnowsDoesDoes not
BoxOfficeShows, bookings, the rules aroundOrders the steps of hold, pay, cancelDecide who has a seat
SeatMapWho has which seat of one show, the lockTakes, gives back, changes the statusCharge, print, know prices
BookingSeats, customer, cents, until, statusNothing. It is a recordRun a timer
Show, SeatFactsNothingChange
PricingRatesCents for a seat in a showKnow who buys
PaymentsA bankCharge and refund by keyKnow 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

Python
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")
The barrier forces the unlucky order, so both succeed every time.
Edit and run it in your browser

With a lock for the show

Checking all before writing any is what makes it all or nothing. There is no undo, because nothing has been done.

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

WayGoodTrouble
A timer for each bookingExactLost on restart. Races with the payment. 10,000 timers
A job every minuteSimpleSeats stay blocked up to a minute too long
Compare when somebody looksAlways right, nothing to runScreens are not told. A sweeper can do that
The third is correctness, the second is courtesy. Build the rule on the comparison and the messages on the job.

How long?

MinutesCustomerCinema
2Cannot find the cardFew empty seats
5 to 10ComfortableThe usual agreement
30Goes for a walkThe best row looks sold and is not
Show the remaining time and warn at one minute. One extension is kind, unlimited ones block seats. A limit of open holds for each customer stops hoarding.

Money

Prices, refunds, whole cents

SeatsBaseSaturday, plus 20%Back 49 h beforeBack 3 h before
B3, B4 premium3000360036001800
A1 vip2000240024001200
B1 premium and A4 vip3500420042002100
24 hours or more: all. 2 hours or more: half. Less: nothing. The price is fixed when the seats are held, so a price change during payment cannot surprise anybody.

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