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
See it run
Holds on a seat map: calls travel, owners change, the clock moves, and the matching lines light up.
Operations
Hold two seats
Check all, then write all, under the lock of the show.
Step 1 of 5
Eight o'clock
Nobody has anything in show S1. A seat that is not in the map is free.
Step 1: Eight o'clock
def take(self, booking): with self._lock: lost = tuple(s for s in booking.seat_ids if self._owner(s)) if lost: raise Refused(Reason.TAKEN, lost) for seat_id in booking.seat_ids: self._taken[seat_id] = booking- Cost
- O(seats wished)
- Guarantee
- All or none
- Seat by seat
- needs an undo
Nothing written before all is checked: nothing to undo.
In the real world
The same movie ticket booking doing real jobs. Pick one and step through it.
Charged, and the answer is lost.
Step 1 of 4
Paying
The charge is on its way.
Step 1: Paying
def pay(self, booking_id, customer): booking = self._mine(booking_id, customer) seats = self._map(booking.show_id) if seats.start_paying(booking): try: self._payments.charge(f"booking-{booking.id}", booking.cents) except Declined: seats.end_paying(booking, paid=False) raise seats.end_paying(booking, paid=True) return bookingCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Status in the chair
criticalThe room has two shows tonight. Sold for the first means sold for both.
Wrongseat.status = BOOKEDRightseat_map[show.id]._taken["B3"] = bookingUndo without an owner
criticalThe undo frees a seat that somebody else has by now.
Wrongexcept NotAvailable: for s in reserved: s.release()Rightlost = [s for s in wanted if self._owner(s)]if lost: raise Refused(Reason.TAKEN, lost) # nothing written yetA timer writes EXPIRED
criticalIt races with the payment: charged, confirmed, and the seat is sold to another.
Wrongschedule(lambda: booking.expire(), minutes=10)Rightif booking.status is PENDING and booking.until <= now: return NoneTimeout is not declined
criticalThe customer was charged and has no seat.
Wrongexcept Exception: seats.end_paying(booking, paid=False)Rightexcept Declined: seats.end_paying(booking, paid=False) # silence stays PAYINGA new key for each try
majorEvery retry is a new charge.
Wrongkey = f"{booking.id}-{time.time()}"Rightkey = f"booking-{booking.id}"Price from the browser
majorIt is a wish. Somebody wishes for 1 cent.
Wrongdef hold(show, seats, total): ...Rightcents = sum(pricing.cents(show, s) for s in seats)
Interview tips
Open with
- The seat of a show.
- All or none.
- Who notices the end of a hold?
Reject aloud
- No status in the chair.
- No EXPIRED.
- No lock held for ten minutes.
Prove it
- Three customers, twelve minutes.
- Two clicks on Pay.
- A silent bank.
Never
- The bank under the lock.
- Charge first, look later.
- A float for money.