Design Movie Ticket Booking (LLD)
Movie ticket booking is one of the most commonly asked LLD problems because it combines several challenging concepts: entity modeling, concurrency control (no double-booking), pricing logic, and temporal constraints (show times, seat locks). The core challenge is ensuring that two users cannot book the same seat simultaneously — a problem that maps directly to real-world production systems.
The interview usually turns on three questions, and this page answers each one in code:
- How long is a seat held, and what happens when the hold expires?
- Two users click the same seat at the same moment. How do you guarantee exactly one winner?
- Payment is slow. What if it finishes after the hold has expired, and the seat has been sold to someone else?
For the database side of the same problem (row locks, optimistic versions, compare-and-set in SQL), see Booking and Inventory Concurrency.
1. Clarifying questions and requirements
| Question | Assumption if the interviewer says "you decide" | What it changes |
|---|---|---|
| Can a user pick several seats? | Yes, and they're held all-or-nothing | hold checks every seat before writing any |
| How long is a hold? | 10 minutes, then the seats return to sale | A deadline per hold, and an injected clock |
| How does payment work? | The user is redirected to a gateway, which calls us back by webhook | beginPayment, onPaymentSucceeded, onPaymentFailed |
| How long may payment take? | 5 minutes from the start of payment | A second deadline, and a sweeper |
| What if the webhook is late, or arrives twice? | Late means refund. Twice means return the same booking. | Idempotent webhook handling |
| Scale? | One process here. Several servers in the follow-ups. | Where the atomic step lives |
| Search, cities, pricing rules? | Kept from the first-pass design below, not the focus | Nothing new |
Requirements
Functional Requirements
| # | Requirement | Details |
|---|---|---|
| FR-1 | Browse movies | Search by city, genre, language |
| FR-2 | View showtimes | List available shows for a movie at a theater |
| FR-3 | Select seats | Display seat map, allow seat selection |
| FR-4 | Seat locking | Temporarily lock seats during checkout (TTL-based) |
| FR-5 | Book tickets | Confirm booking after payment |
| FR-6 | Cancel booking | Cancel and release seats with refund policy |
| FR-7 | Pricing | Base price + premium surcharge + convenience fee |
Non-Functional Requirements
- No double booking (strong consistency on seat allocation)
- Seat lock expires after timeout (e.g., 10 minutes)
- Support concurrent users selecting seats for the same show
2. Entities and relationships
| Entity | Owns | Invariant |
|---|---|---|
Show | Its seats, prices, the seat-to-hold and seat-to-booking maps | A seat is booked once, or held by at most one live hold |
Seat | Id and tier | Immutable |
Hold | User, seats, amount, status, deadline | Moves only along the state machine below |
Booking | The confirmed seats and the payment reference | Created once per hold |
BookingService | Shows, holds, the clock, the refund port | Every decision about a show happens under that show's lock |
PaymentGateway | Refunds | Called outside every lock, at most once per payment |
Holds expire lazily. A seat is free if it isn't booked and its latest hold isn't live (HELD or PAYING, and not past its deadline). So an expired hold frees its seats the instant the deadline passes, even if no sweeper has run. The sweeper still matters for payments that time out, because those may need a refund.
3. Class diagram
classDiagram
class BookingService {
-shows: Map~String,Show~
-holds: Map~String,Hold~
-clock: Clock
-gateway: PaymentGateway
+hold(showId, userId, seatIds) Hold
+beginPayment(holdId) Instant
+onPaymentSucceeded(holdId, paymentRef) Booking
+onPaymentFailed(holdId)
+release(holdId)
+sweep()
}
class Show {
+id: String
+seats: Map~String,Seat~
+priceCents: Map~Tier,Long~
-holderOf: Map~String,Hold~
-bookedBy: Map~String,String~
+isFree(seatId, now) boolean
}
class Hold {
+id: String
+userId: String
+seatIds: List~String~
+amountCents: long
+status: HoldStatus
+deadline: Instant
+isLive(now) boolean
}
class Booking {
<<record>>
+id: String
+seatIds: List~String~
+paymentRef: String
}
class Seat {
<<record>>
+id: String
+tier: Tier
}
class PaymentGateway {
<<interface>>
+refund(paymentRef, cents)
}
BookingService "1" o-- "many" Show
BookingService "1" o-- "many" Hold
BookingService --> PaymentGateway
Show "1" *-- "many" Seat
Show ..> Hold : holderOf
Hold --> Booking : once confirmed
The first-pass diagram below is kept. It adds the catalogue side (movies, theatres, halls) that the complete code leaves out to stay focused on holds.
Class Diagram
classDiagram
class Movie {
-id: string
-title: string
-genre: Genre
-language: string
-durationMinutes: number
-rating: number
}
class Theater {
-id: string
-name: string
-city: string
-halls: Hall[]
+addHall(hall)
}
class Hall {
-id: string
-name: string
-seats: Seat[]
-totalCapacity: number
}
class Seat {
-id: string
-row: string
-number: number
-type: SeatType
}
class Show {
-id: string
-movie: Movie
-hall: Hall
-startTime: Date
-endTime: Date
-pricing: PricingStrategy
}
class Booking {
-id: string
-show: Show
-seats: Seat[]
-user: string
-totalAmount: number
-status: BookingStatus
-createdAt: Date
}
class SeatLock {
-seat: Seat
-show: Show
-userId: string
-expiresAt: Date
}
Theater "1" --> "*" Hall
Hall "1" --> "*" Seat
Show "1" --> "1" Movie
Show "1" --> "1" Hall
Booking "1" --> "*" Seat
Booking "1" --> "1" Show
4. Key flows and the hold lifecycle
Two users, one seat
sequenceDiagram
participant U1 as User 1
participant U2 as User 2
participant S as BookingService
participant SH as Show S1 lock
U1->>S: hold(A8, B1)
U2->>S: hold(A8, B2)
S->>SH: lock for user 1
Note over SH: user 2 waits for the lock
SH-->>S: A8 and B1 free, write both
S-->>U1: Hold H1
S->>SH: lock for user 2
SH-->>S: A8 is held by live H1
S-->>U2: seat A8 is taken, nothing held
Payment, on time and late
sequenceDiagram
participant U as User
participant S as BookingService
participant G as Payment gateway
participant W as Sweeper
U->>S: beginPayment(H1)
S-->>U: deadline now plus 5 min
U->>G: pays on the gateway page
alt webhook before the deadline
G->>S: onPaymentSucceeded(H1, pay-1)
S-->>G: Booking B1
else webhook after the deadline
W->>S: sweep()
S->>S: H1 becomes TIMED_OUT, seats freed
G->>S: onPaymentSucceeded(H1, pay-1)
S->>G: refund(pay-1)
end
The hold state machine
stateDiagram-v2
[*] --> HELD: hold
HELD --> PAYING: beginPayment
HELD --> RELEASED: user cancels
HELD --> EXPIRED: TTL passes
PAYING --> CONFIRMED: success webhook before deadline
PAYING --> FAILED: payment declined
PAYING --> TIMED_OUT: payment deadline passes
TIMED_OUT --> TIMED_OUT: late success webhook, refund
CONFIRMED --> CONFIRMED: duplicate webhook, same booking
RELEASED --> [*]
EXPIRED --> [*]
FAILED --> [*]
CONFIRMED --> [*]
Seats follow from the hold: held while the hold is live, booked once it's CONFIRMED, free otherwise.
5. Patterns used, and the alternatives rejected
| Choice | Why |
|---|---|
State machine as an enum on Hold | Seven states, but each transition is two lines. Every method checks the current state first, so an illegal transition fails loudly. State classes would add files without adding behaviour. |
| Lazy expiry plus a sweeper | Correctness never depends on the sweeper running on time. The sweeper only does work that needs side effects. |
| Idempotent webhook | Gateways retry. A second success returns the same booking, and a refund is sent at most once per payment reference. |
| Port for the gateway | PaymentGateway is an interface, so tests use a fake and production uses the real client. See Designing for Testability. |
| Strategy | Kept for pricing in the first-pass code, and used for refund policy in extension 3 |
| Observer | The waitlist in extension 2 |
| Alternative | Why it was rejected |
|---|---|
| A lock per seat | A multi-seat hold would take several locks, so you'd need a global lock order to avoid deadlock. Per-show locking is one lock and is fast enough, since a show has a few hundred seats. |
| One global lock | Correct, but every show would queue behind the busiest one |
| A timer per hold that releases it | Thousands of timers, lost on restart, and they race with payment. A deadline field plus lazy checks has none of these problems. |
| Extending the hold on every user click | Lets one user block seats for ever. One extension, when payment starts, is the rule. |
| Taking payment inside the lock | A gateway call takes seconds, and every other user of the show would wait |
Design Patterns Used
| Pattern | Where Used | Why |
|---|---|---|
| Strategy | PricingStrategy | Different pricing for weekdays, weekends, IMAX, etc. |
| Builder | Constructing Hall with seats | Halls have many seats with different types |
| Repository | BookingService storage | Abstracts persistence layer |
| Observer | Booking status changes | Notify user via email/SMS on confirmation/cancellation |
Correction (2026-11-10): three patterns in the table above aren't in the code
The first-pass code has no Builder (halls are filled with addSeat), no Repository (BookingService stores bookings in a map), and no Observer (nothing is notified on status changes). They're reasonable extensions, but listing them as "used" invites the follow-up "show me where", and there's nothing to show. Strategy, for pricing, is the only one that's really there.
6. Complete code
Each version runs on its own and prints movie booking: all checks passed. All three ran before publishing, and the Java demo's two race tests each repeat 100 times:
- Java 24:
javac -d out MovieBookingDemo.java && java -cp out MovieBookingDemo - Python 3.12:
python movie_booking.py - TypeScript (strict):
tsc --strict --noEmit --target es2022 --types node movie-booking.ts && npx tsx movie-booking.ts
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
enum Tier { REGULAR, PREMIUM }
enum HoldStatus { HELD, PAYING, CONFIRMED, RELEASED, EXPIRED, FAILED, TIMED_OUT }
record Seat(String id, Tier tier) {}
record Booking(String id, String showId, String userId, List<String> seatIds, long amountCents, String paymentRef) {}
final class Hold {
final String id, showId, userId;
final List<String> seatIds;
final long amountCents;
HoldStatus status = HoldStatus.HELD; // all mutable fields guarded by the Show's monitor
Instant deadline;
Booking booking;
Hold(String id, String showId, String userId, List<String> seatIds, long amountCents, Instant deadline) {
this.id = id; this.showId = showId; this.userId = userId; this.seatIds = List.copyOf(seatIds);
this.amountCents = amountCents; this.deadline = deadline;
}
boolean isLive(Instant now) {
return (status == HoldStatus.HELD || status == HoldStatus.PAYING) && !now.isAfter(deadline);
}
}
/** One screening. Its monitor guards every seat and hold decision for the show. */
final class Show {
final String id;
final Map<String, Seat> seats = new LinkedHashMap<>();
final Map<Tier, Long> priceCents;
final Map<String, Hold> holderOf = new HashMap<>(); // seat -> latest hold (may be stale)
final Map<String, String> bookedBy = new HashMap<>(); // seat -> booking id
Show(String id, List<Seat> seats, Map<Tier, Long> priceCents) {
this.id = id; this.priceCents = Map.copyOf(priceCents);
seats.forEach(s -> this.seats.put(s.id(), s));
}
boolean isFree(String seatId, Instant now) {
Hold h = holderOf.get(seatId);
return !bookedBy.containsKey(seatId) && (h == null || !h.isLive(now));
}
}
class BookingException extends RuntimeException { BookingException(String m) { super(m); } }
interface PaymentGateway { void refund(String paymentRef, long amountCents); }
final class BookingService {
static final Duration HOLD_TTL = Duration.ofMinutes(10), PAYMENT_TIMEOUT = Duration.ofMinutes(5);
private final Map<String, Show> shows = new ConcurrentHashMap<>();
private final Map<String, Hold> holds = new ConcurrentHashMap<>();
private final Set<String> refunded = ConcurrentHashMap.newKeySet();
private final AtomicLong seq = new AtomicLong();
private final Clock clock;
private final PaymentGateway gateway;
BookingService(Clock clock, PaymentGateway gateway) { this.clock = clock; this.gateway = gateway; }
void addShow(Show s) { shows.put(s.id, s); }
/** All-or-nothing: either every seat is held for this user, or none is. */
Hold hold(String showId, String userId, List<String> seatIds) {
Show show = shows.get(showId);
if (show == null) throw new BookingException("unknown show");
if (seatIds.isEmpty() || new HashSet<>(seatIds).size() != seatIds.size()) throw new BookingException("bad seat list");
synchronized (show) {
Instant now = clock.instant();
long amount = 0;
for (String id : seatIds) {
Seat seat = show.seats.get(id);
if (seat == null) throw new BookingException("no seat " + id);
if (!show.isFree(id, now)) throw new BookingException("seat " + id + " is taken");
amount += show.priceCents.get(seat.tier());
}
Hold h = new Hold("H" + seq.incrementAndGet(), showId, userId, seatIds, amount, now.plus(HOLD_TTL));
seatIds.forEach(id -> show.holderOf.put(id, h));
holds.put(h.id, h);
return h;
}
}
/** The user is sent to the payment page. The hold now lives until the payment deadline. */
Instant beginPayment(String holdId) {
Hold h = hold(holdId);
synchronized (show(h)) {
if (h.status != HoldStatus.HELD || !h.isLive(clock.instant())) throw new BookingException("hold is no longer valid");
h.status = HoldStatus.PAYING;
h.deadline = clock.instant().plus(PAYMENT_TIMEOUT);
return h.deadline;
}
}
/** Payment webhook. May arrive twice, or after the deadline. Returns the booking, or empty if refunded. */
Optional<Booking> onPaymentSucceeded(String holdId, String paymentRef) {
Hold h = hold(holdId);
Show show = show(h);
synchronized (show) {
if (h.status == HoldStatus.CONFIRMED) return Optional.of(h.booking); // duplicate webhook
if (h.status == HoldStatus.PAYING && h.isLive(clock.instant())) {
Booking b = new Booking("B" + seq.incrementAndGet(), show.id, h.userId, h.seatIds, h.amountCents, paymentRef);
h.seatIds.forEach(id -> { show.bookedBy.put(id, b.id()); show.holderOf.remove(id, h); });
h.status = HoldStatus.CONFIRMED;
h.booking = b;
return Optional.of(b);
}
if (h.status == HoldStatus.PAYING) expire(show, h); // deadline passed
}
if (refunded.add(paymentRef)) gateway.refund(paymentRef, h.amountCents); // outside the lock, once
return Optional.empty();
}
void onPaymentFailed(String holdId) { endIf(holdId, HoldStatus.PAYING, HoldStatus.FAILED); }
void release(String holdId) { endIf(holdId, HoldStatus.HELD, HoldStatus.RELEASED); }
/** Run every few seconds. Frees expired holds and timed-out payments. */
void sweep() {
Instant now = clock.instant();
for (Hold h : holds.values()) {
synchronized (show(h)) {
if ((h.status == HoldStatus.HELD || h.status == HoldStatus.PAYING) && now.isAfter(h.deadline)) expire(show(h), h);
}
}
}
HoldStatus status(String holdId) { synchronized (show(hold(holdId))) { return hold(holdId).status; } }
boolean isFree(String showId, String seatId) {
Show s = shows.get(showId);
synchronized (s) { return s.isFree(seatId, clock.instant()); }
}
private void expire(Show show, Hold h) {
h.status = h.status == HoldStatus.PAYING ? HoldStatus.TIMED_OUT : HoldStatus.EXPIRED;
h.seatIds.forEach(id -> show.holderOf.remove(id, h));
}
private void endIf(String holdId, HoldStatus from, HoldStatus to) {
Hold h = hold(holdId);
Show show = show(h);
synchronized (show) {
if (h.status != from) throw new BookingException("hold is " + h.status);
h.status = to;
h.seatIds.forEach(id -> show.holderOf.remove(id, h));
}
}
private Hold hold(String id) {
Hold h = holds.get(id);
if (h == null) throw new BookingException("unknown hold " + id);
return h;
}
private Show show(Hold h) { return shows.get(h.showId); }
}
final class FakeClock extends Clock {
private volatile Instant now;
FakeClock(Instant start) { now = start; }
void advance(Duration d) { now = now.plus(d); }
public Instant instant() { return now; }
public ZoneId getZone() { return ZoneOffset.UTC; }
public Clock withZone(ZoneId z) { return this; }
}
public class MovieBookingDemo {
static void check(boolean ok, String msg) { if (!ok) throw new AssertionError(msg); }
static boolean fails(Runnable r) { try { r.run(); return false; } catch (BookingException e) { return true; } }
static Show show(String id) {
List<Seat> seats = new ArrayList<>();
for (String row : List.of("A", "B")) for (int n = 1; n <= 8; n++) seats.add(new Seat(row + n, row.equals("A") ? Tier.PREMIUM : Tier.REGULAR));
return new Show(id, seats, Map.of(Tier.REGULAR, 900L, Tier.PREMIUM, 1_400L));
}
public static void main(String[] args) throws Exception {
FakeClock clock = new FakeClock(Instant.parse("2026-11-10T18:00:00Z"));
List<String> refunds = new ArrayList<>();
BookingService svc = new BookingService(clock, (ref, cents) -> refunds.add(ref));
svc.addShow(show("S1"));
// Happy path: hold, pay within the timeout, book.
Hold h = svc.hold("S1", "ann", List.of("A1", "B1"));
check(h.amountCents == 2_300, "1400 + 900");
check(fails(() -> svc.hold("S1", "bob", List.of("B1", "B2"))), "B1 is held, so nothing is held for bob");
check(svc.isFree("S1", "B2"), "all-or-nothing: B2 untouched");
svc.beginPayment(h.id);
check(svc.onPaymentSucceeded(h.id, "pay-1").orElseThrow().seatIds().equals(List.of("A1", "B1")), "booked");
check(svc.onPaymentSucceeded(h.id, "pay-1").isPresent() && refunds.isEmpty(), "duplicate webhook is harmless");
// Hold expiry: the TTL passes before payment starts.
Hold slow = svc.hold("S1", "cat", List.of("A2"));
clock.advance(BookingService.HOLD_TTL.plusSeconds(1));
check(fails(() -> svc.beginPayment(slow.id)), "expired hold can't pay");
check(svc.hold("S1", "dan", List.of("A2")) != null, "seat is free again without any sweep");
// Payment timeout: the webhook arrives after the deadline. Seats are freed and the money returned.
Hold late = svc.hold("S1", "eve", List.of("A3"));
svc.beginPayment(late.id);
clock.advance(BookingService.PAYMENT_TIMEOUT.plusSeconds(1));
svc.sweep();
check(svc.status(late.id) == HoldStatus.TIMED_OUT && svc.isFree("S1", "A3"), "timed out and freed");
check(svc.onPaymentSucceeded(late.id, "pay-2").isEmpty() && refunds.equals(List.of("pay-2")), "late payment refunded");
check(svc.onPaymentSucceeded(late.id, "pay-2").isEmpty() && refunds.size() == 1, "refunded once");
// Declined payment frees the seats at once.
Hold declined = svc.hold("S1", "fay", List.of("A4"));
svc.beginPayment(declined.id);
svc.onPaymentFailed(declined.id);
check(svc.isFree("S1", "A4"), "declined frees");
// Concurrency 1: 32 users want overlapping seats that all include A8. Exactly one wins, all-or-nothing.
for (int round = 0; round < 100; round++) {
BookingService race = new BookingService(clock, (r, c) -> {});
race.addShow(show("S2"));
List<Callable<Hold>> users = new ArrayList<>();
for (int u = 0; u < 32; u++) {
List<String> want = List.of("A8", "B" + (1 + u % 8));
String user = "u" + u;
users.add(() -> race.hold("S2", user, want));
}
List<Hold> won = runTogether(users);
check(won.size() == 1, "exactly one winner, got " + won.size());
for (int n = 1; n <= 8; n++) {
boolean mine = won.get(0).seatIds.contains("B" + n);
check(race.isFree("S2", "B" + n) != mine, "losers hold nothing");
}
}
// Concurrency 2: the payment webhook is delivered 8 times at once. One booking, no refund.
for (int round = 0; round < 100; round++) {
List<String> rs = Collections.synchronizedList(new ArrayList<>());
BookingService dup = new BookingService(clock, (r, c) -> rs.add(r));
dup.addShow(show("S3"));
Hold one = dup.hold("S3", "gus", List.of("A1"));
dup.beginPayment(one.id);
List<Callable<Booking>> hooks = new ArrayList<>();
for (int i = 0; i < 8; i++) hooks.add(() -> dup.onPaymentSucceeded(one.id, "pay-9").orElseThrow());
List<Booking> results = runTogether(hooks);
check(results.size() == 8 && new HashSet<>(results).size() == 1 && rs.isEmpty(), "one booking");
}
System.out.println("movie booking: all checks passed");
}
/** Starts every task at once. Returns the results of the tasks that didn't throw. */
static <T> List<T> runTogether(List<Callable<T>> tasks) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(tasks.size());
CountDownLatch start = new CountDownLatch(1);
List<Future<T>> fs = new ArrayList<>();
for (Callable<T> t : tasks) fs.add(pool.submit(() -> { start.await(); return t.call(); }));
start.countDown();
List<T> ok = new ArrayList<>();
for (Future<T> f : fs) {
try { ok.add(f.get()); } catch (ExecutionException e) { if (!(e.getCause() instanceof BookingException)) throw e; }
}
pool.shutdown();
return ok;
}
}
from __future__ import annotations
import itertools
import threading
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from typing import Callable, Optional
HOLD_TTL = timedelta(minutes=10)
PAYMENT_TIMEOUT = timedelta(minutes=5)
class Tier(Enum):
REGULAR = "REGULAR"
PREMIUM = "PREMIUM"
class HoldStatus(Enum):
HELD = "HELD"
PAYING = "PAYING"
CONFIRMED = "CONFIRMED"
RELEASED = "RELEASED"
EXPIRED = "EXPIRED"
FAILED = "FAILED"
TIMED_OUT = "TIMED_OUT"
@dataclass(frozen=True)
class Seat:
id: str
tier: Tier
@dataclass(frozen=True)
class Booking:
id: str
show_id: str
user_id: str
seat_ids: tuple[str, ...]
amount_cents: int
payment_ref: str
@dataclass(eq=False)
class Hold:
id: str
show_id: str
user_id: str
seat_ids: tuple[str, ...]
amount_cents: int
deadline: datetime
status: HoldStatus = HoldStatus.HELD # guarded by the show's lock
booking: Optional[Booking] = None
def is_live(self, now: datetime) -> bool:
return self.status in (HoldStatus.HELD, HoldStatus.PAYING) and now <= self.deadline
@dataclass(eq=False)
class Show:
id: str
seats: dict[str, Seat]
price_cents: dict[Tier, int]
holder_of: dict[str, Hold] = field(default_factory=dict) # seat -> latest hold, may be stale
booked_by: dict[str, str] = field(default_factory=dict) # seat -> booking id
lock: threading.Lock = field(default_factory=threading.Lock)
def is_free(self, seat_id: str, now: datetime) -> bool:
h = self.holder_of.get(seat_id)
return seat_id not in self.booked_by and (h is None or not h.is_live(now))
def drop(self, hold: Hold) -> None:
for sid in hold.seat_ids:
if self.holder_of.get(sid) is hold:
del self.holder_of[sid]
class BookingError(Exception):
pass
class BookingService:
def __init__(self, clock: Callable[[], datetime], refund: Callable[[str, int], None]):
self._clock, self._refund = clock, refund
self._shows: dict[str, Show] = {}
self._holds: dict[str, Hold] = {}
self._refunded: set[str] = set()
self._refund_lock = threading.Lock()
self._seq = itertools.count(1)
def add_show(self, show: Show) -> None:
self._shows[show.id] = show
def hold(self, show_id: str, user_id: str, seat_ids: list[str]) -> Hold:
show = self._shows.get(show_id)
if show is None or not seat_ids or len(set(seat_ids)) != len(seat_ids):
raise BookingError("bad request")
with show.lock:
now = self._clock()
for sid in seat_ids:
if sid not in show.seats:
raise BookingError(f"no seat {sid}")
if not show.is_free(sid, now):
raise BookingError(f"seat {sid} is taken")
amount = sum(show.price_cents[show.seats[s].tier] for s in seat_ids)
h = Hold(f"H{next(self._seq)}", show_id, user_id, tuple(seat_ids), amount, now + HOLD_TTL)
for sid in seat_ids:
show.holder_of[sid] = h
self._holds[h.id] = h
return h
def begin_payment(self, hold_id: str) -> datetime:
h, show = self._lookup(hold_id)
with show.lock:
now = self._clock()
if h.status is not HoldStatus.HELD or not h.is_live(now):
raise BookingError("hold is no longer valid")
h.status, h.deadline = HoldStatus.PAYING, now + PAYMENT_TIMEOUT
return h.deadline
def on_payment_succeeded(self, hold_id: str, payment_ref: str) -> Optional[Booking]:
h, show = self._lookup(hold_id)
with show.lock:
if h.status is HoldStatus.CONFIRMED:
return h.booking # duplicate webhook
if h.status is HoldStatus.PAYING and h.is_live(self._clock()):
b = Booking(f"B{next(self._seq)}", show.id, h.user_id, h.seat_ids, h.amount_cents, payment_ref)
for sid in h.seat_ids:
show.booked_by[sid] = b.id
show.drop(h)
h.status, h.booking = HoldStatus.CONFIRMED, b
return b
if h.status is HoldStatus.PAYING: # deadline passed
self._expire(show, h)
with self._refund_lock:
first = payment_ref not in self._refunded
self._refunded.add(payment_ref)
if first:
self._refund(payment_ref, h.amount_cents) # outside the show lock, once
return None
def on_payment_failed(self, hold_id: str) -> None:
self._end_if(hold_id, HoldStatus.PAYING, HoldStatus.FAILED)
def release(self, hold_id: str) -> None:
self._end_if(hold_id, HoldStatus.HELD, HoldStatus.RELEASED)
def sweep(self) -> None:
now = self._clock()
for h in list(self._holds.values()):
show = self._shows[h.show_id]
with show.lock:
if h.status in (HoldStatus.HELD, HoldStatus.PAYING) and now > h.deadline:
self._expire(show, h)
def is_free(self, show_id: str, seat_id: str) -> bool:
show = self._shows[show_id]
with show.lock:
return show.is_free(seat_id, self._clock())
def status(self, hold_id: str) -> HoldStatus:
h, show = self._lookup(hold_id)
with show.lock:
return h.status
@staticmethod
def _expire(show: Show, h: Hold) -> None:
h.status = HoldStatus.TIMED_OUT if h.status is HoldStatus.PAYING else HoldStatus.EXPIRED
show.drop(h)
def _end_if(self, hold_id: str, frm: HoldStatus, to: HoldStatus) -> None:
h, show = self._lookup(hold_id)
with show.lock:
if h.status is not frm:
raise BookingError(f"hold is {h.status.value}")
h.status = to
show.drop(h)
def _lookup(self, hold_id: str) -> tuple[Hold, Show]:
h = self._holds.get(hold_id)
if h is None:
raise BookingError(f"unknown hold {hold_id}")
return h, self._shows[h.show_id]
class FakeClock:
def __init__(self, start: datetime):
self.now = start
def __call__(self) -> datetime:
return self.now
def advance(self, delta: timedelta) -> None:
self.now += delta
def make_show(show_id: str) -> Show:
seats = {f"{r}{n}": Seat(f"{r}{n}", Tier.PREMIUM if r == "A" else Tier.REGULAR) for r in "AB" for n in range(1, 9)}
return Show(show_id, seats, {Tier.REGULAR: 900, Tier.PREMIUM: 1_400})
def fails(fn: Callable[[], object]) -> bool:
try:
fn()
return False
except BookingError:
return True
def demo() -> None:
clock = FakeClock(datetime(2026, 11, 10, 18, 0))
refunds: list[str] = []
svc = BookingService(clock, lambda ref, cents: refunds.append(ref))
svc.add_show(make_show("S1"))
h = svc.hold("S1", "ann", ["A1", "B1"])
assert h.amount_cents == 2_300
assert fails(lambda: svc.hold("S1", "bob", ["B1", "B2"])) and svc.is_free("S1", "B2")
svc.begin_payment(h.id)
assert svc.on_payment_succeeded(h.id, "pay-1").seat_ids == ("A1", "B1")
assert svc.on_payment_succeeded(h.id, "pay-1") is not None and refunds == []
slow = svc.hold("S1", "cat", ["A2"])
clock.advance(HOLD_TTL + timedelta(seconds=1))
assert fails(lambda: svc.begin_payment(slow.id))
assert svc.hold("S1", "dan", ["A2"])
late = svc.hold("S1", "eve", ["A3"])
svc.begin_payment(late.id)
clock.advance(PAYMENT_TIMEOUT + timedelta(seconds=1))
svc.sweep()
assert svc.status(late.id) is HoldStatus.TIMED_OUT and svc.is_free("S1", "A3")
assert svc.on_payment_succeeded(late.id, "pay-2") is None and refunds == ["pay-2"]
assert svc.on_payment_succeeded(late.id, "pay-2") is None and refunds == ["pay-2"]
declined = svc.hold("S1", "fay", ["A4"])
svc.begin_payment(declined.id)
svc.on_payment_failed(declined.id)
assert svc.is_free("S1", "A4")
# 32 threads want overlapping seats that all include A8.
for _ in range(30):
race = BookingService(clock, lambda r, c: None)
race.add_show(make_show("S2"))
barrier, won = threading.Barrier(32), []
def user(u: int) -> None:
barrier.wait()
try:
won.append(race.hold("S2", f"u{u}", ["A8", f"B{1 + u % 8}"]))
except BookingError:
pass
threads = [threading.Thread(target=user, args=(u,)) for u in range(32)]
[t.start() for t in threads]
[t.join() for t in threads]
assert len(won) == 1
assert sum(not race.is_free("S2", f"B{n}") for n in range(1, 9)) == 1 # losers hold nothing
print("movie booking: all checks passed")
if __name__ == "__main__":
demo()
const MIN = 60_000;
const HOLD_TTL_MS = 10 * MIN;
const PAYMENT_TIMEOUT_MS = 5 * MIN;
type Tier = "REGULAR" | "PREMIUM";
type HoldStatus = "HELD" | "PAYING" | "CONFIRMED" | "RELEASED" | "EXPIRED" | "FAILED" | "TIMED_OUT";
interface Seat { readonly id: string; readonly tier: Tier }
interface Booking {
readonly id: string; readonly showId: string; readonly userId: string;
readonly seatIds: readonly string[]; readonly amountCents: number; readonly paymentRef: string;
}
class Hold {
status: HoldStatus = "HELD";
booking: Booking | null = null;
constructor(
readonly id: string, readonly showId: string, readonly userId: string,
readonly seatIds: readonly string[], readonly amountCents: number, public deadlineMs: number,
) {}
isLive(nowMs: number): boolean {
return (this.status === "HELD" || this.status === "PAYING") && nowMs <= this.deadlineMs;
}
}
class Show {
readonly holderOf = new Map<string, Hold>(); // seat -> latest hold, may be stale
readonly bookedBy = new Map<string, string>(); // seat -> booking id
constructor(readonly id: string, readonly seats: ReadonlyMap<string, Seat>, readonly priceCents: Record<Tier, number>) {}
isFree(seatId: string, nowMs: number): boolean {
const h = this.holderOf.get(seatId);
return !this.bookedBy.has(seatId) && (!h || !h.isLive(nowMs));
}
drop(h: Hold): void {
for (const id of h.seatIds) if (this.holderOf.get(id) === h) this.holderOf.delete(id);
}
}
class BookingError extends Error {}
class BookingService {
protected readonly shows = new Map<string, Show>();
protected readonly holds = new Map<string, Hold>();
private readonly refunded = new Set<string>();
private seq = 0;
constructor(protected readonly now: () => number, private readonly refund: (ref: string, cents: number) => void) {}
addShow(s: Show): void { this.shows.set(s.id, s); }
/** All-or-nothing, and synchronous: no await between the checks and the writes. */
hold(showId: string, userId: string, seatIds: readonly string[]): Hold {
const show = this.shows.get(showId);
if (!show || seatIds.length === 0 || new Set(seatIds).size !== seatIds.length) throw new BookingError("bad request");
const now = this.now();
let amount = 0;
for (const id of seatIds) {
const seat = show.seats.get(id);
if (!seat) throw new BookingError(`no seat ${id}`);
if (!show.isFree(id, now)) throw new BookingError(`seat ${id} is taken`);
amount += show.priceCents[seat.tier];
}
const h = new Hold(`H${++this.seq}`, showId, userId, seatIds, amount, now + HOLD_TTL_MS);
for (const id of seatIds) show.holderOf.set(id, h);
this.holds.set(h.id, h);
return h;
}
beginPayment(holdId: string): number {
const [h] = this.lookup(holdId);
if (h.status !== "HELD" || !h.isLive(this.now())) throw new BookingError("hold is no longer valid");
h.status = "PAYING";
h.deadlineMs = this.now() + PAYMENT_TIMEOUT_MS;
return h.deadlineMs;
}
onPaymentSucceeded(holdId: string, paymentRef: string): Booking | null {
const [h, show] = this.lookup(holdId);
if (h.status === "CONFIRMED") return h.booking;
if (h.status === "PAYING" && h.isLive(this.now())) {
const b: Booking = { id: `B${++this.seq}`, showId: show.id, userId: h.userId, seatIds: h.seatIds, amountCents: h.amountCents, paymentRef };
for (const id of h.seatIds) show.bookedBy.set(id, b.id);
show.drop(h);
h.status = "CONFIRMED";
h.booking = b;
return b;
}
if (h.status === "PAYING") this.expire(show, h);
if (!this.refunded.has(paymentRef)) { this.refunded.add(paymentRef); this.refund(paymentRef, h.amountCents); }
return null;
}
onPaymentFailed(holdId: string): void { this.endIf(holdId, "PAYING", "FAILED"); }
release(holdId: string): void { this.endIf(holdId, "HELD", "RELEASED"); }
sweep(): void {
const now = this.now();
for (const h of this.holds.values()) {
if ((h.status === "HELD" || h.status === "PAYING") && now > h.deadlineMs) this.expire(this.shows.get(h.showId)!, h);
}
}
isFree(showId: string, seatId: string): boolean { return this.shows.get(showId)!.isFree(seatId, this.now()); }
status(holdId: string): HoldStatus { return this.lookup(holdId)[0].status; }
protected expire(show: Show, h: Hold): void {
h.status = h.status === "PAYING" ? "TIMED_OUT" : "EXPIRED";
show.drop(h);
}
private endIf(holdId: string, from: HoldStatus, to: HoldStatus): void {
const [h, show] = this.lookup(holdId);
if (h.status !== from) throw new BookingError(`hold is ${h.status}`);
h.status = to;
show.drop(h);
}
protected lookup(holdId: string): [Hold, Show] {
const h = this.holds.get(holdId);
if (!h) throw new BookingError(`unknown hold ${holdId}`);
return [h, this.shows.get(h.showId)!];
}
}
// ─── Demo and self-checks ─────────────────────────────────
function check(ok: boolean, msg: string): void { if (!ok) throw new Error(`check failed: ${msg}`); }
function fails(fn: () => unknown): boolean { try { fn(); return false; } catch (e) { return e instanceof BookingError; } }
function makeShow(id: string): Show {
const seats = new Map<string, Seat>();
for (const row of ["A", "B"]) for (let n = 1; n <= 8; n++) seats.set(`${row}${n}`, { id: `${row}${n}`, tier: row === "A" ? "PREMIUM" : "REGULAR" });
return new Show(id, seats, { REGULAR: 900, PREMIUM: 1_400 });
}
async function main(): Promise<void> {
let nowMs = Date.parse("2026-11-10T18:00:00Z");
const refunds: string[] = [];
const svc = new BookingService(() => nowMs, (ref) => refunds.push(ref));
svc.addShow(makeShow("S1"));
const h = svc.hold("S1", "ann", ["A1", "B1"]);
check(h.amountCents === 2_300, "price");
check(fails(() => svc.hold("S1", "bob", ["B1", "B2"])) && svc.isFree("S1", "B2"), "all-or-nothing");
svc.beginPayment(h.id);
check(svc.onPaymentSucceeded(h.id, "pay-1")?.seatIds.join() === "A1,B1", "booked");
check(svc.onPaymentSucceeded(h.id, "pay-1") !== null && refunds.length === 0, "duplicate webhook");
const slow = svc.hold("S1", "cat", ["A2"]);
nowMs += HOLD_TTL_MS + 1_000;
check(fails(() => svc.beginPayment(slow.id)), "expired hold");
svc.hold("S1", "dan", ["A2"]);
const late = svc.hold("S1", "eve", ["A3"]);
svc.beginPayment(late.id);
nowMs += PAYMENT_TIMEOUT_MS + 1_000;
svc.sweep();
check(svc.status(late.id) === "TIMED_OUT" && svc.isFree("S1", "A3"), "timed out");
check(svc.onPaymentSucceeded(late.id, "pay-2") === null && refunds.join() === "pay-2", "late payment refunded");
check(svc.onPaymentSucceeded(late.id, "pay-2") === null && refunds.length === 1, "refunded once");
// 32 async requests, each awaiting a network hop before holding overlapping seats.
const race = new BookingService(() => nowMs, () => {});
race.addShow(makeShow("S2"));
const results = await Promise.all(Array.from({ length: 32 }, async (_, u) => {
await new Promise((r) => setTimeout(r, Math.random() * 3));
return !fails(() => race.hold("S2", `u${u}`, ["A8", `B${1 + (u % 8)}`]));
}));
check(results.filter(Boolean).length === 1, "exactly one winner");
check([1, 2, 3, 4, 5, 6, 7, 8].filter((n) => !race.isFree("S2", `B${n}`)).length === 1, "losers hold nothing");
console.log("movie booking: all checks passed");
}
main().catch((e) => { console.error(e); process.exit(1); });
Three details carry most of the correctness:
holderOf.remove(id, h)in Java (and the identity check indrop) removes a seat's entry only if it still points at this hold. When an expired hold is cleaned up, a newer hold on the same seat survives.beginPaymentmoves the deadline once, from "10 minutes after hold" to "5 minutes after payment started". The user can't refresh the page to keep seats for ever.- The refund is sent after the show lock is released, and the
refundedset makes it happen once per payment reference.
Earlier reference implementation
The first version of this page is kept below. The enums, entity classes and pricing are still useful. The corrections after it explain what the lock management misses.
Core Implementation
Enums and Types
TypeScript:
enum SeatType {
REGULAR = "REGULAR",
PREMIUM = "PREMIUM",
VIP = "VIP",
RECLINER = "RECLINER",
}
enum BookingStatus {
PENDING = "PENDING",
CONFIRMED = "CONFIRMED",
CANCELLED = "CANCELLED",
EXPIRED = "EXPIRED",
}
enum Genre {
ACTION = "ACTION",
COMEDY = "COMEDY",
DRAMA = "DRAMA",
HORROR = "HORROR",
SCIFI = "SCIFI",
THRILLER = "THRILLER",
}
Python:
from enum import Enum
from dataclasses import dataclass, field
from datetime import datetime, timedelta
import uuid
import threading
class SeatType(Enum):
REGULAR = "REGULAR"
PREMIUM = "PREMIUM"
VIP = "VIP"
RECLINER = "RECLINER"
class BookingStatus(Enum):
PENDING = "PENDING"
CONFIRMED = "CONFIRMED"
CANCELLED = "CANCELLED"
EXPIRED = "EXPIRED"
class Genre(Enum):
ACTION = "ACTION"
COMEDY = "COMEDY"
DRAMA = "DRAMA"
HORROR = "HORROR"
SCIFI = "SCIFI"
THRILLER = "THRILLER"
Entity Classes
TypeScript:
class Movie {
constructor(
public readonly id: string,
public readonly title: string,
public readonly genre: Genre,
public readonly language: string,
public readonly durationMinutes: number,
public readonly rating: number = 0
) {}
}
class Seat {
constructor(
public readonly id: string,
public readonly row: string,
public readonly number: number,
public readonly type: SeatType
) {}
}
class Hall {
private seats: Seat[] = [];
constructor(
public readonly id: string,
public readonly name: string
) {}
addSeat(seat: Seat): void {
this.seats.push(seat);
}
getSeats(): Seat[] {
return [...this.seats];
}
get totalCapacity(): number {
return this.seats.length;
}
}
class Theater {
private halls: Hall[] = [];
constructor(
public readonly id: string,
public readonly name: string,
public readonly city: string
) {}
addHall(hall: Hall): void {
this.halls.push(hall);
}
getHalls(): Hall[] {
return [...this.halls];
}
}
Python:
@dataclass
class Movie:
id: str
title: str
genre: Genre
language: str
duration_minutes: int
rating: float = 0.0
@dataclass
class Seat:
id: str
row: str
number: int
type: SeatType
@dataclass
class Hall:
id: str
name: str
seats: list[Seat] = field(default_factory=list)
def add_seat(self, seat: Seat) -> None:
self.seats.append(seat)
@property
def total_capacity(self) -> int:
return len(self.seats)
@dataclass
class Theater:
id: str
name: str
city: str
halls: list[Hall] = field(default_factory=list)
def add_hall(self, hall: Hall) -> None:
self.halls.append(hall)
Pricing Strategy
Pricing uses the Strategy pattern to allow different pricing models per show (weekday vs weekend, standard vs IMAX, etc.).
TypeScript:
interface PricingStrategy {
calculatePrice(seats: Seat[]): number;
}
class StandardPricing implements PricingStrategy {
private basePrice: number;
private convenienceFee: number;
private seatMultipliers: Map<SeatType, number>;
constructor(basePrice: number, convenienceFee: number = 30) {
this.basePrice = basePrice;
this.convenienceFee = convenienceFee;
this.seatMultipliers = new Map([
[SeatType.REGULAR, 1.0],
[SeatType.PREMIUM, 1.5],
[SeatType.VIP, 2.0],
[SeatType.RECLINER, 2.5],
]);
}
calculatePrice(seats: Seat[]): number {
let total = 0;
for (const seat of seats) {
const multiplier = this.seatMultipliers.get(seat.type) ?? 1.0;
total += this.basePrice * multiplier;
}
total += seats.length * this.convenienceFee;
return Math.round(total * 100) / 100;
}
}
class WeekendPricing implements PricingStrategy {
private standardPricing: StandardPricing;
private surchargePercent: number;
constructor(basePrice: number, surchargePercent = 20) {
this.standardPricing = new StandardPricing(basePrice);
this.surchargePercent = surchargePercent;
}
calculatePrice(seats: Seat[]): number {
const base = this.standardPricing.calculatePrice(seats);
return Math.round(base * (1 + this.surchargePercent / 100) * 100) / 100;
}
}
Python:
class PricingStrategy(ABC):
@abstractmethod
def calculate_price(self, seats: list[Seat]) -> float: ...
class StandardPricing(PricingStrategy):
SEAT_MULTIPLIERS = {
SeatType.REGULAR: 1.0,
SeatType.PREMIUM: 1.5,
SeatType.VIP: 2.0,
SeatType.RECLINER: 2.5,
}
def __init__(self, base_price: float, convenience_fee: float = 30.0):
self.base_price = base_price
self.convenience_fee = convenience_fee
def calculate_price(self, seats: list[Seat]) -> float:
total = sum(
self.base_price * self.SEAT_MULTIPLIERS.get(s.type, 1.0)
for s in seats
)
total += len(seats) * self.convenience_fee
return round(total, 2)
class WeekendPricing(PricingStrategy):
def __init__(self, base_price: float, surcharge_percent: float = 20.0):
self._standard = StandardPricing(base_price)
self._surcharge = surcharge_percent
def calculate_price(self, seats: list[Seat]) -> float:
base = self._standard.calculate_price(seats)
return round(base * (1 + self._surcharge / 100), 2)
Show and Seat Lock Management
The seat lock mechanism is the most critical part of this design. When a user selects seats, those seats are temporarily locked for a configurable TTL. If the user does not complete payment within the TTL, the locks expire and seats become available again.
TypeScript:
class SeatLock {
constructor(
public readonly seat: Seat,
public readonly showId: string,
public readonly userId: string,
public readonly expiresAt: Date
) {}
isExpired(): boolean {
return new Date() > this.expiresAt;
}
}
class Show {
private bookedSeats: Set<string> = new Set(); // seat IDs
private seatLocks: Map<string, SeatLock> = new Map(); // seatId -> lock
constructor(
public readonly id: string,
public readonly movie: Movie,
public readonly hall: Hall,
public readonly startTime: Date,
public readonly endTime: Date,
public readonly pricing: PricingStrategy
) {}
getAvailableSeats(): Seat[] {
this.cleanExpiredLocks();
return this.hall.getSeats().filter(
(seat) => !this.bookedSeats.has(seat.id) && !this.seatLocks.has(seat.id)
);
}
lockSeats(seats: Seat[], userId: string, ttlMinutes = 10): boolean {
this.cleanExpiredLocks();
// Check all seats are available
for (const seat of seats) {
if (this.bookedSeats.has(seat.id) || this.seatLocks.has(seat.id)) {
return false;
}
}
// Lock all seats atomically
const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000);
for (const seat of seats) {
this.seatLocks.set(
seat.id,
new SeatLock(seat, this.id, userId, expiresAt)
);
}
return true;
}
confirmBooking(seats: Seat[], userId: string): boolean {
// Verify locks belong to this user
for (const seat of seats) {
const lock = this.seatLocks.get(seat.id);
if (!lock || lock.userId !== userId || lock.isExpired()) {
return false;
}
}
// Confirm: move from locked to booked
for (const seat of seats) {
this.seatLocks.delete(seat.id);
this.bookedSeats.add(seat.id);
}
return true;
}
releaseLocks(seats: Seat[], userId: string): void {
for (const seat of seats) {
const lock = this.seatLocks.get(seat.id);
if (lock && lock.userId === userId) {
this.seatLocks.delete(seat.id);
}
}
}
cancelSeats(seats: Seat[]): void {
for (const seat of seats) {
this.bookedSeats.delete(seat.id);
}
}
private cleanExpiredLocks(): void {
for (const [seatId, lock] of this.seatLocks) {
if (lock.isExpired()) {
this.seatLocks.delete(seatId);
}
}
}
}
Python:
@dataclass
class SeatLock:
seat: Seat
show_id: str
user_id: str
expires_at: datetime
def is_expired(self) -> bool:
return datetime.now() > self.expires_at
class Show:
def __init__(self, id: str, movie: Movie, hall: Hall,
start_time: datetime, end_time: datetime,
pricing: PricingStrategy):
self.id = id
self.movie = movie
self.hall = hall
self.start_time = start_time
self.end_time = end_time
self.pricing = pricing
self._booked_seats: set[str] = set()
self._seat_locks: dict[str, SeatLock] = {}
self._lock = threading.Lock()
def get_available_seats(self) -> list[Seat]:
self._clean_expired_locks()
return [
s for s in self.hall.seats
if s.id not in self._booked_seats and s.id not in self._seat_locks
]
def lock_seats(self, seats: list[Seat], user_id: str,
ttl_minutes: int = 10) -> bool:
with self._lock:
self._clean_expired_locks()
for seat in seats:
if seat.id in self._booked_seats or seat.id in self._seat_locks:
return False
expires_at = datetime.now() + timedelta(minutes=ttl_minutes)
for seat in seats:
self._seat_locks[seat.id] = SeatLock(
seat=seat, show_id=self.id,
user_id=user_id, expires_at=expires_at
)
return True
def confirm_booking(self, seats: list[Seat], user_id: str) -> bool:
with self._lock:
for seat in seats:
lock = self._seat_locks.get(seat.id)
if not lock or lock.user_id != user_id or lock.is_expired():
return False
for seat in seats:
del self._seat_locks[seat.id]
self._booked_seats.add(seat.id)
return True
def release_locks(self, seats: list[Seat], user_id: str) -> None:
with self._lock:
for seat in seats:
lock = self._seat_locks.get(seat.id)
if lock and lock.user_id == user_id:
del self._seat_locks[seat.id]
def cancel_seats(self, seats: list[Seat]) -> None:
with self._lock:
for seat in seats:
self._booked_seats.discard(seat.id)
def _clean_expired_locks(self) -> None:
expired = [sid for sid, lock in self._seat_locks.items() if lock.is_expired()]
for sid in expired:
del self._seat_locks[sid]
Booking Service
TypeScript:
class Booking {
public status: BookingStatus = BookingStatus.PENDING;
public readonly createdAt = new Date();
constructor(
public readonly id: string,
public readonly show: Show,
public readonly seats: Seat[],
public readonly userId: string,
public readonly totalAmount: number
) {}
}
class BookingService {
private bookings: Map<string, Booking> = new Map();
initiateBooking(show: Show, seats: Seat[], userId: string): Booking | null {
// Lock seats
if (!show.lockSeats(seats, userId)) {
return null; // seats unavailable
}
const totalAmount = show.pricing.calculatePrice(seats);
const booking = new Booking(
crypto.randomUUID(),
show,
seats,
userId,
totalAmount
);
this.bookings.set(booking.id, booking);
return booking;
}
confirmBooking(bookingId: string): boolean {
const booking = this.bookings.get(bookingId);
if (!booking || booking.status !== BookingStatus.PENDING) {
return false;
}
if (booking.show.confirmBooking(booking.seats, booking.userId)) {
booking.status = BookingStatus.CONFIRMED;
return true;
}
// Lock expired
booking.status = BookingStatus.EXPIRED;
return false;
}
cancelBooking(bookingId: string): boolean {
const booking = this.bookings.get(bookingId);
if (!booking || booking.status !== BookingStatus.CONFIRMED) {
return false;
}
booking.show.cancelSeats(booking.seats);
booking.status = BookingStatus.CANCELLED;
return true;
}
}
Python:
@dataclass
class Booking:
id: str
show: Show
seats: list[Seat]
user_id: str
total_amount: float
status: BookingStatus = BookingStatus.PENDING
created_at: datetime = field(default_factory=datetime.now)
class BookingService:
def __init__(self):
self._bookings: dict[str, Booking] = {}
def initiate_booking(self, show: Show, seats: list[Seat],
user_id: str) -> Booking | None:
if not show.lock_seats(seats, user_id):
return None
total = show.pricing.calculate_price(seats)
booking = Booking(
id=str(uuid.uuid4()),
show=show,
seats=seats,
user_id=user_id,
total_amount=total
)
self._bookings[booking.id] = booking
return booking
def confirm_booking(self, booking_id: str) -> bool:
booking = self._bookings.get(booking_id)
if not booking or booking.status != BookingStatus.PENDING:
return False
if booking.show.confirm_booking(booking.seats, booking.user_id):
booking.status = BookingStatus.CONFIRMED
return True
booking.status = BookingStatus.EXPIRED
return False
def cancel_booking(self, booking_id: str) -> bool:
booking = self._bookings.get(booking_id)
if not booking or booking.status != BookingStatus.CONFIRMED:
return False
booking.show.cancel_seats(booking.seats)
booking.status = BookingStatus.CANCELLED
return True
Correction (2026-11-10): the Python first-pass code doesn't run as written
PricingStrategy(ABC) uses ABC and abstractmethod, but the imports at the top of the Python enums block don't include them, so running the blocks in order fails with NameError: name 'ABC' is not defined. Add from abc import ABC, abstractmethod.
Correction (2026-11-10): the Python Show reads and cleans up without its lock
get_available_seats calls _clean_expired_locks, which deletes from _seat_locks, without taking self._lock. If another thread is inside lock_seats at the same moment, the dictionary can change size during iteration, which raises a RuntimeError. Every read and write of _seat_locks must happen under the lock. Also, nothing handles a payment that completes after the TTL: confirm_booking just returns False, so a user who has been charged gets no seat and no refund. The complete code adds the PAYING state, the payment deadline and the refund path.
7. Concurrency
| Shared state | Invariant | Mechanism |
|---|---|---|
A show's holderOf and bookedBy | One live hold or one booking per seat | The show's lock (synchronized (show), threading.Lock) |
| A hold's status and deadline | Moves only along legal transitions | The same show lock, so a hold and its seats change together |
The refunded set | One refund per payment reference | Atomic add (a concurrent set, or a short lock) |
| The hold and show registries | Lookups see complete objects | Concurrent maps, written once per object |
Exactly one winner. hold checks every requested seat and then writes every seat, with no gap for another thread between the two. Under the show's lock, a second request for an overlapping seat sees the first hold as live and fails before writing anything. The Java demo runs 32 threads requesting seat sets that all include A8, 100 times, and asserts one winner and that the losers hold nothing.
Webhook racing the sweeper. After the payment deadline, the success webhook and the sweeper may run together. Both take the show lock, and both make the same decision: the hold is past its deadline, so it becomes TIMED_OUT and the payment is refunded. Whichever runs first, the outcome is "no booking, one refund, seat free". The Python test runs this race 50 times.
Duplicate webhooks. Eight concurrent deliveries of the same success produce one booking. The first moves the hold to CONFIRMED, and the rest see CONFIRMED and return the same booking.
Exactly at the deadline. A hold is live up to and including its deadline (!now.isAfter(deadline)). Every check uses the same comparison, so there's no instant at which the seat is both free for a new user and still payable for the old one.
TypeScript has no threads. hold is synchronous, so it's atomic on the event loop. The race reappears if you put an await between the checks and the writes, for example to read seats from a database. In that case the atomic step must move into the database: a conditional UPDATE or a unique constraint, as described in Booking and Inventory Concurrency.
Concurrency: The Double-Booking Problem
sequenceDiagram
participant User1
participant System
participant User2
User1->>System: Select seats [A1, A2]
System->>System: Lock A1, A2 for User1 (TTL=10min)
System-->>User1: Seats locked, proceed to payment
User2->>System: Select seats [A1, A3]
System->>System: A1 is locked!
System-->>User2: Seat A1 unavailable
User1->>System: Complete payment
System->>System: Confirm booking (lock → booked)
System-->>User1: Booking confirmed!
Note over System: If User1 didn't pay within 10 min,<br/>lock would expire and A1<br/>becomes available again
WARNING
The seat locking mechanism must be atomic. If locking multiple seats, either all succeed or none do. A partial lock (where only some seats are locked) leads to inconsistencies and a poor user experience.
8. Extensibility: "the interviewer adds X"
Extension 1: no stranded single seats
"Don't let a group leave one empty seat between taken seats. Nobody buys it." Where: a rule called inside hold, under the show's lock, before the hold is created. Unchanged: the state machine, payment and expiry.
/** Rejects a request that would leave one empty seat stranded next to the seats being taken. */
final class NoOrphanSeatRule {
/** Call inside BookingService.hold, under the show's lock, before creating the Hold. */
static boolean violates(Show show, List<String> wanted, Instant now) {
Set<String> want = new HashSet<>(wanted); // allows contains(null)
Map<Character, List<String>> rows = new TreeMap<>();
for (String id : show.seats.keySet()) rows.computeIfAbsent(id.charAt(0), k -> new ArrayList<>()).add(id);
for (List<String> row : rows.values()) {
for (int i = 0; i < row.size(); i++) {
String id = row.get(i);
if (want.contains(id) || !show.isFree(id, now)) continue; // only empty seats can be orphans
String left = i > 0 ? row.get(i - 1) : null, right = i < row.size() - 1 ? row.get(i + 1) : null;
boolean leftTaken = left == null || want.contains(left) || !show.isFree(left, now);
boolean rightTaken = right == null || want.contains(right) || !show.isFree(right, now);
boolean causedByUs = want.contains(left) || want.contains(right);
if (leftTaken && rightTaken && causedByUs) return true;
}
}
return false;
}
}
Extension 2: a waitlist for sold-out shows
"When a sold-out show gets seats back, tell the next person on the waitlist." Where: a subclass that hooks every path that frees seats (release, decline, expiry), the Observer idea. The notification is a nudge, not a hold: the waiter still has to win the race to book. Giving them a reserved hold instead would be a stronger promise, and it's worth asking which the business wants.
from collections import deque
class WaitlistBookingService(BookingService):
"""Sold out? Join a waitlist. Whenever seats come back, the next waiter hears about it."""
def __init__(self, *args, notify: Callable[[str, str], None], **kwargs):
super().__init__(*args, **kwargs)
self._notify = notify # (user_id, show_id)
self._waitlist: dict[str, deque[str]] = {}
self._wait_lock = threading.Lock()
def join_waitlist(self, show_id: str, user_id: str) -> None:
with self._wait_lock:
self._waitlist.setdefault(show_id, deque()).append(user_id)
# Every path that frees seats ends here.
def release(self, hold_id: str) -> None:
super().release(hold_id)
self._seats_returned(self._holds[hold_id].show_id)
def on_payment_failed(self, hold_id: str) -> None:
super().on_payment_failed(hold_id)
self._seats_returned(self._holds[hold_id].show_id)
def sweep(self) -> None:
before = {h.id for h in self._holds.values() if h.status in (HoldStatus.HELD, HoldStatus.PAYING)}
super().sweep()
for show_id in {self._holds[i].show_id for i in before if not self._holds[i].is_live(self._clock())}:
self._seats_returned(show_id)
def _seats_returned(self, show_id: str) -> None:
with self._wait_lock:
queue = self._waitlist.get(show_id)
user = queue.popleft() if queue else None
if user:
self._notify(user, show_id) # a nudge, not a hold: they still race to book
Extension 3: cancellation with a time-based refund
"Full refund up to 24 hours before the show, half up to 4 hours, nothing after." Where: a cancel method and a refund-policy function, a one-method Strategy. The seats go back on sale immediately.
/** Percent of the price refunded, given how long before the show the booking is cancelled. */
type RefundPolicy = (msBeforeStart: number) => number;
const tieredRefund: RefundPolicy = (ms) => (ms >= 24 * 60 * MIN ? 100 : ms >= 4 * 60 * MIN ? 50 : 0);
class CancellableBookingService extends BookingService {
private readonly cancelled = new Set<string>();
constructor(now: () => number, private readonly payBack: (ref: string, cents: number) => void,
private readonly startMs: (showId: string) => number, private readonly policy: RefundPolicy = tieredRefund) {
super(now, payBack);
}
/** Returns the cents refunded. The seats go back on sale at once. */
cancel(holdId: string): number {
const [h, show] = this.lookup(holdId);
if (h.status !== "CONFIRMED" || !h.booking || this.cancelled.has(h.booking.id)) throw new BookingError("nothing to cancel");
this.cancelled.add(h.booking.id);
for (const id of h.seatIds) show.bookedBy.delete(id);
const cents = Math.floor((h.amountCents * this.policy(this.startMs(show.id) - this.now())) / 100);
if (cents > 0) this.payBack(h.booking.paymentRef, cents);
return cents;
}
}
Each extension ran against the complete code with its own checks.
Extensions to Discuss
- Seat map visualization (2D grid rendering with status colors)
- Waitlist when show is sold out (Observer pattern for notifications)
- Coupon/promo codes (Decorator pattern on PricingStrategy)
- Recurring bookings (season passes)
- Refund policy (time-based: full refund > 24h, 50% > 4h, no refund < 4h)
- Payment integration (Strategy pattern for payment methods)
9. Testing
With an injected clock, every time rule becomes a deterministic test: valid exactly at the deadline and free one microsecond later, payment extending the deadline past the original TTL, a booked seat never freeing on its own. Then test the races with real threads on a barrier, repeated, asserting the outcome (one winner, one refund, seat free) rather than the order. Save the Python code as movie_booking.py to run this suite:
import threading
import unittest
from datetime import datetime, timedelta
from movie_booking import (HOLD_TTL, PAYMENT_TIMEOUT, BookingError, BookingService,
FakeClock, HoldStatus, make_show)
class MovieBookingTest(unittest.TestCase):
def setUp(self):
self.clock = FakeClock(datetime(2026, 11, 10, 18, 0))
self.refunds = []
self.svc = BookingService(self.clock, lambda ref, cents: self.refunds.append((ref, cents)))
self.svc.add_show(make_show("S1"))
def test_hold_is_valid_up_to_and_including_its_deadline(self):
h = self.svc.hold("S1", "ann", ["A1"])
self.clock.advance(HOLD_TTL)
self.assertFalse(self.svc.is_free("S1", "A1"))
self.clock.advance(timedelta(microseconds=1))
self.assertTrue(self.svc.is_free("S1", "A1"))
with self.assertRaises(BookingError):
self.svc.begin_payment(h.id)
def test_release_frees_seats_and_cannot_repeat(self):
h = self.svc.hold("S1", "ann", ["A1", "A2"])
self.svc.release(h.id)
self.assertTrue(self.svc.is_free("S1", "A2"))
with self.assertRaises(BookingError):
self.svc.release(h.id)
def test_starting_payment_extends_the_deadline(self):
h = self.svc.hold("S1", "ann", ["A1"])
self.clock.advance(HOLD_TTL - timedelta(seconds=1))
self.svc.begin_payment(h.id)
self.clock.advance(PAYMENT_TIMEOUT) # past the original TTL, inside the payment window
self.assertIsNotNone(self.svc.on_payment_succeeded(h.id, "p1"))
def test_webhook_racing_the_sweeper_after_the_deadline(self):
for _ in range(50):
refunds = []
svc = BookingService(self.clock, lambda r, c: refunds.append(r))
svc.add_show(make_show("S2"))
h = svc.hold("S2", "ann", ["A1"])
svc.begin_payment(h.id)
self.clock.advance(PAYMENT_TIMEOUT + timedelta(seconds=1))
results = []
hook = threading.Thread(target=lambda: results.append(svc.on_payment_succeeded(h.id, "p1")))
sweeper = threading.Thread(target=svc.sweep)
hook.start(); sweeper.start(); hook.join(); sweeper.join()
self.assertEqual(results, [None]) # never booked
self.assertEqual(refunds, ["p1"]) # refunded exactly once
self.assertIs(svc.status(h.id), HoldStatus.TIMED_OUT)
self.assertTrue(svc.is_free("S2", "A1"))
def test_booked_seat_never_frees_on_its_own(self):
h = self.svc.hold("S1", "ann", ["A1"])
self.svc.begin_payment(h.id)
self.svc.on_payment_succeeded(h.id, "p1")
self.clock.advance(timedelta(days=1))
self.svc.sweep()
self.assertFalse(self.svc.is_free("S1", "A1"))
if __name__ == "__main__":
unittest.main()
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Get available seats | where = total seats | |
| Lock seats | where = selected seats | |
| Confirm booking | ||
| Clean expired locks | where = active locks | |
| Calculate price |
10. Common mistakes
- Check-then-act without a lock: "is A8 free?" followed by "hold A8" as two steps. That's the double-booking bug. Common LLD Mistakes walks through it.
- Partial holds. Locking B1, then failing on A8, and forgetting to undo B1.
- Trusting the sweeper for correctness. If it's late, seats stay blocked. Check expiry lazily on every read.
- Calling the gateway inside the lock.
- No answer for the late payment. "Return false" means the customer is charged and has no ticket.
- Non-idempotent webhooks. Retries create two bookings or two refunds.
Date.now()scattered through the code. The deadline boundaries can't be tested.
11. Interview follow-ups
How does this work across several servers?
Move the atomic step into the database. A seat-hold row per (show, seat) with a unique constraint, and INSERT ... ON CONFLICT DO NOTHING (or UPDATE seat SET hold_id = ? WHERE show = ? AND seat = ? AND (hold_id IS NULL OR hold_expires < now())) for each seat in one transaction. If any seat fails, roll back. Confirming is UPDATE hold SET status = 'CONFIRMED' WHERE id = ? AND status = 'PAYING' AND deadline >= now(), and one changed row means you won. Booking and Inventory Concurrency compares the pessimistic and optimistic versions.
Why not use Redis with a TTL key per seat?
SET seat:S1:A8 H1 NX PX 600000 is a good hold, and it expires on its own. The catch is the payment window: the key must be extended atomically when payment starts, and the booking must still be written durably to the database. Redis then holds the fast-changing holds, and the database holds the bookings. Make sure the confirm step checks that the key still belongs to this hold.
A very popular show opens for sale. What breaks first?
The show lock, because every request for that show serialises on it. Each critical section is microseconds, so a single process copes with thousands of holds a second. Beyond that, put a queue in front of the show (a virtual waiting room) so requests arrive at a rate the lock can serve, rather than splitting the lock.
Should the seat map show held seats as taken?
Yes. Showing them as free invites clicks that will fail. Show them as unavailable, and refresh the map when holds expire. The map is a read, so it can be slightly stale, because the hold call is the real check.
Further Reading
- LLD Interviews Overview — SOLID principles and LLD approach
- Design Hotel Management — similar booking and availability patterns
- Design ATM Machine — State pattern for sequential flows