Design it yourself · Chapter 24

Movie ticket booking

Design a BookMyShow-style booking system: shows and per-show seats, 10-minute holds that expire, no double booking, a safe payment flow, full Java and Python code, and the database version.

AdvancedInterview priority: High55 min
On this page
  1. The problem: two people, one seat
  2. 1. Clarify the requirements
  3. 2. Find the entities
  4. 3. The class design
  5. 4. The payment flow
  6. 5. The code
  7. 6. Concurrency
  8. 7. On a real database
  9. 8. Extensions the interviewer will ask for
  10. When not to over-design
  11. In the interview
  12. Quiz

The problem: two people, one seat

"Design a movie ticket booking system" is really a question about one bug. Two customers open the seat map for the 6 pm show, both see C5 free, and both press "Book". The first attempt looks like this:

Booking book(String user, Show show, String seatId) {
    Seat seat = show.seat(seatId);
    if (seat.isBooked()) throw new SeatTakenException(seatId);   // check
    paymentGateway.charge(user, show.price());                     // slow: 2-5 seconds
    seat.setBooked(true);                                           // act
    return new Booking(user, show, seat);
}

Both requests pass the check before either sets the flag, so both are charged and both get C5. This is a check-then-act race: the decision is made on data that changes before you act on it. The code has two more problems: the seat is not reserved during the seconds the payment takes, and a seat "booked" on the Seat itself is booked for every show on that screen.

The rest of this page builds a design that fixes all three, in interview order: requirements, entities, classes, code, concurrency, the database version, extensions.

1. Clarify the requirements

The requirements, and the one rule that must never break

  1. “Design a movie ticket booking system”, like BookMyShow. Requirements: cinemas have screens; a show is one movie on one screen at one time; customers pick seats, which are held for 10 minutes while they pay; and two people must never get the same seat.
Your turn: scope it

The interviewer says "Design BookMyShow." Write 5–6 questions you would ask, then the agreed requirements and what's out of scope.

Compare with our answer

Questions worth asking: Many cinemas and cities? Can a customer pick specific seats, and how many at once? How long are seats held while paying? Are there seat categories with different prices? What happens if payment succeeds after the hold expires? Cancellations and refunds? One server or many?

A strong answer mentions: a show as movie + screen + time · seat availability per show, not per seat · a time-limited hold while paying · all-or-nothing for several seats · never selling one seat twice · what happens when payment and expiry race · out-of-scope items stated.

The agreed list for this page:

FunctionalDetail
CatalogueCinemas have screens; a screen has seats with a type (REGULAR, PREMIUM)
ShowsA show is one movie on one screen at one start time, with a price per seat type
Seat mapShow which seats are free for a given show
HoldA customer picks 1–6 seats; they are held for 10 minutes, all or none
Pay and confirmPayment within the hold confirms the booking; seats become BOOKED
ExpiryAn unpaid hold expires and its seats become free again
The ruleA seat is never sold twice for the same show, under any timing

Out of scope: search and recommendations, dynamic pricing, coupons, food, refunds after confirmation, notifications. The large-scale version (a million people for one concert) is a system design question: see Design Ticketmaster.

2. Find the entities

The classes fall out of the nouns

  1. The classes fall out of the nouns. A Cinema has Screens, a Screen has Seats. A Show links a Movie to a Screen at a time. A Booking belongs to a customer, for one show, and covers some seats.

The relationships:

  • Composition: a cinema owns its screens; a screen owns its seats. Seats are physical and permanent.
  • Association: a show refers to a movie and a screen; a booking refers to a customer, a show and some seats.
  • Dependency: confirming a booking uses a payment gateway for one call.

The subtle entity: ShowSeat

Availability belongs to a seat for one show

  1. A subtle point: a seat is free or taken for a particular show, not forever. Seat C5 can be sold for the 6 pm show and still free at 9 pm. So availability lives on a ShowSeat: one per seat, per show.

A Seat is a chair: row C, number 5. Whether it's free is a fact about that chair at that show. So the design needs a ShowSeat for every (show, seat) pair, holding the status, which booking holds it, and until when. A 200-seat screen with 5 shows a day has 1,000 ShowSeat rows a day. This is the most common modelling mistake in this question, and naming it early scores points.

3. The class design

Class / typeKindResponsibility
SeatType, SeatStatus, BookingStatusenumsREGULAR/PREMIUM · FREE/HELD/BOOKED · HELD/CONFIRMED/EXPIRED/CANCELLED
Movie, Seat, Screenvalue objectsImmutable catalogue data
ShowentityMovie, screen, start time, prices; owns its ShowSeats and one lock
ShowSeatentityStatus, holding booking id, hold expiry; isFree(now) treats an expired hold as free
BookingentityUser, show, seats, amount (fixed at hold time), expiry, status
PaymentGatewayinterfacecharge(idempotencyKey, cents), refund(...)
BookingServicefacadeavailable, hold, confirm, cancelHold

The booking lifecycle

HELD, then CONFIRMED or EXPIRED

  1. A booking moves through states: HELD while the customer pays, then CONFIRMED, or EXPIRED if 10 minutes pass. Expired holds release their seats so others can buy them.
FromEventTo
(new)hold succeedsHELD
HELDpayment succeeds while the seats are still oursCONFIRMED
HELD10 minutes pass and someone else takes a seat, or a sweeper runsEXPIRED
HELDcustomer abandonsCANCELLED

It's a small state machine; an enum is enough here. If refunds, partial cancellations and exchanges were in scope, the State pattern would earn its place.

Three decisions worth saying out loud:

  • Lazy expiry. A HELD seat whose holdUntil has passed simply counts as free (isFree(now)). Nobody has to run a timer at exactly 10:00 for correctness; a background sweeper can tidy up statuses for the seat map, but the rule holds without it.
  • One lock per show. Every check-and-change for a show's seats happens under that show's lock. Shows never block each other, and a multi-seat hold is all-or-nothing without any lock-ordering puzzle.
  • Time is passed in (hold(..., now)), so expiry can be tested without waiting 10 minutes.

4. The payment flow

Payment is the slow, external step, and it must not happen while holding the lock (a 3-second card call would block every other customer of that show). So confirm does three things in order:

  1. Before paying: refuse if the booking is not HELD or its hold has already expired. A customer is never charged for a hold that's gone.
  2. Pay, outside the lock, with the booking id as the idempotency key (a unique id the payment provider uses to recognise retries), so a double click or a retried request charges once.
  3. Under the lock: confirm only if every seat is still HELD by this booking. If a seat was taken by someone else while the payment ran (the hold expired mid-payment), refund and report the failure.

The third step is what makes the system safe under every timing: payment can succeed late, but a seat can only become BOOKED for the booking that holds it.

5. The code

import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

// ---------- Demo (first, so `java BookingDemo.java` finds main) ----------
public class BookingDemo {
    static Instant at(String hhmm) { return Instant.parse("2026-11-21T" + hhmm + ":00Z"); }

    public static void main(String[] args) throws Exception {
        List<Seat> seats = new ArrayList<>();
        for (char row : "ABC".toCharArray())
            for (int n = 1; n <= 5; n++) seats.add(new Seat("" + row + n, row == 'C' ? SeatType.PREMIUM : SeatType.REGULAR));
        Show show = new Show("S1", new Movie("M1", "Dune: Part Two", 166), new Screen("Screen 1", seats),
                             at("18:00"), Map.of(SeatType.REGULAR, 1200L, SeatType.PREMIUM, 1800L));
        BookingService svc = new BookingService();
        svc.addShow(show);
        FakeGateway pay = new FakeGateway();

        Booking alice = svc.hold("alice", "S1", List.of("C5", "C4"), at("17:00"));
        System.out.println("alice holds " + alice.seatIds + " for " + alice.amountCents + " cents");
        try { svc.hold("bob", "S1", List.of("C5"), at("17:01")); }
        catch (SeatUnavailableException e) { System.out.println("bob: " + e.getMessage()); }
        svc.confirm(alice.id, pay, at("17:03"));
        System.out.println("alice: " + alice.status);

        Booking carol = svc.hold("carol", "S1", List.of("A1"), at("17:05"));    // never pays
        Booking dave = svc.hold("dave", "S1", List.of("A1"), at("17:16"));      // carol's hold has expired
        System.out.println("dave takes A1 after carol's hold expired; carol: " + carol.status);
        try { svc.confirm(carol.id, pay, at("17:17")); }
        catch (IllegalStateException e) { System.out.println("carol: " + e.getMessage() + ", charged: " + pay.charged(carol.id)); }

        // Payment finishes after the hold expired AND someone else took the seat: refund, never double-sell
        Booking erin = svc.hold("erin", "S1", List.of("B1"), at("17:20"));
        pay.duringCharge = () -> svc.hold("frank", "S1", List.of("B1"), at("17:31"));
        try { svc.confirm(erin.id, pay, at("17:29")); }
        catch (IllegalStateException e) { System.out.println("erin: " + e.getMessage() + ", refunded: " + pay.refunded(erin.id)); }
        pay.duringCharge = null;

        // 50 users click B3 at the same instant
        ExecutorService pool = Executors.newFixedThreadPool(16);
        List<Future<Boolean>> fs = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            final String user = "user" + i;
            fs.add(pool.submit(() -> {
                try { svc.hold(user, "S1", List.of("B3"), at("17:40")); return true; }
                catch (SeatUnavailableException e) { return false; }
            }));
        }
        int winners = 0;
        for (Future<Boolean> f : fs) if (f.get()) winners++;
        pool.shutdown();
        System.out.println("50 users race for B3, holds granted: " + winners);
        System.out.println("free seats at 17:41: " + svc.available("S1", at("17:41")).size());
    }
}

// ---------- Values and entities ----------
enum SeatType { REGULAR, PREMIUM }
enum SeatStatus { FREE, HELD, BOOKED }
enum BookingStatus { HELD, CONFIRMED, EXPIRED, CANCELLED }

record Movie(String id, String title, int minutes) {}
record Seat(String id, SeatType type) {}
record Screen(String id, List<Seat> seats) {}

/** Availability of one seat for one show. Guarded by its Show's lock. */
final class ShowSeat {
    final Seat seat;
    SeatStatus status = SeatStatus.FREE;
    String bookingId;
    Instant holdUntil;
    ShowSeat(Seat seat) { this.seat = seat; }
    boolean isFree(Instant now) {             // an expired hold counts as free (lazy expiry)
        return status == SeatStatus.FREE || (status == SeatStatus.HELD && !now.isBefore(holdUntil));
    }
}

final class Show {
    final String id; final Movie movie; final Screen screen; final Instant start;
    final Map<SeatType, Long> prices;
    final Map<String, ShowSeat> seats = new TreeMap<>();
    final Object lock = new Object();          // one lock per show: shows never block each other
    Show(String id, Movie movie, Screen screen, Instant start, Map<SeatType, Long> prices) {
        this.id = id; this.movie = movie; this.screen = screen; this.start = start; this.prices = prices;
        for (Seat s : screen.seats()) seats.put(s.id(), new ShowSeat(s));
    }
}

final class Booking {
    final String id, user, showId; final List<String> seatIds; final long amountCents; final Instant expiresAt;
    volatile BookingStatus status = BookingStatus.HELD;
    Booking(String id, String user, String showId, List<String> seatIds, long amountCents, Instant expiresAt) {
        this.id = id; this.user = user; this.showId = showId; this.seatIds = seatIds;
        this.amountCents = amountCents; this.expiresAt = expiresAt;
    }
}

class SeatUnavailableException extends RuntimeException {
    SeatUnavailableException(String seat) { super(seat + " is not available"); }
}

interface PaymentGateway {
    boolean charge(String idempotencyKey, long cents);   // same key twice = one charge
    void refund(String idempotencyKey, long cents);
}

final class FakeGateway implements PaymentGateway {
    private final Map<String, Long> charges = new ConcurrentHashMap<>(), refunds = new ConcurrentHashMap<>();
    volatile Runnable duringCharge;                        // lets the demo simulate a slow payment
    public boolean charge(String key, long cents) {
        if (duringCharge != null) duringCharge.run();
        charges.putIfAbsent(key, cents);
        return true;
    }
    public void refund(String key, long cents) { refunds.putIfAbsent(key, cents); }
    boolean charged(String key) { return charges.containsKey(key); }
    boolean refunded(String key) { return refunds.containsKey(key); }
}

// ---------- The service ----------
final class BookingService {
    static final Duration HOLD = Duration.ofMinutes(10);
    static final int MAX_SEATS = 6;
    private final Map<String, Show> shows = new ConcurrentHashMap<>();
    private final Map<String, Booking> bookings = new ConcurrentHashMap<>();
    private final AtomicLong seq = new AtomicLong();

    void addShow(Show s) { shows.put(s.id, s); }

    List<String> available(String showId, Instant now) {
        Show show = show(showId);
        synchronized (show.lock) {
            return show.seats.values().stream().filter(s -> s.isFree(now)).map(s -> s.seat.id()).toList();
        }
    }

    /** All or nothing: either every seat is held for this booking, or none is. */
    Booking hold(String user, String showId, List<String> seatIds, Instant now) {
        if (seatIds.isEmpty() || seatIds.size() > MAX_SEATS) throw new IllegalArgumentException("1 to " + MAX_SEATS + " seats");
        Show show = show(showId);
        synchronized (show.lock) {                          // check and take are one step
            List<ShowSeat> wanted = new ArrayList<>();
            for (String id : new TreeSet<>(seatIds)) {
                ShowSeat s = show.seats.get(id);
                if (s == null || !s.isFree(now)) throw new SeatUnavailableException(id);
                wanted.add(s);
            }
            long amount = wanted.stream().mapToLong(s -> show.prices.get(s.seat.type())).sum();  // price fixed at hold time
            Booking b = new Booking("B" + seq.incrementAndGet(), user, showId, List.copyOf(seatIds), amount, now.plus(HOLD));
            for (ShowSeat s : wanted) {
                if (s.status == SeatStatus.HELD) expire(s.bookingId);   // taking over an expired hold
                s.status = SeatStatus.HELD; s.bookingId = b.id; s.holdUntil = b.expiresAt;
            }
            bookings.put(b.id, b);
            return b;
        }
    }

    /** Charge outside the lock, then confirm only if the seats are still held for this booking. */
    Booking confirm(String bookingId, PaymentGateway pay, Instant now) {
        Booking b = booking(bookingId);
        if (b.status == BookingStatus.CONFIRMED) return b;                  // double click: already done
        if (b.status != BookingStatus.HELD || !now.isBefore(b.expiresAt))
            throw new IllegalStateException("hold expired, not charged");
        if (!pay.charge(b.id, b.amountCents)) throw new IllegalStateException("payment declined");
        Show show = show(b.showId);
        synchronized (show.lock) {
            if (b.status == BookingStatus.CONFIRMED) return b;
            boolean stillOurs = b.status == BookingStatus.HELD && b.seatIds.stream()
                .map(show.seats::get).allMatch(s -> s.status == SeatStatus.HELD && b.id.equals(s.bookingId));
            if (stillOurs) {
                for (String id : b.seatIds) show.seats.get(id).status = SeatStatus.BOOKED;
                b.status = BookingStatus.CONFIRMED;
                return b;
            }
        }
        pay.refund(b.id, b.amountCents);                                    // lost the seats while paying
        throw new IllegalStateException("seats were released before payment finished");
    }

    void cancelHold(String bookingId) {
        Booking b = booking(bookingId);
        synchronized (show(b.showId).lock) {
            if (b.status != BookingStatus.HELD) throw new IllegalStateException("not a hold: " + b.status);
            release(b, BookingStatus.CANCELLED);
        }
    }

    // caller holds the show's lock
    private void expire(String bookingId) {
        Booking old = bookings.get(bookingId);
        if (old != null && old.status == BookingStatus.HELD) release(old, BookingStatus.EXPIRED);
    }
    private void release(Booking b, BookingStatus why) {
        Show show = show(b.showId);
        for (String id : b.seatIds) {
            ShowSeat s = show.seats.get(id);
            if (b.id.equals(s.bookingId) && s.status == SeatStatus.HELD) { s.status = SeatStatus.FREE; s.bookingId = null; }
        }
        b.status = why;
    }
    private Show show(String id) { return Optional.ofNullable(shows.get(id)).orElseThrow(() -> new NoSuchElementException("show " + id)); }
    private Booking booking(String id) { return Optional.ofNullable(bookings.get(id)).orElseThrow(() -> new NoSuchElementException("booking " + id)); }
}

Both print:

alice holds [C5, C4] for 3600 cents
bob: C5 is not available
alice: CONFIRMED
dave takes A1 after carol's hold expired; carol: EXPIRED
carol: hold expired, not charged, charged: false
erin: seats were released before payment finished, refunded: true
50 users race for B3, holds granted: 1
free seats at 17:41: 12

What each line shows: two premium seats at 1,800 cents each; a conflicting hold refused; a hold taken over lazily after expiry (carol's 17:05 hold ran out at 17:15, so dave's 17:16 request succeeds and marks her booking EXPIRED); an expired hold that is refused before charging; the payment-versus-expiry race resolved by a refund (erin's payment started at 17:29 and finished after frank took B1 at 17:31); and 50 threads racing for one seat with exactly one winner. Of the 15 seats, C4 and C5 are sold and B3 is held; dave's and frank's holds have lapsed by 17:41, so 12 are free.

6. Concurrency

Check-then-act loses; one atomic step wins

  1. The hardest part is double booking. If the code checks “is C5 free?” and then marks it taken in a second step, two customers can both pass the check in between. Taking the seat must be one atomic step, like a single database update that only succeeds if the seat is still free.
RaceWhat goes wrongFix in the code above
Two customers, one seatBoth pass "is it free?" and both hold itCheck and hold happen under the show's lock as one step
Overlapping multi-seat holds (C4+C5 vs C5+C6)Each gets half; or a deadlock if seats are locked one by one in different ordersOne lock per show; the whole set is checked before any seat changes (all or nothing)
Payment succeeds after the hold expiredThe seat is sold to two peopleConfirm re-checks under the lock that the seats are still held by this booking; otherwise refund
Double click on "Pay"Charged twiceIdempotency key = booking id; a second confirm sees CONFIRMED and returns
Expiry sweeper versus a late confirmSweeper frees seats that are being confirmedBoth run under the show lock, and both check the booking's status first

7. On a real database

The in-memory lock protects one process. Put the service on three servers and each has its own lock, so the database must enforce the rule. There are three standard ways, all covered in depth in Contention and double booking:

Conditional update (atomic compare-and-set): one statement that only succeeds if the seat is still free.

BEGIN;
UPDATE show_seat
   SET status = 'HELD', booking_id = :booking, hold_until = now() + interval '10 minutes'
 WHERE show_id = :show
   AND seat_id IN (:c4, :c5)
   AND (status = 'FREE' OR (status = 'HELD' AND hold_until < now()));
-- rows changed = 2  -> COMMIT: you hold both seats
-- rows changed < 2  -> ROLLBACK: someone was faster; nothing is held

Pessimistic locking: SELECT … FROM show_seat WHERE show_id = ? AND seat_id IN (…) ORDER BY seat_id FOR UPDATE, check the statuses, then update. Locking in a fixed order (by seat id) prevents two multi-seat holds from deadlocking.

Optimistic locking: read the rows with a version column, then UPDATE … SET …, version = version + 1 WHERE id = ? AND version = :read_version. Zero rows means another writer got there first: re-read and retry, or report "seat taken". Best when conflicts are rare (most shows); under heavy contention (a premiere) retries pile up and pessimistic locking or a queue does better.

A unique constraint as the last line of defence: a booked_seat (show_id, seat_id) table with a primary key on both columns. A second confirmed booking for C5 fails on insert even if application code has a bug.

ApproachGood atWeak atUse when
Conditional UPDATE … WHERE status = 'FREE'One round trip; no lock held while thinkingAll-or-nothing needs a row count check and rollbackThe default for seat holds
SELECT … FOR UPDATESimple read-check-write logicHolds row locks; lock order mattersSeveral checks before writing
Optimistic version columnNo locks; scales with low contentionRetries storm on a hot showMost shows, most of the time
Unique constraintGuaranteed by the databaseOnly catches the final insert, not holdsAlways, as a backstop
Redis SET key value NX PX 600000 per seatVery fast holds with built-in expiryA second system to keep consistent with the databaseHuge on-sales (see Ticketmaster)

8. Extensions the interviewer will ask for

  • Seat categories and dynamic pricing: a PricingStrategy per show (weekend, demand-based); the price is fixed in the booking at hold time, so it can't change mid-payment.
  • Cancellations with refunds: CONFIRMED → CANCELLED with a policy (full refund up to 24 hours before); the seats return to FREE; now the booking lifecycle is worth a State pattern.
  • Coupons and offers: a discount step between hold and payment; the coupon's single use is another "only one may win" problem (a conditional update on the coupon).
  • Notifications: Observer, or a BookingConfirmed event published to a queue for email, SMS and analytics.
  • Seat-map updates in real time: push HELD/FREE changes to open seat maps over WebSockets or server-sent events.
  • No single gaps: a rule that refuses holds leaving one isolated empty seat, checked inside hold under the same lock.

When not to over-design

  • General admission (no seat numbers): a counter per show and one conditional decrement (UPDATE show SET left = left - 2 WHERE id = ? AND left >= 2) replaces the whole seat model.
  • Small venues with one server: the in-memory design plus a unique constraint is enough; Redis and queues are for on-sales with huge demand.
  • No payment step (free events): skip holds; book directly with the atomic update.

In the interview

Your turn: spot the bug

A candidate's hold method is below. Find at least three bugs and fix them.

Booking hold(String user, Show show, List<String> seatIds) {
    for (String id : seatIds) {
        ShowSeat s = show.seats.get(id);
        synchronized (s) {
            if (s.status != SeatStatus.FREE) throw new SeatUnavailableException(id);
            s.status = SeatStatus.HELD;
        }
    }
    return new Booking(user, show, seatIds, Instant.now().plus(Duration.ofMinutes(10)));
}
Compare with our answer

The bugs: (1) not all-or-nothing: if the third seat is taken, the first two stay HELD for nobody, for ever; (2) locking seat by seat lets two overlapping group requests each get part of what they wanted; (3) holdUntil and the booking id are never stored on the seat, so the hold can't expire or be confirmed by its owner; (4) an expired HELD seat is treated as taken, so seats leak until something resets them; (5) it reads the system clock inside, which makes expiry untestable.

Booking hold(String user, String showId, List<String> seatIds, Instant now) {
    Show show = show(showId);
    synchronized (show.lock) {                              // the whole request is one atomic step
        List<ShowSeat> wanted = new ArrayList<>();
        for (String id : new TreeSet<>(seatIds)) {
            ShowSeat s = show.seats.get(id);
            if (s == null || !s.isFree(now)) throw new SeatUnavailableException(id);   // nothing changed yet
            wanted.add(s);
        }
        long amount = wanted.stream().mapToLong(s -> show.prices.get(s.seat.type())).sum();
        Booking b = new Booking("B" + seq.incrementAndGet(), user, showId, List.copyOf(seatIds), amount, now.plus(HOLD));
        for (ShowSeat s : wanted) {
            if (s.status == SeatStatus.HELD) expire(s.bookingId);
            s.status = SeatStatus.HELD; s.bookingId = b.id; s.holdUntil = b.expiresAt;
        }
        bookings.put(b.id, b);
        return b;
    }
}

A strong answer mentions: check every seat before changing any (all or nothing) · one lock for the whole request, not per seat · storing the holder and expiry on the seat · treating expired holds as free · passing time in · the database equivalent (one conditional UPDATE with a row-count check).

Your turn: the requirement changes

The cinema chain launches a superhero premiere: 300 seats, 200,000 people trying at 10:00 sharp, on 20 application servers. What breaks in the design above, and what do you change?

Compare with our answer

A strong answer mentions:

  • The in-memory show lock is per process, so with 20 servers the database (or Redis) must decide every hold: a conditional UPDATE … WHERE status = 'FREE' or SET NX PX per seat.
  • All traffic hits one show's rows: a hot partition. A virtual waiting room admits users in batches so only a few thousand are choosing seats at once.
  • Holds in Redis with a 10-minute TTL absorb the burst; the database records only confirmed bookings, with a unique (show, seat) constraint as the backstop.
  • Per-user and per-card hold limits, plus login, against bots.
  • The seat map is served from a cache that may be a few seconds stale; the hold itself is the source of truth and can still say "taken".
  • The payment and idempotency flow stays the same. See Design Ticketmaster.
Movie booking on one page
  • Entities: Cinema ◆ Screen ◆ Seat; Show = movie + screen + time; ShowSeat per (show, seat); Booking; PaymentGateway.
  • Seat status FREE → HELD → BOOKED; booking HELD → CONFIRMED / EXPIRED / CANCELLED.
  • Hold: all or nothing, under one lock per show; price fixed at hold time.
  • Lazy expiry: a HELD seat past holdUntil counts as free; a sweeper only tidies up.
  • Confirm: refuse expired holds before charging · charge outside the lock with idempotency key = booking id · re-check seats are still ours · otherwise refund.
  • Database: conditional UPDATE … WHERE status = 'FREE' with a row-count check, or FOR UPDATE in seat-id order, or optimistic version; unique (show, seat) on bookings.
  • Scale: waiting room, Redis SET NX PX holds, per-user limits; see Ticketmaster and contention lessons.
Interactive labPractise it: sell seats without selling one twiceOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Two customers each try to hold seats for the same show: one wants C4 and C5, the other C5 and C6. The code locks each ShowSeat separately and marks seats HELD one at a time. What can go wrong?

2. A customer starts paying at 18:09. Their hold expires at 18:10, and the payment succeeds at 18:11. Nobody else has taken the seats. What does the design on this page do?

3. Why does the design treat an expired HELD seat as free when checking availability, instead of relying on a timer to reset it?

4. The service runs on three servers sharing PostgreSQL. Which statement best prevents two servers holding the same seat?

5. A customer double-clicks "Pay". Both requests reach confirm. What prevents a double charge?

6. When is optimistic locking (a version column with retries) a poor choice for seat holds?

7. Which part of the model makes it possible to sell seat C5 for both the 6 pm and the 9 pm show?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.