"Design BookMyShow" sounds like a catalogue: cities, cinemas, screens, movies and shows. A weak answer draws all of those, adds a Booking with a list of seats, and stops. The boxes are right, and the part that makes ticket booking hard has not been touched.
The interviewer wants to see what happens around one seat. Two people tap D4 at the same moment, so who gets it? While Asha types her card number, can anyone else take her seats? What happens if she walks away? What if her bank says yes twelve minutes later, after the seats were given to someone else?
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| Is search part of this? | No. We book seats for a show the user has already picked | No search index; a show is found by its id |
| Does the user pick seats? | Yes, specific seats from a seat map | Seats have ids, and the show tracks each one |
| How many seats in one booking? | 1 to 10 | A limit checked before anything is held |
| What happens while the user pays? | Their seats are kept for them for 10 minutes | A hold with a deadline, and a clock we can control |
| Can two people get the same seat? | Never. And a request for three seats gets all three or none | One lock per show, and an all-or-nothing hold |
| How is a seat priced? | By seat category, with an extra on weekends | One interface for pricing, with a rule that wraps another |
| How does payment work? | Through a bank's gateway, which is slow and can fail | An interface for the gateway, called outside any lock |
| What if the bank answers late? | The money goes back and nothing is booked | A refund path, and a list of refunds to retry |
| Do many people book at once? | Yes, on many phones, often for the same show | Every method is safe to call from many threads |
The question about paying matters most. Paying takes time, and the bank is outside our code. Everything about holds, deadlines and refunds follows from the answer.
Requirements
Functional:
- A user picks 1 to 10 seats for a show. The show holds all of them for that user for 10 minutes, or none of them if any is taken.
- While seats are held, nobody else can hold or book them. The seat map shows each seat as free, held or booked.
- The user pays for a hold. If the bank approves before the deadline, the seats are booked. If the bank declines or fails, the seats are given back.
- A hold that reaches its deadline is given up, and its seats are free again. A payment that arrives after that is refunded, and nothing is booked. No hold lasts past the start of the show.
- If the call to the bank fails, the seats are given back, and a job later asks the bank to undo the payment. Money it took is refunded, and a charge it has not made yet is refused.
- The price of each seat depends on its category and the day of the show. The amount charged is the amount shown when the seats were held.
- No seats can be held once the show has started.
Out of scope: search, cancelling a booking, coupons, food, and one user holding many seats across many requests. We come back to these at the end, because each is a natural follow-up, and a design that bends towards them is part of the answer.
Everything lives in memory, as is normal for a low-level design interview. Keeping seats in a database so that many servers can share them is a follow-up at the end.
What the code itself must handle:
- Many users at once.
hold,payandcancelare called from many threads, often on the same show. - A slow and unreliable bank. A payment can take minutes, fail, or arrive after its deadline.
- Time. Deadlines must be testable, so the code takes a
Clockand never reads the system time itself.
Finding the classes
A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.
The noun that needs the most thought is the seat lock. One option is to make it a class, with a seat, a user and an expiry time, and keep a list of them.
Is a seat lock its own class?
A SeatLock object for every held seat
It looks tidy, but a request for three seats becomes three locks that must be created together and released together. A failure in the middle leaves one or two of them behind. Finding whether D4 is free means searching the list.
One hold for the whole request, and a status per seat inside the showOur pick
A SeatHold stands for one request: its seats, its user, its amount and its deadline. The show keeps a map from each held seat to its hold. Holding three seats is one hold and three map entries, written together under one lock, so they cannot come apart.
Data or behaviour?
Some classes only carry data and never change once created: a movie, a screen, a seat, a booking. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.
/** One seat on a screen, such as D4. */public record Seat(String id, SeatCategory category) { public Seat { Objects.requireNonNull(id, "id"); Objects.requireNonNull(category, "category"); if (id.isBlank()) { throw new IllegalArgumentException("A seat needs an id"); } }}Screen is a record too, and it refuses a seat id that appears twice. Booking copies its list of seats, so nobody can change a booking after it is made. SeatHold is a class, not a record, because its status changes as the user pays or walks away.
The class diagram
The classes fall into three groups:
- Data:
Movie,Screen,Seat,Booking,PaymentResult,RefundandPaymentToCheckare records, andSeatCategory,HoldStatusandSeatStatusare enums. - The core:
BookingService,ShowandSeatHold. They hold the state that changes and keep it correct under many threads. - Rules and outside systems:
PricingRulewith its two implementations, andPaymentGateway. The core depends on these interfaces and never on a particular bank.
The rest of the article builds these one at a time.
Building it
A show and its seats
A Seat belongs to a screen, and the same screen runs many shows a day. So a seat cannot carry "free" or "taken" itself. The state belongs to the show:
public final class Show { private final String id; private final Movie movie; private final Screen screen; private final ZonedDateTime startsAt; private final PricingRule pricing; private final Map<String, Seat> seatsById = new LinkedHashMap<>(); // A private lock, so code outside the show cannot hold it. private final Object lock = new Object(); // Guarded by lock. A seat in neither map is free. private final Map<String, SeatHold> heldBy = new HashMap<>(); private final Map<String, String> bookedBy = new HashMap<>(); // Guarded by lock. Holds that still keep their seats: ACTIVE or PAYING. private final Map<String, SeatHold> liveHolds = new LinkedHashMap<>();heldBy maps a held seat to its hold, and bookedBy maps a booked seat to its booking id. A seat in neither map is free. liveHolds lists the holds that still keep seats, so the show can find the ones whose time is up. All three maps are guarded by lock, a private object, so code outside the show cannot hold it and stall every user.
Holding seats: all or none
When Asha asks for D3 and D4, the show checks every seat first and changes nothing until all of them have passed:
/** Holds every seat asked for, or none of them. A hold never lasts past the start of the show. */ SeatHold hold(LongSupplier nextId, String userId, String paymentKey, List<String> seatIds, long amountCents, Clock clock, Duration holdTime) { synchronized (lock) { Instant now = clock.instant(); Instant start = startsAt.toInstant(); if (!now.isBefore(start)) { throw new BookingClosedException(id); } expire(now); List<String> taken = new ArrayList<>(); for (String seatId : seatIds) { if (heldBy.containsKey(seatId) || bookedBy.containsKey(seatId)) { taken.add(seatId); } } if (!taken.isEmpty()) { throw new SeatsUnavailableException(taken); } Instant deadline = now.plus(holdTime); if (deadline.isAfter(start)) { deadline = start; } // The id is taken only now, so a refused request uses none. SeatHold hold = new SeatHold("H-" + nextId.getAsLong(), id, userId, paymentKey, seatIds, amountCents, deadline); for (String seatId : seatIds) { heldBy.put(seatId, hold); } liveHolds.put(hold.id(), hold); return hold; } }The method reads the clock after it has the lock, refuses a show that has started, and expires old holds. The loop then collects every seat that is held or booked. If the list is not empty, the method throws SeatsUnavailableException naming those seats, and nothing has been written. Only then does it work out the deadline, create the hold and point each seat at it. The deadline is 10 minutes away, or the start of the show if that comes first, so no hold outlasts the show. The check and the writes sit inside one synchronized (lock) block, so no other request can slip in between them.
If one seat of three is taken, what does the user get?
The seats that are free
It sounds generous, but a family of three who asked for seats together gets two, and has to decide on the spot whether to keep them. The seats it did get are held from someone else in the meantime.
All or none, and the refusal names the taken seatsOur pick
The user asked for a group of seats, and the answer is about that group. The refusal says which seats are taken, so the seat map can show them and the user can pick again. Nothing is held for a request that failed.
BookingService.hold does the checks that need no lock before it calls the show:
/** Keeps the seats for this user for holdTime, or until the show starts. Every seat, or none. */ public SeatHold hold(String showId, String userId, List<String> seatIds) { Objects.requireNonNull(userId, "userId"); Show show = show(showId); List<String> seats = List.copyOf(seatIds); if (seats.isEmpty() || seats.size() > MAX_SEATS_PER_HOLD) { throw new IllegalArgumentException("Pick 1 to " + MAX_SEATS_PER_HOLD + " seats, not " + seats.size()); } if (new HashSet<>(seats).size() != seats.size()) { throw new IllegalArgumentException("A seat is listed twice in " + seats); } // The price is fixed now, so the amount paid is the amount the user was shown. long amount = show.priceOf(seats); String paymentKey = UUID.randomUUID().toString(); SeatHold hold = show.hold(holdCounter::incrementAndGet, userId, paymentKey, seats, amount, clock, holdTime); holds.put(hold.id(), hold); return hold; }It refuses an empty request, more than 10 seats and a seat listed twice. It works out the price, makes a random payment key, and hands the show the clock and a counter for the hold id. The show takes an id only after the seats pass, so a refused request uses none, and the ids in the demo run without gaps.
There are two kinds of error, and each one says what it is for. SeatsUnavailableException, HoldNotActiveException, PaymentFailedException and BookingClosedException are messages for a person: someone else got the seat, or the time ran out. IllegalArgumentException and NullPointerException are for a programmer: the screen sent 11 seats or a seat that does not exist, which a working app never does. So are ArithmeticException, for a total too big for a long, and IllegalStateException, for a pricing rule that returns zero or less.
Prices
A seat's price depends on its category and the day of the show, and a cinema changes its prices more often than its seats. So the show asks an interface:
/** Works out the price of one seat at one show, in cents. A price is always above zero. */public interface PricingRule { /** startsAt is in the cinema's own time zone, so "Saturday" means Saturday there. */ long priceCents(SeatCategory category, ZonedDateTime startsAt);}The weekend extra is not a new set of prices. It is the normal price with something added:
public final class WeekendPricing implements PricingRule { private final PricingRule base; private final int extraPercent; public WeekendPricing(PricingRule base, int extraPercent) { this.base = Objects.requireNonNull(base, "base"); if (extraPercent < 0 || extraPercent > 100) { throw new IllegalArgumentException("The weekend extra must be 0 to 100 percent, not " + extraPercent); } this.extraPercent = extraPercent; } @Override public long priceCents(SeatCategory category, ZonedDateTime startsAt) { long price = base.priceCents(category, startsAt); DayOfWeek day = startsAt.getDayOfWeek(); if (day != DayOfWeek.SATURDAY && day != DayOfWeek.SUNDAY) { return price; } // Rounded down to the cent. return Math.multiplyExact(price, 100 + extraPercent) / 100; }Math.multiplyExact throws on overflow instead of wrapping round to a negative price, and the division rounds down to the cent. Show.priceOf adds the seats with Math.addExact and refuses a price of zero or less from a rule with a bug. Every amount is a long of cents, never a double. A show's start is a ZonedDateTime in the cinema's own time zone, so "Saturday" means Saturday in that city, whatever zone the server runs in. Deadlines are Instants, which have no zone at all.
When is the price fixed?
Work it out again when the user pays
The price would always follow the latest rule. But a user who saw $30 could be charged $36 if a rule changed while they typed their card number, which is a complaint and a support call.
Work it out when the seats are held, and keep it on the holdOur pick
hold stores the amount on the SeatHold, and pay charges exactly that. The user pays the price they were shown. The pricing rule runs before the lock is taken, because it only does arithmetic and needs no seat state.
Holds that run out
A hold keeps its seats for 10 minutes. A hold moves through a small set of states, kept in the HoldStatus enum:
Something has to notice when a deadline passes. The show does it at the start of every call that touches seats:
// Called with the lock held. A hold expires at its deadline, even while it is being paid. private int expire(Instant now) { int expired = 0; Iterator<SeatHold> it = liveHolds.values().iterator(); while (it.hasNext()) { SeatHold hold = it.next(); if (!now.isBefore(hold.expiresAt())) { it.remove(); free(hold, HoldStatus.EXPIRED); expired++; } } return expired; }expire walks the live holds and gives up every one whose deadline has come. The check is !now.isBefore(hold.expiresAt()), so a hold made at 10:00 is gone at exactly 10:10, not a moment after. hold, startPayment, confirm, cancel and seatMap each call expire first, inside the lock.
Who frees a hold whose time is up?
A timer for every hold
Each hold schedules its own release. A busy show then has thousands of timers, a timer that fires late leaves seats held, and tests have to wait for real time to pass.
A background job that sweeps every few seconds, and nothing else
It is simple, but between two sweeps a seat whose hold has expired still looks taken. A user who asks for it in that gap is refused for no reason.
Every call expires old holds first, and a job may sweep as wellOur pick
Because hold, pay, cancel and seatMap each expire old holds first, no request is refused because of a hold that has run out, and the seat map never shows one. BookingService.expireHolds exists for a timer to call now and then, so a quiet show frees its seats too. Time comes from the injected Clock, so tests move it forward by exactly 10 minutes.
Paying
Paying is three steps, and only the first and last hold the show's lock:
/** Charges the user and books the seats. The gateway is called with no lock held. */ public Booking pay(String holdId) { SeatHold hold = findHold(holdId); Show show = show(hold.showId()); show.startPayment(hold, clock); PaymentResult result = null; try { result = Objects.requireNonNull(gateway.charge(hold.userId(), hold.amountCents(), hold.paymentKey()), "payment result"); } finally { if (result == null) { // No answer, whatever was thrown: the bank may have taken the money, so a job undoes the key later. show.paymentFailed(hold); paymentsToCheck.add(new PaymentToCheck(hold.id(), hold.paymentKey(), hold.amountCents())); } } if (!result.approved()) { show.paymentFailed(hold); throw new PaymentFailedException(hold.id(), result.message()); } Optional<Booking> booking = show.confirm(hold, bookingCounter::incrementAndGet, result.reference(), clock); if (booking.isPresent()) { return booking.get(); } // The hold expired while the bank was working, and its seats may already be someone else's. refund(hold.id(), result.reference(), hold.amountCents()); throw new PaymentFailedException(hold.id(), "the hold expired before the payment arrived, so it is refunded"); }First, startPayment checks that the hold is still ACTIVE and marks it PAYING, under the lock. A second tap on Pay, or a cancel while the bank works, now finds PAYING and is refused, so a hold cannot be paid twice at once. Second, the service calls the gateway with no lock held. Third, confirm takes the lock again and, if the hold is still PAYING, moves its seats from heldBy to bookedBy.
The gateway is given the hold's payment key, not its hold id. Hold ids such as H-1 are for people, and they start again after a restart or on a second server. The payment key is a random UUID, so it never repeats, and the bank can never mix up two holds:
/** The bank or card network. It is outside our code, it is slow, and it can fail. */public interface PaymentGateway { /** Charges the user. The same key on a retry must not charge twice. */ PaymentResult charge(String userId, long amountCents, String key); /** * Undoes the charge made with this key: refunds it if it was made, or * blocks the key if it was not, so a charge that arrives later is refused. */ Reversal reverse(String key, long amountCents); /** Gives the money back. Refunding the same reference twice gives it back once. */ void refund(String reference, long amountCents);}The key does two jobs. If the same charge ever reaches the bank twice, the bank charges once. And if we never hear back about a charge, the key is how we ask the bank to undo exactly that one.
Should the lock be held while the bank works?
Yes, hold the show's lock for the whole payment
It is simple to reason about, because nothing changes while the bank works. But a payment takes seconds, sometimes minutes, and the lock covers the whole show. Every other user of that show would wait for one person's bank.
No: mark the hold as PAYING, call the bank, then take the lock againOur pick
The lock is held for a few map operations at a time. The PAYING status does the job the long lock would have done: it stops a second payment or a cancel. The price is one more case to handle, because the hold can reach its deadline while the bank works.
When the bank says no, the seats go back at once through paymentFailed, and the user sees the bank's reason.
An exception from the gateway is different. A timeout can arrive after the bank has taken the money, so we do not know what happened. If we treated it as a decline, the user would hold the seats again and pay on a new hold, and the first charge would never be given back. So pay checks, in a finally block, whether it got an answer. If it did not, whatever was thrown, it gives the seats back, adds the payment to paymentsToCheck, and lets the bank's own exception carry on unchanged. A gateway that answers null counts as no answer.
/** * For a job: asks the bank to undo every payment whose outcome we did not * learn. A refund or a blocked key settles it; PENDING keeps it for the * next run. Returns how many it settled. */ public int checkPayments() { int settled = 0; for (int n = paymentsToCheck.size(); n > 0; n--) { PaymentToCheck payment = paymentsToCheck.poll(); if (payment == null) { break; } try { Reversal answer = Objects.requireNonNull(gateway.reverse(payment.paymentKey(), payment.amountCents()), "reversal"); if (answer == Reversal.PENDING) { paymentsToCheck.add(payment); } else { settled++; } } catch (RuntimeException e) { paymentsToCheck.add(payment); } } return settled; }A job calls checkPayments now and then. For each payment it asks the gateway to reverse the key. If the bank made the charge, it refunds it. If it did not, it blocks the key, so a charge that is still on its way is refused when it arrives. If the bank is still working on the charge, it answers PENDING, and the payment stays in the queue for the next run, as it does when the bank cannot be reached.
The call to the bank failed. What happened to the money?
Treat it as a decline
It is simple, and the user can try again at once. But a timeout often comes after the bank has charged the card. The user pays again on a new hold, and the first charge is never given back.
Retry the charge inside pay, with the same key
The key makes a retry safe, so the bank charges once. But the user waits through every retry, and a bank that is down stays down. pay still needs an answer for the last failure.
Give the seats back now, and ask the bank about the key laterOur pick
The user is not kept waiting, and the seats are not stuck. A job asks the bank to reverse the key: refund the charge if it was made, or block the key so that it can never be charged. The cost is a second gateway method, reverse, which the bank must offer, and a job to run it.
After a declined card, keep the hold or give it up?
Keep it until its deadline, so the user can try another card
It is kinder to a user with two cards. But the hold has to go back from PAYING to ACTIVE, and a user who has given up still blocks the seats for the rest of the 10 minutes.
Give the seats back at onceOur pick
The seats return to the seat map for the next person straight away. A user who wants to try another card holds the seats again, which works whenever nobody has taken them in the meantime. Keeping the hold is a reasonable answer too, and it is a small change to paymentFailed.
Giving seats back
Apart from a deadline passing, seats go back in two ways before a payment succeeds. The user can cancel, or the payment can fail:
/** * The user gives the seats back. Returns whether this call freed them: a * second tap on Cancel is an answer, not an error. A hold being paid is * refused, because the bank may already be moving the money. */ boolean cancel(SeatHold hold, Clock clock) { synchronized (lock) { expire(clock.instant()); if (hold.status() == HoldStatus.PAYING) { throw new HoldNotActiveException(hold.id(), "being paid"); } if (hold.status() != HoldStatus.ACTIVE) { return false; } free(hold, HoldStatus.RELEASED); return true; } } /** Gives the seats back after a payment fails, unless the hold has already ended. */ void paymentFailed(SeatHold hold) { synchronized (lock) { if (hold.status() == HoldStatus.PAYING) { free(hold, HoldStatus.RELEASED); } } }cancel throws an exception for a hold that is being paid, because the user asked for something that cannot be done: the bank may already be moving the money. It returns false for a hold that has already ended, because a second tap on Cancel is an answer, not a mistake. Returning true or false says whether this call freed the seats. paymentFailed gives the seats back only if the hold is still PAYING, and does nothing otherwise.
That last check matters more than it looks. Suppose Dev's card is declined, but the decline arrives after his deadline, and Tara has held his seat in the meantime. Without the check, paymentFailed would free the seat again and take it from Tara. With it, the late decline finds Dev's hold EXPIRED and changes nothing. The same rule protects confirm: a hold that is no longer PAYING can neither book seats nor free them.
The seat map
The seat map is the screen a user picks from, so it must agree with the holds:
/** Every seat and its status, in the order of the screen's seat map. */ Map<String, SeatStatus> seatMap(Clock clock) { synchronized (lock) { expire(clock.instant()); Map<String, SeatStatus> map = new LinkedHashMap<>(); for (String seatId : seatsById.keySet()) { if (bookedBy.containsKey(seatId)) { map.put(seatId, SeatStatus.BOOKED); } else if (heldBy.containsKey(seatId)) { map.put(seatId, SeatStatus.HELD); } else { map.put(seatId, SeatStatus.FREE); } } return map; } }It expires old holds first, then reads every seat in the order the screen lists them, which is the order the app draws them in. A booked seat shows as BOOKED, a seat in heldBy as HELD, and the rest as FREE. The map is a copy made under the lock, so the app can draw it while other users keep booking.
A payment that arrives too late
The hold has a deadline, and the bank does not know about it. In the demo, Dev holds A1 at 10:11 with a deadline of 10:21, and his bank takes 12 minutes to approve.
confirm calls expire first. If the deadline has passed, the hold is no longer PAYING, and confirm returns an empty Optional. pay then refunds the payment by its reference and throws PaymentFailedException, so the user is told what happened.
Can a hold expire while it is being paid?
No: a PAYING hold keeps its seats until the bank answers
Late payments never happen. But if the bank hangs, or the phone loses its connection after startPayment, the seats stay held with no end. A gateway outage would empty every show.
Yes, at its deadline, and a late approval is refundedOur pick
The deadline means the same thing in every state, so no seat stays held past it. The cost is a refund now and then, and a user who is told "too late" after the bank said yes. The deadline can include enough time for a normal payment, so this stays rare.
The service keeps the holds it has handed out in its holds map, so a late call about an old hold gets a clear answer instead of "no such hold". expireHolds forgets an ended hold one day after its deadline, and a show one day after it started, so neither map grows for ever.
A refund calls the bank too, and the bank can fail again. If gateway.refund throws, pay adds a Refund to refundsToRetry and still throws the PaymentFailedException, so the refund's own failure never replaces the user's answer. A job calls retryRefunds, which takes each refund off the queue, sends it, and puts it back only if the bank fails again. The gateway promises that refunding the same reference twice gives the money back once, so a refund that went through but whose answer was lost can be sent again safely.
Many users, one show
When a show opens for booking, many people ask for the best seats at the same moment.
Each show has its own lock, and every method that reads or changes the show's seats takes it. Each one reads the clock only after it has the lock, so a request that waited for the lock judges deadlines by the moment it acts, not the moment it arrived. The lock is held only for map lookups and writes. Pricing happens before it is taken, and the bank is called with it released, so the only outside call under the lock is the clock read.
The project includes a check, demo/RaceCheck.java. It runs 2,000 rounds. In each round, 16 users ask for two to four seats next to each other in the same row of 8, at the same moment. Each user who gets seats then pays, cancels or walks away, and the bank declines one payment in five. Another thread moves the clock forward all the while.
2,000 rounds. In each, 16 users ask for overlapping seats in one row of 8 at the same moment Holds granted: 4,651. Refused because a seat was taken: 27,349 Rounds where two live holds shared a seat: 0 Bookings: 1,257, covering 3,357 seats Seats sold twice: 0 The seat maps agree with the bookings: true Seats still held after every deadline passed: 0
No two live holds shared a seat, no seat was sold twice, and every booked seat on the seat maps belongs to exactly one booking. We also ran the same check with the lock removed from Show.hold. Every run we tried crashed with a ConcurrentModificationException, because one thread changed the list of live holds while another was walking it. When we caught that crash and carried on, every run gave the same seat to two users in some rounds, and some seats were sold twice. The exact numbers change from run to run, and none of it shows up when one person tests the app alone.
Where does the lock go?
One lock for the whole app
It is correct and simple. But a user booking a Tuesday matinee in Pune would wait for every user booking any other show in the country. Nothing in one show depends on another.
A ConcurrentHashMap of seats, with putIfAbsent for each seat
Each seat is safe on its own. But a request for three seats is three separate steps. If the third seat is taken, the first two must be undone, and in between another user sees them taken and is refused for no reason.
A lock for each seat, taken in seat order
All or nothing works, and two requests for different seats never wait. But every request takes up to 10 locks, always in the same order to avoid deadlock, and the seat map and the expiry sweep need all of them. The gain is small, because the show's lock is held only for a few map operations.
One lock per showOur pick
Everything that must stay consistent, the seats of one show, sits under one lock. A request for several seats is checked and written in one step. Users of different shows never wait for each other, and the lock is held only for a few map operations.
The final design
BookingService runs every step, keeps the holds it hands out, and reaches the bank only through PaymentGateway. Each Show owns its seat maps and the one lock that guards them, and it reaches prices only through PricingRule.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Is a seat lock its own class? | One hold for the whole request, and a status per seat inside the show | One hold and its map entries are written together under one lock, so they cannot come apart |
| 2 | If one seat of three is taken, what does the user get? | All or none, and the refusal names the taken seats | The user asked for a group, and nothing is held for a request that failed |
| 3 | When is the price fixed? | Work it out when the seats are held, and keep it on the hold | The user pays the price they were shown |
| 4 | Who frees a hold whose time is up? | Every call expires old holds first, and a job may sweep as well | No request is refused because of a hold that has run out |
| 5 | Should the lock be held while the bank works? | No: mark the hold as PAYING, call the bank, then take the lock again | The lock is held for a few map operations, and PAYING stops a second payment |
| 6 | The call to the bank failed. What happened to the money? | Give the seats back now, and ask the bank about the key later | The user is not kept waiting, and the seats are not stuck |
| 7 | After a declined card, keep the hold or give it up? | Give the seats back at once | The seats return to the seat map for the next person straight away |
| 8 | Can a hold expire while it is being paid? | Yes, at its deadline, and a late approval is refunded | The deadline means the same thing in every state, so no seat stays held past it |
| 9 | Where does the lock go? | One lock per show | A request is checked and written in one step, and different shows never wait for each other |
Here is Asha's booking of D3 and D4, end to end:
- Her phone calls
BookingService.hold, which checks the list of seats with no lock held.Show.priceOfasks thePricingRulefor the price of each seat, and the service makes a random payment key. Show.holdtakes the show's lock, expires old holds and checks D3 and D4. Both are free, so it creates an ACTIVESeatHoldwith the amount, the key and its deadline. It points both seats at the hold inheldByand releases the lock.- When she taps Pay,
BookingService.paycallsShow.startPayment. It takes the lock, checks that the hold is still ACTIVE, marks it PAYING, and releases the lock. A second tap on Pay now finds PAYING and is refused. paycallsPaymentGateway.chargewith the hold's amount and payment key. This is the outside call, and no lock is held while the bank works, so other users of the show can still hold seats.- The bank approves, so
paycallsShow.confirm. It takes the lock again, expires old holds and finds the hold still PAYING. It moves D3 and D4 fromheldBytobookedBy, creates theBookingand releases the lock as it returns.payhands the booking back to her phone.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package booking; import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.ArrayList;import java.util.EnumSet;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Queue;import java.util.Set;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentLinkedQueue;import java.util.concurrent.atomic.AtomicLong; import exception.PaymentFailedException;import payment.PaymentGateway;import payment.PaymentResult;import payment.PaymentToCheck;import payment.Refund;import payment.Reversal; /** * Holds seats, takes payment and turns holds into bookings. The seat state * lives in each Show, under that show's lock. This class never holds a lock * while it calls the payment gateway. */public final class BookingService { public static final int MAX_SEATS_PER_HOLD = 10; /** How long a hold is kept after its deadline, and a show after its start, so late calls get a clear answer. */ public static final Duration KEEP_FOR = Duration.ofDays(1); private static final Set<HoldStatus> ENDED = EnumSet.of(HoldStatus.CONFIRMED, HoldStatus.RELEASED, HoldStatus.EXPIRED); private final Clock clock; private final PaymentGateway gateway; private final Duration holdTime; private final Map<String, Show> shows = new ConcurrentHashMap<>(); private final Map<String, SeatHold> holds = new ConcurrentHashMap<>(); private final AtomicLong holdCounter = new AtomicLong(); private final AtomicLong bookingCounter = new AtomicLong(); private final Queue<Refund> refundsToRetry = new ConcurrentLinkedQueue<>(); private final Queue<PaymentToCheck> paymentsToCheck = new ConcurrentLinkedQueue<>(); public BookingService(Clock clock, PaymentGateway gateway, Duration holdTime) { this.clock = Objects.requireNonNull(clock, "clock"); this.gateway = Objects.requireNonNull(gateway, "gateway"); this.holdTime = Objects.requireNonNull(holdTime, "holdTime"); if (holdTime.isNegative() || holdTime.isZero()) { throw new IllegalArgumentException("A hold must last longer than zero, not " + holdTime); } } public void addShow(Show show) { Objects.requireNonNull(show, "show"); if (shows.putIfAbsent(show.id(), show) != null) { throw new IllegalArgumentException("Show " + show.id() + " is already listed"); } } /** Keeps the seats for this user for holdTime, or until the show starts. Every seat, or none. */ public SeatHold hold(String showId, String userId, List<String> seatIds) { Objects.requireNonNull(userId, "userId"); Show show = show(showId); List<String> seats = List.copyOf(seatIds); if (seats.isEmpty() || seats.size() > MAX_SEATS_PER_HOLD) { throw new IllegalArgumentException("Pick 1 to " + MAX_SEATS_PER_HOLD + " seats, not " + seats.size()); } if (new HashSet<>(seats).size() != seats.size()) { throw new IllegalArgumentException("A seat is listed twice in " + seats); } // The price is fixed now, so the amount paid is the amount the user was shown. long amount = show.priceOf(seats); String paymentKey = UUID.randomUUID().toString(); SeatHold hold = show.hold(holdCounter::incrementAndGet, userId, paymentKey, seats, amount, clock, holdTime); holds.put(hold.id(), hold); return hold; } /** Charges the user and books the seats. The gateway is called with no lock held. */ public Booking pay(String holdId) { SeatHold hold = findHold(holdId); Show show = show(hold.showId()); show.startPayment(hold, clock); PaymentResult result = null; try { result = Objects.requireNonNull(gateway.charge(hold.userId(), hold.amountCents(), hold.paymentKey()), "payment result"); } finally { if (result == null) { // No answer, whatever was thrown: the bank may have taken the money, so a job undoes the key later. show.paymentFailed(hold); paymentsToCheck.add(new PaymentToCheck(hold.id(), hold.paymentKey(), hold.amountCents())); } } if (!result.approved()) { show.paymentFailed(hold); throw new PaymentFailedException(hold.id(), result.message()); } Optional<Booking> booking = show.confirm(hold, bookingCounter::incrementAndGet, result.reference(), clock); if (booking.isPresent()) { return booking.get(); } // The hold expired while the bank was working, and its seats may already be someone else's. refund(hold.id(), result.reference(), hold.amountCents()); throw new PaymentFailedException(hold.id(), "the hold expired before the payment arrived, so it is refunded"); } /** The user gives the seats back before paying. False if the hold no longer keeps any. */ public boolean cancel(String holdId) { SeatHold hold = findHold(holdId); return show(hold.showId()).cancel(hold, clock); } public Map<String, SeatStatus> seatMap(String showId) { return show(showId).seatMap(clock); } /** * For a timer to call now and then. Every other method also expires old * holds first. This also forgets ended holds whose deadline, and shows * whose start, is more than KEEP_FOR ago, so the maps do not grow for ever. */ public int expireHolds() { int expired = 0; for (Show show : shows.values()) { expired += show.expireHolds(clock); } Instant cutoff = clock.instant().minus(KEEP_FOR); holds.values().removeIf(h -> ENDED.contains(h.status()) && h.expiresAt().isBefore(cutoff)); shows.values().removeIf(s -> s.startsAt().toInstant().isBefore(cutoff)); return expired; } /** * For a job: asks the bank to undo every payment whose outcome we did not * learn. A refund or a blocked key settles it; PENDING keeps it for the * next run. Returns how many it settled. */ public int checkPayments() { int settled = 0; for (int n = paymentsToCheck.size(); n > 0; n--) { PaymentToCheck payment = paymentsToCheck.poll(); if (payment == null) { break; } try { Reversal answer = Objects.requireNonNull(gateway.reverse(payment.paymentKey(), payment.amountCents()), "reversal"); if (answer == Reversal.PENDING) { paymentsToCheck.add(payment); } else { settled++; } } catch (RuntimeException e) { paymentsToCheck.add(payment); } } return settled; } /** For a job: tries every failed refund again. Returns how many went through. */ public int retryRefunds() { int done = 0; for (int n = refundsToRetry.size(); n > 0; n--) { Refund refund = refundsToRetry.poll(); if (refund == null) { break; } try { gateway.refund(refund.reference(), refund.amountCents()); done++; } catch (RuntimeException e) { refundsToRetry.add(refund); } } return done; } public List<Refund> refundsToRetry() { return new ArrayList<>(refundsToRetry); } public List<PaymentToCheck> paymentsToCheck() { return new ArrayList<>(paymentsToCheck); } private void refund(String holdId, String reference, long amountCents) { try { gateway.refund(reference, amountCents); } catch (RuntimeException e) { // A failed refund must not hide the real answer from the user. refundsToRetry.add(new Refund(holdId, reference, amountCents)); } } private Show show(String showId) { Show show = shows.get(Objects.requireNonNull(showId, "showId")); if (show == null) { throw new IllegalArgumentException("No show " + showId); } return show; } private SeatHold findHold(String holdId) { SeatHold hold = holds.get(Objects.requireNonNull(holdId, "holdId")); if (hold == null) { throw new IllegalArgumentException("No hold " + holdId); } return hold; }}demo/Main.java runs a Saturday evening show with 28 seats. Asha books two prime seats, Ravi asks for one of them, Meera's card is declined, and Kabir's hold runs out. Zoya takes the seat Kabir lost, Dev's bank answers too late, and Tara holds two seats as the demo ends:
A prime seat costs $12.50 on Thursday and $15.00 on Saturday Asha holds D3, D4 for $30.00 until 10:10 (H-1) Ravi asks for D4, D5: refused. Seats taken: D4. D5 is still FREE Asha pays: booking B-1 for [D3, D4], $30.00 Meera holds E1, E2 for $54.00 (H-2) Payment for hold H-2 failed: card declined. E1 is FREE, E2 is FREE Kabir holds C1 at 10:00 (H-3) At 10:11 Kabir tries to pay: Hold H-3 is EXPIRED Zoya holds C1 and pays: booking B-2 Dev holds A1 for $10.80 until 10:21, and the bank takes 12 minutes Payment for hold H-5 failed: the hold expired before the payment arrived, so it is refunded. Refunds sent: [PAY-3] Tara holds B2, B3 at 10:23 (H-6) Seat map at 10:23 (. free, h held, X booked): A . . . . . . B . h h . . . C X . . . . . D . . X X . . E . . . .
Notice four things in the output. A prime seat costs $12.50 on Thursday and $15.00 on Saturday, so Asha's two seats cost $30.00. Ravi asked for D4 and D5 and was refused, and D5 stayed free, because a hold is all or none. Kabir's hold expired at 10:10, so at 10:11 his payment was refused before the bank was asked, and Zoya could take C1. Dev's payment arrived after his deadline, so it was refunded as PAY-3, and A1 is free on the final seat map.
Follow-up questions
After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Run on many servers." | The seat maps move to a database: a row per seat per show, held with a conditional update such as UPDATE … WHERE status = 'FREE' in one transaction, or a key with an expiry in Redis. Show's maps become calls to that store. Payment keys are already UUIDs, and paymentsToCheck and refundsToRetry move to the database too, so a restart loses neither. | The hold lifecycle, PricingRule, PaymentGateway. |
| "Stop one user holding half the show." | Show counts live holds per user under its lock, and hold refuses a request over the limit. | Pricing, payment, the lifecycle. |
| "Cancel a paid booking." | A cancelBooking on Show that frees the seats under the lock, then a refund call outside it. | Holds and pricing. |
| "Show the seat map changing live." | A listener list on Show, told after the lock is released. This is the Observer pattern. | Holding, paying, pricing. |
| "Prices that rise as the show fills." | PricingRule also gets the number of free seats, so its signature changes, and hold prices from a snapshot of the seat map. | The fixed price on a hold, payment. |
| "Coupons and offers." | A discount step applied to the hold's total in hold, before it is stored. | Show, the lock, the lifecycle. |
| "Give UPI payments more time than cards." | hold takes the hold time as an argument, chosen by the payment method, still capped at the show's start. | Show's maps, the lock, the lifecycle. |
| "Food and drinks with the tickets." | Items on the hold, with their own stock per cinema and their own lock. | Seats and the show's lock. |
In most rows the change lands in one class or behind one interface. The row about many servers is the big one: the seat state moves out of memory, and the rest of the design stays as it is.
What the interviewer looks for
Mid-level
A mid-level candidate shows clear classes for a show, its seats and a booking, a way to pick seats and pay, and a check that a seat is free before it is sold. They notice that two users can ask for the same seat, and they add a lock.
Senior
A senior candidate shows everything above and gives the reasons. They hold seats with a deadline before payment, make a hold all or none, and keep the seat state per show rather than on a shared seat. They call the bank outside the lock, and they give the seats back when a payment fails. They take a clock so that deadlines can be tested.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They point out that a hold can expire while the bank works, and they explain the refund and the retry list. They pick the lock's scope by what must stay consistent, and they explain how the same rules move to a database row per seat with a conditional update when there is more than one server.
Common mistakes
- Checking a seat, then booking it, with no lock around both. Two users both see the seat free, and both get it.
- A status field on the
Seat. A seat belongs to a screen that runs many shows, so a seat taken at 7pm would look taken at 10pm too. - Holding the lock while the bank works. One slow card blocks every user of the show for as long as the bank takes.
- Holds with no deadline. A user who closes the app keeps the seats until someone notices.
- Treating a timeout from the bank as a decline. The bank may have taken the money, and the user pays again on a new hold.
- Booking a payment that arrived late. The seats may already belong to someone else, so a late approval must be refunded.
- Calling
LocalDateTime.now()inside the code. Deadlines then cannot be tested without waiting for real minutes to pass.
Summary
- Ask before designing. The seat limit, the hold time and how payment works each change the code.
- Keep seat state per show, in maps from seat to hold and seat to booking, guarded by one private lock per show.
- Hold every seat of a request or none, with the check and the writes under the same lock.
- Fix the price when the seats are held, and put pricing behind one interface. A rule that adds to another rule is a Decorator.
- Give every hold a deadline from an injected clock, and expire old holds at the start of every call.
- Pay in three steps: mark the hold PAYING, call the bank with no lock held, then confirm under the lock.
- Let a hold expire even while it is being paid, and refund a late approval. Undo a payment whose outcome is unknown by its key, and retry a failed refund, from jobs that run now and then.