Skip to main content
← PROBLEMS / LLD
An end-to-end domain learning journey

Design a Movie Ticket
Booking System (LLD).

A movie ticket booking engine models seats with a 3-state lifecycle (AVAILABLE, HELD, BOOKED), acquires multi-seat locks in sorted seat-ID order, and validates monotonic fencing tokens on payment confirmation.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, always sort seat IDs before acquiring multi-seat locks to prevent deadlocks, freeze the dynamic price snapshot at hold time, and verify the fencing token before transitioning HELD to BOOKED.

TL;DR30-second simplified summary
▾

Core Mechanics: During an IMAX premiere rush (50,000 concurrent users competing for 350 seats), users frequently select 2–4 adjacent seats simultaneously.

Visual & Structural Flow: Depicts AVAILABLE -> HELD (600s TTL + Fence) -> BOOKED (AVAILABLE -> HELD -> BOOKED); Sorted Lock Acquisition & Late-Webhook Rejection (User 1 -> BookingEngine -> SeatStore -> PaymentGW).

Trade-Offs & Production: A naive LLD wraps holdSeats() in a single synchronized lock on the Show object or updates seats one-by-one in a loop: Global Show Contention: Locking the entire 350-seat. Clean LLD separates Concurrency Control, State Lifecycle, and Pricing Strategy: Deadlock-Free Multi-Seat Lock: Sort requested seatIds lexicographically (`A4 <.

Failure Modes & Application: The same 3-state lease + fencing pattern powers high-contention reservation systems at scale: Event Ticketing (Ticketmaster / BookMyShow): Distributed Redis/Postgres seat holds with sorted lock keys and TTL sweeps.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why atomic seat locking and fencing matter in ticketing LLD.

Why this matters: The mechanism: understand how Why atomic seat locking and fencing matter in ticketing LLD works from first principles.

Think of Why atomic seat locking and fencing matter in ticketing LLD as the intuition layer for Design a Movie Ticket Booking System (LLD): The mechanism: understand how Why atomic seat locking and fencing matter in ticketing LLD works from first principles.

During an IMAX premiere rush (50,000 concurrent users competing for 350 seats), users frequently select 2–4 adjacent seats simultaneously. If seat reservation is not atomic and deadlock-free, two users selecting (A4, A5) and (A5, A4) can deadlock, or a delayed payment webhook arriving after the 600 s hold TTL can overwrite a seat already reassigned to another customer.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens without sorted locking and fencing tokens.

Why this matters: The problem: see what breaks without What happens without sorted locking and fencing tokens under real concurrency or scale.

Without strict state transitions and lease fencing, three race conditions corrupt inventory:

  1. AB-BA Deadlock: User 1 locks A4 then waits for A5, while User 2 locks A5 then waits for A4.
  2. Late Webhook Double-Booking: User 1's 600 s hold expires, User 2 holds and pays for A4, and then User 1's delayed payment gateway callback marks A4 BOOKED for User 1.
  3. Price Drift: Dynamic surge pricing changes between seat selection and payment capture, causing a mismatch with the quoted checkout total.
3-State Seat Lifecycle

AVAILABLE -> HELD (600s TTL + Fence) -> BOOKED

atomic hold + price snapshotvalid fenceToken + paid600s TTL expired / cancelAVAILABLESelectable on seat mapHELD600s TTL + fenceTokenBOOKEDConfirmed & immutable

A seat only transitions from HELD to BOOKED if the request presents the active fencing token before expiresAt.

Engineering Decision Framework
Problem
How to implement Design a Movie Ticket Booking System (LLD) without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, always sort seat IDs before acquiring multi-seat locks to prevent deadlocks, freeze the dynamic price snapshot at hold time, and verify the fencing token before transitioning HELD to BOOKED.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Movie Ticket Booking System (LLD) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why coarse show-level locks break).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

A naive LLD wraps holdSeats() in a single synchronized lock on the Show object or updates seats one-by-one in a loop:

  • Global Show Contention: Locking the entire 350-seat show serializes users booking unrelated rows, failing the < 50 ms hold latency SLA.
  • Partial Hold Leaks: Locking A4 then failing on A5 without rollback leaves A4 stranded in HELD.
  • Mutable Pricing: Recomputing surge pricing during confirmBooking() charges the user a different amount than quoted.
Design Trade-Off

Naive solution (and why coarse show-level locks break)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Sorted Seat Locking, Fencing Tokens & Strategy Pricing.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Clean LLD separates Concurrency Control, State Lifecycle, and Pricing Strategy:

  • Deadlock-Free Multi-Seat Lock: Sort requested seatIds lexicographically (A4 < A5) before acquiring per-seat locks or running an atomic SELECT ... FOR UPDATE / CAS batch.
  • Monotonic Fencing Token: Each HELD transition mints a unique fence_token and freezes quoted_price via composable PricingStrategy rules (BaseTier, OccupancySurge, MatineeDiscount).
  • Idempotent Confirmation: Payment webhooks pass (booking_id, fence_token, idempotency_key); expired or mismatched tokens are rejected with 409 Conflict.
Fenced Checkout Flow

Sorted Lock Acquisition & Late-Webhook Rejection

User 1BookingEngineSeatStorePaymentGW1. hold([A5, A4]) -> sort [A4, A5]2. CAS AVAILABLE->HELD fence=423. Hold 600s + price snapshot4. 600s elapsed -> revert AVAILABLE5. Late webhook fence=42 -> 409

Sorting seat IDs eliminates AB-BA deadlocks, and fence=42 validation blocks stale payment callbacks after TTL expiry.

from dataclasses import dataclass
from enum import Enum
import threading, time

class SeatStatus(Enum):
    AVAILABLE = "AVAILABLE"
    HELD = "HELD"
    BOOKED = "BOOKED"

@dataclass
class SeatRecord:
    seat_id: str
    status: SeatStatus = SeatStatus.AVAILABLE
    fence_token: int = 0
    expires_at: float = 0.0
    lock: threading.Lock = None

    def __post_init__(self):
        self.lock = threading.Lock()

class BookingEngine:
    def __init__(self, seats: dict[str, SeatRecord], hold_ttl_s: int = 600):
        self.seats = seats
        self.hold_ttl_s = hold_ttl_s
        self._seq = 0
        self._seq_lock = threading.Lock()

    def hold_seats(self, seat_ids: list[str], quoted_price: float) -> int:
        ordered = sorted(set(seat_ids))  # Deadlock-free canonical order
        acquired = []
        now = time.monotonic()
        try:
            for sid in ordered:
                seat = self.seats[sid]
                seat.lock.acquire()
                acquired.append(seat)
                if seat.status == SeatStatus.HELD and seat.expires_at <= now:
                    seat.status = SeatStatus.AVAILABLE
                if seat.status != SeatStatus.AVAILABLE:
                    raise ValueError(f"Seat {sid} unavailable")
            with self._seq_lock:
                self._seq += 1
                token = self._seq
            for seat in acquired:
                seat.status = SeatStatus.HELD
                seat.fence_token = token
                seat.expires_at = now + self.hold_ttl_s
            return token
        finally:
            for seat in reversed(acquired):
                seat.lock.release()

    def confirm_seats(self, seat_ids: list[str], fence_token: int) -> None:
        ordered = sorted(set(seat_ids))
        now = time.monotonic()
        acquired = [self.seats[sid] for sid in ordered]
        for s in acquired:
            s.lock.acquire()
        try:
            for s in acquired:
                if s.status != SeatStatus.HELD or s.fence_token != fence_token or s.expires_at <= now:
                    raise RuntimeError("Stale or expired fencing token")
            for s in acquired:
                s.status = SeatStatus.BOOKED
        finally:
            for s in reversed(acquired):
                s.lock.release()
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Seat-Locking & Fencing Patterns apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

The same 3-state lease + fencing pattern powers high-contention reservation systems at scale:

  • Event Ticketing (Ticketmaster / BookMyShow): Distributed Redis/Postgres seat holds with sorted lock keys and TTL sweeps.
  • Ride-Sharing & Hotel Inventory: Holding a driver dispatch offer or hotel room for 60–300 s before payment capture.
  • Distributed Lock Services: Using ZooKeeper/etcd fencing tokens to reject zombie workers after GC pauses.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does BookingEngine sort requested seat IDs before acquiring per-seat locks?

Recommended Learning Flow