Design Seat Booking (BookMyShow)
The problem that spans both rounds — seat states, temporary holds that expire, the payment flow, and the exact moment an in-memory answer stops working.
Ask for this one if you get a choice. It's where LLD and HLD meet: the class design is small, but the interesting part — two people, one seat — stays interesting all the way up to a distributed system. It's also the likeliest place to be asked "and now with five servers?", so it's the best rehearsal for that switch.
#1 · Requirements (0–5)
Ask first: how many seats per show — hundreds, or a 100,000-seat stadium? Do we hold seats while the user pays, or is booking one atomic step? One server or several? Assigned seats or general admission?
Assume: cinema-sized shows, hold-then-pay, and "start with one machine, then let's scale it".
What it must do
- Browse cities → cinemas → shows → a seat map showing what's free.
- Select seats and hold them for a few minutes while paying.
- Pay → the hold becomes a booking. Fail or run out of time → the seats go back.
- Cancel a booking, with a refund rule.
Qualities that shape the design
- A seat is sold at most once. This is the rule; everything else is negotiable.
- Holds must expire even if the user closes their laptop mid-checkout.
- The seat map is read far more than it's written and can be a second out of date — but the booking decision itself cannot.
Out of scope: pricing engines, recommendations, the payment provider's internals.
#2 · Classes (5–12)
City · Cinema · Screen the catalogue, rarely changes
Show id, movieId, screenId, startsAt, pricing
Seat id, screenId, row, number, category (physical, permanent)
ShowSeat showId, seatId, status, holderId?, holdExpiresAt?, bookingId?
Hold id, showId, seatIds[], userId, expiresAt
Booking id, showId, seatIds[], userId, Money amount, status, paymentId
Payment bookingId, amount, status, gatewayRef, idempotencyKey
enum SeatStatus { AVAILABLE, HELD, BOOKED }
enum BookingStatus { PENDING, CONFIRMED, CANCELLED, EXPIRED }The decision to narrate:
"
Seatis the physical chair — row F, seat 12 of screen 3. It never changes.ShowSeatis that chair for one particular show, and that's the thing with a status. Putting availability onSeatwould break the moment the same screen has two showings in a day. This split is the whole data model."
#3 · The seat's states (12–18)
hold (expires in 8 min) payment confirmed
AVAILABLE ────────────────────────▶ HELD ─────────────────────▶ BOOKED
▲ │ │
│ released, or expired │ cancelled + refunded │
└──────────────────────────────────┴─────────────────────────────┘
Every arrow is a conditional change:
AVAILABLE → HELD only if it is currently AVAILABLE
HELD → BOOKED only if held by *this* user, and not expired
HELD → AVAILABLE on release, expiry, or failed paymentEverything correctness-related in this problem is that right-hand column: a change happens only if the current state is what you thought it was. That's compare-and-set: check the current value and swap in the new one as a single indivisible step, so if anyone changed it in between, your swap fails instead of overwriting them. It's the same sentence in memory and in SQL.
#4 · Holding a seat, one server (18–26)
class ShowSeat {
private final AtomicReference<SeatState> state =
new AtomicReference<>(SeatState.available());
/** Exactly one of several racing callers gets true. */
boolean tryHold(UserId user, Instant now, Duration ttl) {
SeatState current = state.get();
// taken: booked, or held by a hold that hasn't expired
if (!current.isAvailableAt(now)) return false;
SeatState held = SeatState.heldBy(user, now.plus(ttl));
// fails cleanly if someone changed it first
return state.compareAndSet(current, held);
}
boolean tryConfirm(UserId user, Instant now) {
SeatState current = state.get();
if (!current.isHeldBy(user, now)) return false; // expired, or not yours
return state.compareAndSet(current, SeatState.booked(user));
}
}Notice isAvailableAt(now): an expired hold counts as available. Expiry is judged when the seat is read, rather than depending on a timer having fired. A background sweeper — a job that runs every so often and resets expired holds to AVAILABLE — then exists only to keep the displayed map tidy, not for correctness. Say that distinction out loud; it's the difference between a design that survives a dead scheduler thread and one that doesn't.
#Four seats together, or none
Someone picking four seats side by side must get all four or nothing.
class BookingService {
HoldResult hold(ShowId showId, List<SeatId> requested, UserId user) {
// sorted, so overlapping requests can't deadlock
List<ShowSeat> seats = seatsFor(showId, sorted(requested));
List<ShowSeat> acquired = new ArrayList<>();
for (ShowSeat seat : seats) {
if (seat.tryHold(user, clock.instant(), HOLD_TTL)) {
acquired.add(seat);
} else {
acquired.forEach(ShowSeat::release); // give back what we took
return HoldResult.unavailable(seat.id());
}
}
Hold hold = Hold.create(showId, requested, user,
clock.instant().plus(HOLD_TTL));
holds.save(hold);
return HoldResult.ok(hold);
}
}Two things to say while writing it. Sort the seat IDs, so two people grabbing overlapping seats always take them in the same order and can't deadlock — where Alice holds F12 and waits for F13 while Bob holds F13 and waits for F12, forever. And the rollback loop is a compensating action — undoing earlier steps by hand because there's no transaction spanning them. That's the small-scale version of a saga; see Distributed Transactions.
#5 · Payment, and not charging twice (26–33)
- 1 1 · Hold Flip seats to HELD for 8 minutes. Return a hold id.
- 2 2 · Create booking PENDING, amount worked out, idempotency key issued.
- 3 3 · Pay Charge the card, tagged with that key.
- 4 4 · Confirm HELD → BOOKED for this holder. Booking CONFIRMED.
- 5 5 · Or unwind Failure or timeout → release the seats, booking EXPIRED.
The hold is what makes a slow payment safe: the user gets 8 minutes, and the seats can't vanish underneath them.
An idempotency key is a unique string sent with a payment so that if the same request arrives twice, the provider charges once and returns the original result.
Three failure cases to raise before you're asked:
- The user abandons checkout. The hold expires; the seats are available again next time anyone reads them. No cleanup needed for correctness.
- The payment succeeds but the confirmation doesn't (the server dies between steps 3 and 4). This is the dangerous one: money taken, no seats. The fix is that the payment carries the booking's idempotency key, and a reconciliation job — a scheduled task that compares payments against bookings — either finishes the booking or refunds it if the seats were resold. Say the word "reconciliation"; real systems have one and most candidates never mention it. See Idempotency.
- The user double-clicks Pay. Same key, so the provider charges once and the second call returns the first result.
#6 · Now with five servers (33–40)
This is the switch the interviewer is waiting for. AtomicReference lives in one program's memory. With five servers, each has its own copy of the seat's state, so two servers can each see the seat as free and both sell it. The answer moves down a layer, and the shape is identical:
-- The same compare-and-set, written in SQL.
UPDATE show_seats
SET status = 'HELD', holder_id = :user,
hold_expires_at = :now + interval '8 minutes'
WHERE show_id = :show
AND seat_id = :seat
AND (status = 'AVAILABLE'
-- an expired hold counts as available
OR (status = 'HELD' AND hold_expires_at < :now));
-- Then check how many rows changed. 1 = you got it. 0 = someone else did.Four points, in this order:
- The row is the lock. A single conditional
UPDATEis atomic in any relational database, so you don't need a separate distributed lock — and saying so shows judgement. Wrap the multi-seat case in one transaction, and keep sorting the IDs so rows are always locked in the same order. - Splitting the data is natural. Everything for a show is keyed by show, so split by show. One wildly popular show is a hot spot, but it's bounded by the number of seats. A 300-seat show can only ever have 300 successful bookings, so when 10,000 people pile in, almost all of that traffic is people viewing the seat map — a read storm the cache absorbs, not a write storm on the database.
- Reads and writes take different paths. The seat map comes from a cache that may be a second stale, with a "seats may have gone" note in the UI; the booking write always goes to the real database. Optimistic display, authoritative write. See Caching.
- Expiry at scale. Judging expiry in the
WHEREclause keeps correctness independent of any sweeper. A periodic job then flips expired rows back purely so the cached map and the analytics look right.
#7 · Extensions
"Add a queue for a big on-sale."
"A virtual waiting room. Users get a place in line and are let in at a rate the booking tier can handle. It protects the database from a 100× spike and it's more honest than a spinning wheel — 'you are number 4,120' beats a timeout. That's a pure HLD addition; no class in the booking model changes."
"Different seat categories and dynamic pricing."
"Pricing is a strategy keyed on category and show — the same 'thing that varies' as in every other problem here. Early-bird and surge pricing become new implementations without touching the seat logic."
"Group bookings that must be together."
"That's a rule about which seats to offer: find a run of k free seats in one row. A bitmap per row — one bit per seat, 1 for taken and 0 for free — turns that into scanning for k zero bits in a row, cheap enough to do on every request."
"Cancellations and refunds."
"
BOOKED → CANCELLEDputs the show-seats back to available and issues a refund through the same idempotency-keyed path. How much you refund is a policy — another strategy, based on how close to showtime it is."
#Check yourself
Seat versus ShowSeat?Show answer
What rule governs every seat state change?Show answer
How do holds expire without depending on a timer?Show answer
How do you hold four seats as all-or-nothing?Show answer
Why is the hold the whole design?Show answer
What if payment succeeds but confirmation never happens?Show answer
How does the race answer change with five servers?Show answer
How do reads and writes differ at scale?Show answer
#What to carry forward
- Separate the permanent seat from the per-show seat that carries status.
- Every transition is a conditional change; the same sentence works in memory and SQL.
- Holds are leases judged at read time — no correctness depends on a sweeper.
- Idempotency keys plus reconciliation cover the "charged but not booked" gap.
- Prefer a conditional UPDATE on the row to a distributed lock.