LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 21 OF 42

Design a Movie Ticket Booking System: LLD with Java Code

The BookMyShow-style machine coding question, solved end to end: movies, screens, shows and seats, holding seats for ten minutes, all-or-nothing seat selection, a lock per show so no seat is sold twice, paying outside the lock, expiring holds, pricing as a strategy, and a full Java 17 solution with a 20-thread race.

Patterns usedObserverDecoratorStrategy

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 18

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 272 lines, with a small main() demo. Save it as MovieBooking.java, then run javac MovieBooking.java && java MovieBooking.

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/** Movie ticket booking: hold seats for a few minutes, pay, confirm. No seat is ever sold twice. */
public class MovieBooking {

    // ---------- the model ----------
    enum SeatType { REGULAR, PREMIUM, RECLINER }

    record Seat(String id, SeatType type) {}

    record Screen(String id, List<Seat> seats) {}

    record Movie(String id, String title, int minutes) {}

    record Show(String id, Movie movie, Screen screen, Instant start) {}

    record Hold(String id, String showId, String user, List<Seat> seats, Instant expires) {}

    record Booking(String id, String showId, String user, List<String> seats, long paidCents) {}

    static final class BookingException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        BookingException(String msg) { super(msg); }
    }

    // ---------- strategies ----------
    interface PricingStrategy { long priceCents(Show show, Seat seat); }

    /** Base price per seat type, 25% more on Friday to Sunday. */
    static final class WeekendPricing implements PricingStrategy {
        private final Map<SeatType, Long> base = Map.of(
                SeatType.REGULAR, 20000L, SeatType.PREMIUM, 30000L, SeatType.RECLINER, 50000L);

        @Override
        public long priceCents(Show show, Seat seat) {
            DayOfWeek d = show.start().atZone(ZoneOffset.UTC).getDayOfWeek();
            boolean weekend = d == DayOfWeek.FRIDAY || d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY;
            long p = base.get(seat.type());
            return weekend ? p * 125 / 100 : p;
        }
    }

    interface PaymentGateway { boolean charge(String user, long cents); }

    // ---------- per-show seat inventory ----------
    /** All seat state for one show. One lock per show: a show has a few hundred seats, so waits are tiny. */
    static final class ShowInventory {
        private final Show show;
        private final Map<String, String> heldBy = new HashMap<>();   // seatId -> holdId
        private final Map<String, Hold> holds = new HashMap<>();      // holdId -> hold
        private final Map<String, String> booked = new HashMap<>();   // seatId -> bookingId

        ShowInventory(Show show) { this.show = show; }

        /** All or nothing: either every requested seat is held for this user, or none is. */
        synchronized Hold hold(String user, List<String> seatIds, Instant now, Duration ttl) {
            expire(now);
            Map<String, Seat> byId = new HashMap<>();
            for (Seat s : show.screen().seats()) byId.put(s.id(), s);
            List<Seat> seats = new ArrayList<>();
            for (String id : seatIds) {
                Seat s = byId.get(id);
                if (s == null) throw new BookingException("no seat " + id);
                boolean taken = booked.containsKey(id) || heldBy.containsKey(id);
                if (taken) throw new BookingException(id + " is taken");
                seats.add(s);
            }
            String holdId = UUID.randomUUID().toString();
            Hold h = new Hold(holdId, show.id(), user, List.copyOf(seats), now.plus(ttl));
            holds.put(h.id(), h);
            for (Seat s : seats) heldBy.put(s.id(), h.id());
            return h;
        }

        /** Returns the hold if it is still alive, so the caller can charge outside the lock. */
        synchronized Hold live(String holdId, Instant now) {
            expire(now);
            Hold h = holds.get(holdId);
            if (h == null) throw new BookingException("hold expired or unknown");
            return h;
        }

        synchronized Booking confirm(Hold h, long paidCents, Instant now) {
            expire(now);
            if (holds.remove(h.id()) == null) throw new BookingException("hold expired during payment");
            String bookingId = "B-" + h.id().substring(0, 8);
            List<String> ids = new ArrayList<>();
            for (Seat s : h.seats()) {
                heldBy.remove(s.id());
                booked.put(s.id(), bookingId);
                ids.add(s.id());
            }
            return new Booking(bookingId, show.id(), h.user(), ids, paidCents);
        }

        synchronized void release(String holdId) {
            Hold h = holds.remove(holdId);
            if (h != null) for (Seat s : h.seats()) heldBy.remove(s.id());
        }

        /** Lazy expiry: old holds are dropped whenever anyone touches the show. */
        private void expire(Instant now) {
            holds.values().removeIf(h -> {
                if (h.expires().isAfter(now)) return false;
                for (Seat s : h.seats()) heldBy.remove(s.id());
                return true;
            });
        }

        synchronized long free(Instant now) {
            expire(now);
            return show.screen().seats().size() - heldBy.size() - booked.size();
        }
    }

    // ---------- the service ----------
    private final Map<String, ShowInventory> shows = new ConcurrentHashMap<>();
    private final Map<String, Show> showById = new ConcurrentHashMap<>();
    private final PricingStrategy pricing;
    private final PaymentGateway payments;
    private final Supplier<Instant> clock;
    private final Duration holdFor;

    MovieBooking(PricingStrategy pricing, PaymentGateway payments,
                 Supplier<Instant> clock, Duration holdFor) {
        this.pricing = pricing;
        this.payments = payments;
        this.clock = clock;
        this.holdFor = holdFor;
    }

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

    List<Show> showsFor(String movieId) {
        List<Show> out = new ArrayList<>();
        for (Show s : showById.values()) if (s.movie().id().equals(movieId)) out.add(s);
        out.sort((a, b) -> a.start().compareTo(b.start()));
        return out;
    }

    Hold hold(String user, String showId, List<String> seatIds) {
        return inventory(showId).hold(user, seatIds, clock.get(), holdFor);
    }

    long quote(Hold h) {
        Show show = showById.get(h.showId());
        long total = 0;
        for (Seat s : h.seats()) total += pricing.priceCents(show, s);
        return total;
    }

    /** Check the hold, charge without holding any lock, then confirm. A declined card frees the seats. */
    Booking pay(String holdId, String showId) {
        ShowInventory inv = inventory(showId);
        Hold h = inv.live(holdId, clock.get());
        long cents = quote(h);
        if (!payments.charge(h.user(), cents)) {
            inv.release(holdId);
            throw new BookingException("payment declined");
        }
        return inv.confirm(h, cents, clock.get());
    }

    long freeSeats(String showId) { return inventory(showId).free(clock.get()); }

    private ShowInventory inventory(String showId) {
        return Optional.ofNullable(shows.get(showId))
                .orElseThrow(() -> new BookingException("no show " + showId));
    }

    // ---------- demo ----------
    static Screen screen(String id, int rows, int perRow) {
        List<Seat> seats = new ArrayList<>();
        for (int r = 0; r < rows; r++) {
            SeatType t = r == rows - 1 ? SeatType.RECLINER
                    : r >= rows - 3 ? SeatType.PREMIUM : SeatType.REGULAR;
            for (int c = 1; c <= perRow; c++) seats.add(new Seat((char) ('A' + r) + "" + c, t));
        }
        return new Screen(id, List.copyOf(seats));
    }

    static String rupees(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }

    public static void main(String[] args) throws InterruptedException {
        Instant[] now = { Instant.parse("2026-11-20T18:00:00Z") };   // a Friday
        Map<String, Boolean> cards = new LinkedHashMap<>(Map.of("asha", true, "ravi", true, "meera", false));
        PaymentGateway gateway = (user, cents) -> cards.getOrDefault(user, true);
        MovieBooking app = new MovieBooking(new WeekendPricing(), gateway,
                () -> now[0], Duration.ofMinutes(10));

        Movie movie = new Movie("m1", "Orbit", 142);
        Show evening = new Show("s1", movie, screen("audi-1", 8, 10), Instant.parse("2026-11-20T19:30:00Z"));
        app.addShow(evening);
        System.out.println("Shows for Orbit: " + app.showsFor("m1").size()
                + ", free seats " + app.freeSeats("s1"));

        Hold a = app.hold("asha", "s1", List.of("G4", "G5"));
        System.out.println("asha holds G4 G5, quote " + rupees(app.quote(a)));
        try {
            app.hold("ravi", "s1", List.of("G5", "G6"));
        } catch (BookingException e) {
            System.out.println("ravi: " + e.getMessage() + " (nothing held, all or nothing)");
        }
        Booking b = app.pay(a.id(), "s1");
        System.out.println("asha booked " + b.seats() + ", paid " + rupees(b.paidCents()));

        Hold m = app.hold("meera", "s1", List.of("H1"));
        try {
            app.pay(m.id(), "s1");
        } catch (BookingException e) {
            boolean freeAgain = app.freeSeats("s1") == 78;
            System.out.println("meera: " + e.getMessage() + ", H1 free again: " + freeAgain);
        }

        Hold late = app.hold("ravi", "s1", List.of("C1", "C2"));
        now[0] = now[0].plus(Duration.ofMinutes(11));
        System.out.println("After 11 minutes free seats: " + app.freeSeats("s1"));
        try {
            app.pay(late.id(), "s1");
        } catch (BookingException e) {
            System.out.println("ravi pays late: " + e.getMessage());
        }

        // Race: 20 users try to grab the same two seats at once. Exactly one wins.
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch start = new CountDownLatch(1);
        AtomicInteger wins = new AtomicInteger();
        Collection<String> winners = new ConcurrentHashMap<String, Boolean>().keySet(true);
        for (int i = 0; i < 20; i++) {
            String user = "u" + i;
            pool.submit(() -> {
                try {
                    start.await();
                    Hold h = app.hold(user, "s1", List.of("E5", "E6"));
                    app.pay(h.id(), "s1");
                    wins.incrementAndGet();
                    winners.add(user);
                } catch (BookingException | InterruptedException e) {
                    // lost the race
                }
            });
        }
        start.countDown();
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Race for E5 E6: " + wins.get() + " winner of 20, free seats "
                + app.freeSeats("s1"));
        if (wins.get() != 1 || winners.size() != 1) throw new AssertionError("double booking");
    }
}

Notes

Requirements

Start with scope. Users list the shows for a movie, open the seat map and pick one or more seats. Those seats are held while the user pays. A successful payment confirms a booking. A failed payment, or a user who walks away, must release the seats. Prices depend on the seat type and the day. Many users book at once. Say that refunds, snacks and coupons are out of scope so the interviewer can pull them back in if they care.

Ask the questions that change the code. How long do we hold seats? Ten minutes. If a user asks for four seats and one is gone, do we give them three? No, all or nothing, because families sit together. Is there a limit per booking? Ten seats. Each answer turns into a rule in one class, which is exactly what the interviewer is listening for.

Requirements
  • list shows for a movie
  • show the seat map with states
  • pick one or more seats
  • hold them while the user pays
  • pay, then confirm a booking
  • release seats if payment fails
  • release seats if time runs out
  • price by seat type and day
  • many users at once
  • out of scope: refunds, snacks
Clarify first
  • how long is a hold?
  • ten minutes
  • partial seats if one is gone?
  • no: all or nothing
  • max seats per booking?
  • ten
  • one city or many?
  • many, but one show at a time
  • cancel after paying?
  • out of scope for now

Entities

Underline the nouns. A movie plays as a show, at a time, on a screen, and a screen is a fixed layout of seats with a type: regular, premium or recliner. All of this is static data that rarely changes, so every one of them is an immutable Java record. Theatres and cities are just groupings above the screen; keep them out until a requirement needs them.

Now the part that changes. Seat G5 can be free for the three o'clock show and sold for the seven o'clock show, so seat state cannot live on the seat. It lives in a ShowInventory, one per show, with three maps: which hold owns each held seat, the holds themselves, and which booking owns each sold seat. Free simply means a seat is in neither map.

Static model
enum SeatType { REGULAR, PREMIUM,
               RECLINER }
record Seat(String id, SeatType type)
record Screen(String id, List<Seat> s)
record Movie(String id, String title,
             int minutes)
record Show(String id, Movie movie,
            Screen screen, Instant start)
Seat state per show
  • the same seat is free at 3 pm
  • and sold at 7 pm
  • so state lives per show, not
  • on the Seat record
  • ShowInventory:
  • heldBy: seatId -> holdId
  • holds: holdId -> Hold
  • booked: seatId -> bookingId

Seat lifecycle

Draw the seat lifecycle for one show. A free seat becomes held when a user picks it. A held seat becomes booked when payment succeeds, or free again when payment fails or the ten minutes run out. Booked stays booked. The hold itself is a small record: an id, the user, the seats and an expiry time. Making the hold a first class object is the key idea of the whole design.

A seat for one show
  • FREE
  • -> HELD (user picks it)
  • HELD
  • -> BOOKED (payment succeeds)
  • -> FREE (payment fails)
  • -> FREE (ten minutes pass)
  • BOOKED
  • -> stays booked
  • a Hold is a record with an expiry

Flow: hold seats

The hold flow. First drop any expired holds. Then check every requested seat; if any one is held or booked, throw and change nothing, so the user never ends up with half their seats. Only when all are free do we create the hold with an expiry ten minutes from now and mark each seat as held by it. Check everything, then write everything: that is how all or nothing stays simple.

hold(user, seatIds)
synchronized Hold hold(...) {
  expire(now);
  for (id : seatIds)
    if (booked or held) throw taken
  Hold h = new Hold(id, user, seats,
                    now + 10 min);
  for (seat : seats) heldBy.put(..)
  return h;
}

Concurrency

Now the real question. Asha and Ravi both tap seat G5 at the same instant. Without a lock, both check, both see it free, and both get it. One global lock fixes that but makes every show in every city wait in one line. The right grain is one lock per show: different shows never block each other, and a single show has a few hundred seats, so the time inside the lock is microseconds. Ravi gets a clear seat taken message.

Interviewers often ask why not lock each seat. You can, but watch for deadlock: user one locks A1 then waits for A2 while user two locks A2 and waits for A1. The fix is to always lock seats in sorted order. Another option is compare-and-set on each seat with a rollback if a later seat fails. Both work, but one lock per show is simpler and fast enough, so say that and move on.

Why one lock per show
  • check-then-set without a lock:
  • both see G5 free, both win
  • one global lock: every show
  • in every city waits in line
  • one lock per show:
  • shows never block each other
  • a show has ~300 seats, so
  • the critical section is tiny
Alternative: lock per seat
  • user 1 wants A1 then A2
  • user 2 wants A2 then A1
  • each holds one, waits forever
  • fix: sort seat ids, lock in order
  • or skip locks: compare-and-set
  • each seat, roll back on failure
  • per show is simpler and fast
  • enough: say so, then move on

Strategy: pricing

Pricing is a business policy, so put it behind an interface with one method: the price of this seat for this show. Our default charges by seat type and adds twenty five percent from Friday to Sunday, so two premium seats on a Friday cost seven hundred and fifty. Demand-based surge pricing or a bank offer is another class, and the booking service never changes. Money is a whole number of paise, never a double.

PricingStrategy
interface PricingStrategy {
  long priceCents(Show s, Seat seat);
}

WeekendPricing: base by seat type,
  +25% Friday to Sunday
G4, G5 premium on a Friday:
  2 x 300.00 x 1.25 = 750.00
surge, offers: new classes

Flow: pay

The payment flow has one rule: never call the payment gateway while holding the show lock. A card payment can take seconds, and holding the lock that long would freeze the whole show. So we take the lock briefly to check the hold is alive, release it, charge the card, then take the lock again to confirm. If the card is declined we release the seats right away instead of making others wait ten minutes.

pay(holdId)
Hold h = inv.live(holdId)  // lock
long amount = quote(h)
if (!payments.charge(user, amount)) {
  inv.release(holdId)       // lock
  throw: payment declined
}
return inv.confirm(h, amount) // lock

Expiry

How do held seats come back after ten minutes? You could run a timer per hold, but there is a simpler way: lazy expiry. Every time anyone touches the show, we first drop holds whose expiry has passed. A seat map request, a hold or a confirm all clean up as a side effect. For the seat map to look right with no traffic, a small background sweep every minute is enough.

Lazy expiry
private void expire(Instant now) {
  holds.values().removeIf(h -> {
    if (h.expires().isAfter(now))
      return false;
    free every seat of h;
    return true;
  });
}
called inside hold, live, confirm

Edge cases

Here is the edge case that impresses interviewers. The user starts paying at nine minutes fifty eight seconds and the gateway answers after the hold has expired. Someone else may already hold those seats. Confirm must check the hold again and, if it is gone, fail and refund rather than double book. A common fix is to extend the hold by a minute when payment starts, so this almost never happens.

Paid, but the hold expired
  • user pays at minute 9:58
  • gateway answers at 10:03
  • confirm finds no hold
  • never book seats that may now
  • belong to someone else
  • refund the payment instead
  • (or extend holds on payment
  • start by a minute)
  • tell the user clearly

Concurrency

Walk through every shared field. Seat state for a show is guarded by that show's lock. The map from show id to inventory is a concurrent hash map, so finding a show never blocks. Payments run outside every lock. Hold ids are random, so a guessed id cannot steal someone's seats. Everything else is an immutable record. If you push live seat maps to clients, listeners go in a copy-on-write list.

Thread safety checklist
  • seat state: per-show lock
  • inventories: ConcurrentHashMap
  • keyed by show id
  • payment: outside every lock
  • hold ids: random UUIDs
  • records: immutable, share freely
  • expiry: inside the lock
  • listeners for seat-map pushes:
  • CopyOnWriteArrayList

Extensibility

Now the follow-up changes. Many theatres and cities? Add Theatre and City objects that group screens. Coupons? A pricing decorator. Cancellation? A new booking state and the seats go back to free. Live seat maps? Observers on each show inventory. And at real scale, inventories are sharded by show id across servers, with the database enforcing that a seat for a show is sold once.

Extension points
  • many theatres: a Theatre groups
  • screens, a City groups theatres
  • coupons: a pricing decorator
  • cancel and refund: BOOKED ->
  • CANCELLED, seat back to free
  • waitlist: notify on release
  • live seat map: observers on
  • each ShowInventory
  • scale out: shard inventories
  • by show id across servers

Testing

The full code is below the player. The demo holds two premium seats on a Friday and checks the price, shows that a second user cannot take one of them, declines a card and checks the seat is free again, moves an injected clock forward eleven minutes to expire a hold, and finally starts twenty threads that race for the same two seats. Exactly one booking wins, every run.

Run it
asha holds G4 G5, quote 750.00
ravi: G5 is taken (nothing held)
asha booked [G4, G5], paid 750.00
meera: payment declined, H1 free
After 11 minutes free seats: 78
ravi pays late: hold expired
Race for E5 E6: 1 winner of 20

Say it like this

Here is the short version to say out loud. Movies, shows, screens and seats are immutable records. Seat state lives in one show inventory per show, guarded by its own lock. Seats are held all or nothing for ten minutes and expire lazily. Payment runs outside the lock, and we check the hold again before confirming, so no seat is ever sold twice.

In the interview
  • "Shows, screens and seats are
  • records. Seat state lives in
  • one ShowInventory per show,
  • guarded by its own lock. Seats
  • are held all or nothing for
  • ten minutes and expire lazily.
  • Payment runs outside the lock,
  • then we confirm the hold again."

Interview questions

How do you stop two users from booking the same seat?

All seat changes for a show go through one lock for that show. Inside it the service checks every requested seat and only then marks them held, so exactly one of two racing users wins. Different shows have different locks and never block each other.

Why not store free or booked on the Seat object?

A seat belongs to a screen and is reused by every show on that screen. G5 can be free at 3 pm and sold at 7 pm, so its state must be per show. ShowInventory keeps it in maps keyed by seat id.

Why hold seats before payment instead of booking straight away?

Payment takes time and can fail. A hold reserves the seats for a short window so nobody else takes them mid-payment, and it expires on its own if the user leaves, so seats are never stuck.

Why must the payment call happen outside the lock?

A gateway call can take seconds. Holding the show lock that long would block every other user picking seats for the show. The service checks the hold under the lock, charges with no lock held, then locks again to confirm.

What happens if the hold expires while the payment is in progress?

Confirm checks the hold again and finds it gone, so it fails instead of booking seats that may now belong to someone else, and the payment is refunded. Extending the hold by a minute when payment starts makes this rare.

How do expired holds release their seats without a timer per hold?

Lazy expiry: every operation on a show first removes holds whose expiry time has passed and frees their seats. A small periodic sweep keeps the seat map right for shows nobody is touching.

Would you lock each seat instead of the whole show?

It works if seats are always locked in sorted order, otherwise two users can deadlock waiting for each other. A per-show lock is simpler and the critical section is tiny, so it is the better default.

How does this work across many servers?

Route each show to one owner by show id, or keep holds and bookings in a database with a unique constraint on show id plus seat id, so the database itself rejects a second sale of the same seat.