Design BookMyShow: Machine Coding Round Walkthrough
The movie ticket booking machine coding problem solved end to end: requirements, entities, seat holds with expiry, concurrency-safe booking, pricing by seat type, runnable Python code, and the follow-ups interviewers push on.
"Design BookMyShow" is a favourite machine coding problem at Indian product companies because it mixes ordinary modelling with one hard part: two people clicking the same seat at the same time. This walkthrough uses the workflow from our machine coding guide.
Clarify requirements
In scope for 90 minutes:
- List movies playing in a city, and the shows for a movie.
- Show the seat map for a show, with availability.
- Book one or more seats for a show. No double booking.
- Seats have categories (silver, gold, recliner) with different prices.
- Cancel a booking.
Out of scope unless asked: real payments, offers and coupons, food add-ons, reviews.
Entities
| Class | Responsibility |
|---|---|
Movie | id, title, duration |
Theatre, Screen | a theatre has screens; a screen has a seat layout |
Seat | id, row, category |
Show | a movie on a screen at a time; owns seat state for that show |
SeatHold | seats, user, expiry |
Booking | id, show, seats, user, amount, status |
PricingStrategy | price of seats for a show |
BookingService | hold, confirm, cancel; enforces the rules |
Why seat state lives on Show: the same physical seat is free for the 6 p.m. show and booked for the 9 p.m. one.
The booking flow
- User picks seats →
hold(show, seats, user): atomically check all are free, mark them held with an expiry, return a hold id. - User pays (outside our scope) →
confirm(hold_id): if the hold hasn't expired, mark seats booked and create aBooking. - If the user abandons, the hold expires and the seats free up.
The all-or-nothing hold stops a user from ending up with seats 1 and 3 but not seat 2.
The code
import itertools
import threading
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
class Category(Enum):
SILVER = "silver"
GOLD = "gold"
RECLINER = "recliner"
@dataclass(frozen=True)
class Seat:
seat_id: str
category: Category
@dataclass
class Hold:
hold_id: int
show_id: str
seat_ids: tuple[str, ...]
user: str
expires_at: datetime
class Show:
def __init__(self, show_id: str, movie: str, seats: list[Seat], starts_at: datetime):
self.show_id, self.movie, self.starts_at = show_id, movie, starts_at
self.seats = {s.seat_id: s for s in seats}
self.booked: dict[str, str] = {} # seat_id -> booking id
self.held: dict[str, Hold] = {} # seat_id -> active hold
self.lock = threading.Lock() # one lock per show
def _release_expired(self, now: datetime) -> None:
for seat_id, hold in list(self.held.items()):
if hold.expires_at <= now:
del self.held[seat_id]
def available(self, now: datetime) -> list[str]:
with self.lock:
self._release_expired(now)
return sorted(s for s in self.seats if s not in self.booked and s not in self.held)
class PricingStrategy:
def price(self, show: Show, seats: list[Seat]) -> int:
raise NotImplementedError
class CategoryPricing(PricingStrategy):
RATES = {Category.SILVER: 200, Category.GOLD: 350, Category.RECLINER: 600}
def price(self, show, seats):
return sum(self.RATES[s.category] for s in seats)
@dataclass
class Booking:
booking_id: str
show_id: str
seat_ids: tuple[str, ...]
user: str
amount: int
status: str = "CONFIRMED"
@dataclass
class BookingService:
pricing: PricingStrategy
hold_minutes: int = 5
shows: dict[str, Show] = field(default_factory=dict)
holds: dict[int, Hold] = field(default_factory=dict)
bookings: dict[str, Booking] = field(default_factory=dict)
_ids: itertools.count = field(default_factory=lambda: itertools.count(1))
def hold(self, show_id: str, seat_ids: list[str], user: str, now: datetime) -> Hold:
show = self.shows[show_id]
with show.lock: # check-and-hold is atomic per show
show._release_expired(now)
unknown = [s for s in seat_ids if s not in show.seats]
if unknown:
raise ValueError(f"unknown seats {unknown}")
taken = [s for s in seat_ids if s in show.booked or s in show.held]
if taken:
raise RuntimeError(f"seats not available: {taken}")
h = Hold(next(self._ids), show_id, tuple(seat_ids), user,
now + timedelta(minutes=self.hold_minutes))
for s in seat_ids:
show.held[s] = h
self.holds[h.hold_id] = h
return h
def confirm(self, hold_id: int, now: datetime) -> Booking:
h = self.holds.pop(hold_id, None)
if h is None:
raise ValueError("unknown hold")
show = self.shows[h.show_id]
with show.lock:
if h.expires_at <= now or any(show.held.get(s) is not h for s in h.seat_ids):
raise RuntimeError("hold expired; please select seats again")
booking_id = f"BKG{h.hold_id}"
for s in h.seat_ids:
del show.held[s]
show.booked[s] = booking_id
amount = self.pricing.price(show, [show.seats[s] for s in h.seat_ids])
booking = Booking(booking_id, h.show_id, h.seat_ids, h.user, amount)
self.bookings[booking_id] = booking
return booking
def cancel(self, booking_id: str) -> None:
b = self.bookings[booking_id]
show = self.shows[b.show_id]
with show.lock:
for s in b.seat_ids:
show.booked.pop(s, None)
b.status = "CANCELLED"
if __name__ == "__main__":
seats = [Seat(f"A{i}", Category.SILVER) for i in range(1, 5)] + \
[Seat(f"B{i}", Category.GOLD) for i in range(1, 3)]
t0 = datetime(2026, 11, 23, 18, 0)
svc = BookingService(CategoryPricing())
svc.shows["S1"] = Show("S1", "Interstellar", seats, t0 + timedelta(hours=3))
h1 = svc.hold("S1", ["A1", "A2", "B1"], "asha", t0)
try:
svc.hold("S1", ["A2"], "ravi", t0)
except RuntimeError as e:
print("ravi:", e) # A2 is held by asha
print(svc.confirm(h1.hold_id, t0 + timedelta(minutes=2)).amount) # 750
h2 = svc.hold("S1", ["A3"], "ravi", t0)
print(svc.shows["S1"].available(t0 + timedelta(minutes=6))) # A3 released after expiryDemo output: Ravi is refused A2 while Asha holds it, Asha's three seats cost ₹750, and Ravi's unconfirmed hold on A3 lapses after five minutes.
Design decisions to say out loud
- Lock per show, not global. Bookings for different shows never wait on each other.
- Lazy expiry. Expired holds are cleared when someone reads or writes the show, so there's no background thread to manage. A real system would also run a sweeper.
- Hold identity check on confirm. If a hold expired and someone else grabbed the seat,
show.held.get(s) is not hcatches it. - Pricing outside the booking flow. Weekend pricing or convenience fees are a new Strategy.
In a real distributed system
Interviewers often ask, "What changes with many servers?"
- In-memory locks don't work across machines. Use the database: a row per (show, seat) with a status and
hold_expires_at, and claim seats with a conditional update (UPDATE … WHERE status = 'FREE' OR hold_expires_at < now()), checking the affected-row count. - Alternatively, a Redis
SET key value NX PX <ttl>per seat works as a short-lived hold. - Seat maps are read far more than written, so cache them, but always re-check availability at hold time.
- Payment callbacks must be idempotent: confirming the same hold twice shouldn't create two bookings. See design a payment system.
Practising machine coding for product companies?
In a live round, InterviewPilot reads the problem statement off your screen and answers with entities, extension points and runnable code, in an overlay that screen shares don't capture.
Follow-up questions
| Follow-up | Answer sketch |
|---|---|
| Search movies by city, language, genre | A SearchService over an index; filters as a Specification/Strategy |
| Partial cancellation | Booking holds seat lines; cancel frees a subset and recalculates |
| Offers and coupons | Decorator or chain of discount rules applied after pricing |
| Waitlist for sold-out shows | Observer on seat release, notifying the queue head |
| Prevent seat-gap rules (no single empty seat left) | Validation step in hold, as a pluggable rule |
Mistakes that cost points
- Booking in one step, with no hold and no payment window.
- Seat availability stored on
Seatinstead of per show. - No locking, or a global lock around everything.
- Holding some of the requested seats when others are taken.
Related
- Design Splitwise
- Design a parking lot
- Design Snake and Ladder
- Flipkart, Razorpay and Swiggy interview process
Frequently asked questions
Was this article useful?
Bring backup into your next round.
Install InterviewPilot, upload your resume, and walk in with structured answers a keystroke away — visible to you and nobody else.
More from the blog
Design Splitwise: Machine Coding Round Walkthrough
A complete walkthrough of the Splitwise / expense-sharing machine coding problem: requirements, entities, a Strategy-based split design, balance tracking, debt simplification, runnable Java code, and the follow-up questions interviewers ask.
Design a Parking Lot: Low-Level Design Interview Walkthrough
The parking lot LLD problem solved end to end: clarifying questions, entities, spot allocation and pricing as Strategies, tickets, multiple floors and gates, runnable Python code, concurrency, and the follow-ups interviewers ask.
The Coding Interview Guide for Software Engineers in India (2026)
Everything a software engineer in India needs for coding rounds: how online assessments, DSA rounds, machine coding and CS fundamentals differ by company type, a 10-week preparation plan, and how to perform in the room.
Discussion
No comments yet. Been through an interview like this? Your experience could help the next candidate.