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.
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.
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:
- AB-BA Deadlock: User 1 locks
A4then waits forA5, while User 2 locksA5then waits forA4. - Late Webhook Double-Booking: User 1's
600 shold expires, User 2 holds and pays forA4, and then User 1's delayed payment gateway callback marksA4BOOKEDfor User 1. - Price Drift: Dynamic surge pricing changes between seat selection and payment capture, causing a mismatch with the quoted checkout total.
AVAILABLE -> HELD (600s TTL + Fence) -> BOOKED
A seat only transitions from HELD to BOOKED if the request presents the active fencing token before expiresAt.
- 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.
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?
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 mshold latency SLA. - Partial Hold Leaks: Locking
A4then failing onA5without rollback leavesA4stranded inHELD. - Mutable Pricing: Recomputing surge pricing during
confirmBooking()charges the user a different amount than quoted.
Naive solution (and why coarse show-level locks break)
- No backpressure on spikes
- Implicit shared state
- Cascading tail latency
- Explicit capacity budgets
- Isolated failure domains
- Predictable p99 latency
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
seatIdslexicographically (A4 < A5) before acquiring per-seat locks or running an atomicSELECT ... FOR UPDATE/ CAS batch. - Monotonic Fencing Token: Each
HELDtransition mints a uniquefence_tokenand freezesquoted_pricevia composablePricingStrategyrules (BaseTier,OccupancySurge,MatineeDiscount). - Idempotent Confirmation: Payment webhooks pass
(booking_id, fence_token, idempotency_key); expired or mismatched tokens are rejected with409 Conflict.
Sorted Lock Acquisition & Late-Webhook Rejection
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()
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: Make the trade-off yourself.
Why does BookingEngine sort requested seat IDs before acquiring per-seat locks?