Skip to main content
System DesignDSA & CodingIndia Tech Careers

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.

InterviewPilot TeamNovember 23, 20266 min read

"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:

  1. List movies playing in a city, and the shows for a movie.
  2. Show the seat map for a show, with availability.
  3. Book one or more seats for a show. No double booking.
  4. Seats have categories (silver, gold, recliner) with different prices.
  5. Cancel a booking.

Out of scope unless asked: real payments, offers and coupons, food add-ons, reviews.

Entities

ClassResponsibility
Movieid, title, duration
Theatre, Screena theatre has screens; a screen has a seat layout
Seatid, row, category
Showa movie on a screen at a time; owns seat state for that show
SeatHoldseats, user, expiry
Bookingid, show, seats, user, amount, status
PricingStrategyprice of seats for a show
BookingServicehold, 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

  1. User picks seats → hold(show, seats, user): atomically check all are free, mark them held with an expiry, return a hold id.
  2. User pays (outside our scope) → confirm(hold_id): if the hold hasn't expired, mark seats booked and create a Booking.
  3. 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 expiry

Demo 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 h catches 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.

Try it freeHow the AI interview assistant works3 free sessions a day · Windows 10/11 · no card required

Follow-up questions

Follow-upAnswer sketch
Search movies by city, language, genreA SearchService over an index; filters as a Specification/Strategy
Partial cancellationBooking holds seat lines; cancel frees a subset and recalculates
Offers and couponsDecorator or chain of discount rules applied after pricing
Waitlist for sold-out showsObserver 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 Seat instead of per show.
  • No locking, or a global lock around everything.
  • Holding some of the requested seats when others are taken.

Frequently asked questions

Both. As machine coding it's about classes and safe booking in one process. As system design it becomes about distributed seat locks, caching show listings and payment integration.

Make the check-and-hold step atomic: take a lock per show (in memory), or use a conditional database update or unique constraint on (show, seat) in a real system.

A few minutes is typical. Make it configurable and mention the trade-off: too short and payments fail mid-way; too long and popular shows look sold out.

No. Put payment behind an interface and simulate success or failure in your demo.

Was this article useful?

Discussion

No comments yet. Been through an interview like this? Your experience could help the next candidate.

You’re posting anonymously — it appears after a quick review. Sign in to post under your name instantly.
0/2000

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.