What you will learn
- The domain model for a movie booking system.
- Why booking is two steps: hold, then confirm after payment.
- How to prevent double booking with locks in memory and with conditional updates in a database.
Requirements
- Cities have theatres; theatres have screens; a show is a movie on a screen at a time.
- Users browse shows and pick specific seats.
- Selected seats are held for a few minutes while the user pays.
- If payment succeeds, seats become booked; if it fails or the hold expires, they become free again.
- No seat is ever booked twice, even when many users click at once.
- Selecting several seats is all-or-nothing.
Domain model
City *-- Theatre *-- Screen *-- SeatLayout
Show --> Movie, Show --> Screen, Show *-- "many" ShowSeat (status per show)
Booking --> User, Booking --> Show, Booking --> "many" ShowSeat, Booking --> Payment
ShowSeat.status: FREE -> HELD -> BOOKED (HELD -> FREE on expiry or failed payment)
Seat status belongs to the show, not the physical seat: seat A1 is booked for the 6 pm show and free for 9 pm.
Hold, then confirm
Payment takes time and can fail. Booking immediately on click would leave seats stuck when payments fail; booking only after payment would let two users pay for the same seat. A hold with expiry solves both:
hold(show, seats, user): atomically check all seats are free and mark them held, with an expiry time.- User pays.
confirm(show, seats, user, payment_ok): if the hold is still theirs and valid, mark booked; otherwise fail (and refund if money was taken).
The code
"""Movie ticket booking (BookMyShow-style): seat holds with expiry and no double booking."""
import threading
import time
from dataclasses import dataclass, field
from enum import Enum
class SeatStatus(Enum):
FREE = "free"
HELD = "held"
BOOKED = "booked"
@dataclass
class Seat:
id: str
status: SeatStatus = SeatStatus.FREE
held_by: str | None = None
hold_expires: float = 0.0
@dataclass
class Show:
id: str
movie: str
seats: dict[str, Seat]
lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
class SeatUnavailable(Exception):
pass
class BookingService:
HOLD_SECONDS = 0.2 # 10 minutes in real life; short here for the demo
def __init__(self, clock=time.monotonic):
self.shows: dict[str, Show] = {}
self.clock = clock
def add_show(self, show: Show):
self.shows[show.id] = show
def _release_expired(self, show: Show):
now = self.clock()
for seat in show.seats.values():
if seat.status is SeatStatus.HELD and seat.hold_expires <= now:
seat.status, seat.held_by = SeatStatus.FREE, None
def hold(self, show_id: str, seat_ids: list[str], user: str):
"""All-or-nothing: hold every requested seat or none of them."""
show = self.shows[show_id]
with show.lock: # one lock per show: different shows don't block each other
self._release_expired(show)
unavailable = [s for s in seat_ids if show.seats[s].status is not SeatStatus.FREE]
if unavailable:
raise SeatUnavailable(f"{user}: seats {unavailable} not available")
for s in seat_ids:
seat = show.seats[s]
seat.status, seat.held_by = SeatStatus.HELD, user
seat.hold_expires = self.clock() + self.HOLD_SECONDS
return seat_ids
def confirm(self, show_id: str, seat_ids: list[str], user: str, payment_ok: bool):
show = self.shows[show_id]
with show.lock:
self._release_expired(show)
for s in seat_ids:
seat = show.seats[s]
if seat.status is not SeatStatus.HELD or seat.held_by != user:
raise SeatUnavailable(f"{user}: hold on {s} expired")
for s in seat_ids:
seat = show.seats[s]
if payment_ok:
seat.status = SeatStatus.BOOKED
else:
seat.status, seat.held_by = SeatStatus.FREE, None
return payment_ok
if __name__ == "__main__":
svc = BookingService()
svc.add_show(Show("s1", "Interstellar", {f"A{i}": Seat(f"A{i}") for i in range(1, 6)}))
results = []
def try_book(user):
try:
svc.hold("s1", ["A2", "A3"], user)
results.append(f"{user} holds A2,A3")
except SeatUnavailable as e:
results.append(str(e))
threads = [threading.Thread(target=try_book, args=(f"user{i}",)) for i in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sorted(results))
winner = next(r.split()[0] for r in results if "holds" in r)
time.sleep(0.25) # the winner dawdles past the hold expiry...
try:
svc.confirm("s1", ["A2", "A3"], winner, payment_ok=True)
except SeatUnavailable as e:
print(e)
svc.hold("s1", ["A2", "A3"], "late_user")
svc.confirm("s1", ["A2", "A3"], "late_user", payment_ok=True)
print({s.id: s.status.value for s in svc.shows["s1"].seats.values()})
Output from one run (which user wins the race varies between runs):
['user0 holds A2,A3', "user1: seats ['A2', 'A3'] not available", "user2: seats ['A2', 'A3'] not available", "user3: seats ['A2', 'A3'] not available", "user4: seats ['A2', 'A3'] not available"]
user0: hold on A2 expired
{'A1': 'free', 'A2': 'booked', 'A3': 'booked', 'A4': 'free', 'A5': 'free'}
Five users race for the same two seats; exactly one wins. The winner pays too late, the hold expires, and another user books the seats.
Design choices:
- One lock per show: bookings for different shows never block each other.
- All-or-nothing: the method checks every seat before changing any, inside the same lock.
- Lazy expiry: expired holds are released when the show is next touched, so no background thread is needed. Production systems often also run a sweeper or use Redis keys with a TTL for holds.
- Injectable clock:
clock=time.monotoniccan be replaced with a fake clock in tests, so expiry is testable without sleeping.
With a database
Across many servers an in-process lock isn’t enough. Common options:
- Conditional update (optimistic):
UPDATE show_seat SET status='HELD', user_id=?, expires_at=? WHERE show_id=? AND seat_id IN (...) AND (status='FREE' OR (status='HELD' AND expires_at < now()))inside a transaction; if the affected row count isn’t the number of seats requested, roll back. - Row locks (pessimistic):
SELECT ... FOR UPDATEon the seat rows, then update. - Unique constraint on
(show_id, seat_id)in a bookings table as the final safety net.
The System Design course covers the surrounding architecture (caching show listings, queues for notifications).
Key takeaways
- Seat status is per show; model a ShowSeat, not just a Seat.
- Use hold-with-expiry plus confirm to handle slow and failing payments.
- Make multi-seat holds all-or-nothing under one lock or one transaction.
- In a database, rely on conditional updates, row locks or unique constraints, not application checks alone.
Exercises
- Replace
time.monotonicwith a fake clock in a test and verify a hold expires without sleeping. - Add a
cancel_bookingthat frees seats and records a refund, allowed only until 2 hours before the show. - Write the SQL schema for shows, show_seats and bookings, including the constraint that prevents double booking.
Quiz
- Why not mark seats booked immediately when the user clicks them?
- Why is there one lock per show rather than one global lock?
- What does the hold expiry protect against?
Show answers
- Payment might fail or be abandoned, leaving seats unavailable to everyone; the hold reserves them temporarily instead.
- Bookings for different shows don’t conflict, so a global lock would block them unnecessarily and limit throughput.
- Users who abandon checkout: without expiry, their held seats would never become available again.