Design a movie ticket booking system
Design a movie ticket booking system like BookMyShow or a cinema chain's app: users pick a movie, a showtime and specific seats, hold them for a few minutes while paying, and get a confirmed booking.
A typical framing: "A popular premiere opens for booking at 10:00 and thousands of people try to grab the same seats. Two people must never get the same seat. Seats someone abandons mid-payment should become free again. Show me the classes, the API and how you handle the concurrency."
TL;DR
The heart of this question is concurrency on seats. Split booking into two steps: a short hold (lock seats for ~10 minutes) and a confirm after payment. A seat for a show moves through a state machine: available → held → booked (and back to available when a hold expires or a payment fails).
Make the hold atomic in the database: a single conditional update that claims all requested seats only if they're all still available (or a unique constraint on (showId, seatId) for active holds). Optimistic concurrency (conditional updates, versions) beats pessimistic row locks for a hot show, because conflicts fail fast instead of piling up waiting transactions. Holds carry an expiry that is checked on every read, plus a background job that releases expired holds. Payment confirmation is idempotent and verifies the hold is still valid.
1. Requirements
Questions worth asking:
- Do users pick specific seats, or just a quantity?
- How long can seats be held during payment?
- Can a booking mix seat categories with different prices?
- Cancellations and refunds?
- Peak load: how many users try to book the same show at once?
Functional
- Browse movies, cinemas and showtimes.
- See the seat map of a show with live availability.
- Hold selected seats, pay, and get a confirmed booking.
- Cancel a booking (within a policy).
Non-functional
- No double booking, ever.
- Abandoned holds are released automatically.
- The seat map stays fast under heavy read load.
2. Entities and classes
Seat describes the physical seat in a screen (row, number, category). ShowSeat is that seat for one specific show; it's the row that carries the status and is the target of every concurrency check.
3. API
GET /v1/shows?movieId=&city=&date=
GET /v1/shows/{showId}/seats -> seat map with status
POST /v1/shows/{showId}/holds { seatIds } -> 201 { holdId, expiresAt } or 409 { unavailableSeatIds }
DELETE /v1/holds/{holdId} -> release early
POST /v1/holds/{holdId}/booking { paymentToken } (Idempotency-Key) -> 201 { bookingId }
POST /v1/bookings/{bookingId}/cancel4. Core logic
Holding seats atomically
-- Claim all requested seats in one statement. Expired holds count as available.
UPDATE show_seats
SET status = 'held', hold_id = :holdId, hold_expires_at = now() + interval '10 minutes'
WHERE show_id = :showId
AND seat_id = ANY(:seatIds)
AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));async function holdSeats(userId: string, showId: string, seatIds: string[]) {
return db.transaction(async (tx) => {
const holdId = newId()
const claimed = await tx.claimSeats(showId, seatIds, holdId) // the UPDATE above
if (claimed.rowCount !== seatIds.length) {
// Someone else got at least one seat: roll back, so we don't keep a partial hold.
throw new SeatsUnavailableError(await tx.unavailable(showId, seatIds))
}
await tx.insertHold({ id: holdId, userId, showId, seatIds, expiresAt: inMinutes(10) })
return holdId
})
}All or nothing: a user who asked for four seats together shouldn't end up with two. The transaction rolls back if fewer rows were updated than requested.
Confirming after payment
async function confirm(holdId: string, paymentToken: string, idempotencyKey: string) {
const previous = await bookings.findByIdempotencyKey(idempotencyKey)
if (previous) return previous
const hold = await holds.get(holdId)
if (hold.expiresAt < new Date()) throw new HoldExpiredError()
const payment = await payments.charge(paymentToken, priceOf(hold), idempotencyKey)
return db.transaction(async (tx) => {
// Only succeeds if the seats are still held by this hold.
const updated = await tx.markBooked(hold.showId, hold.seatIds, holdId)
if (updated !== hold.seatIds.length) {
await payments.refund(payment.id) // hold expired during payment
throw new HoldExpiredError()
}
return tx.insertBooking({ hold, paymentId: payment.id, idempotencyKey })
})
}The race between "payment succeeded" and "hold expired" is real. Either give the hold a grace period during an active payment, or refund automatically as above.
Expiring holds
Availability checks treat an expired hold as free (the hold_expires_at < now() condition), so correctness never depends on the cleanup job. A background job still releases expired holds every minute, so the seat map shows the right status.
5. Edge cases and extensions
- Pessimistic vs. optimistic locking:
SELECT ... FOR UPDATEon the seats works, but under a rush thousands of transactions wait on the same rows. A conditional update either wins immediately or fails immediately, which is what users need ("seat taken, pick another"). - Distributed lock (Redis
SET NX PX) per seat is another option, but the database must still be the source of truth; two systems of record are harder to keep consistent. - Seat map under load: cache it for a second or two and push changes to viewers (SSE or WebSocket). A slightly stale map is fine because the hold itself is the real check.
- Virtual waiting room: for huge premieres, admit users in batches before they reach the seat map.
- Bots and abuse: limit the number of seats per hold and active holds per user.
- Cancellations:
booked → availablewith a refund through the payment provider; a cancellation window per policy.
Common follow-ups
- "Why not just a unique constraint?" A unique index on
(show_id, seat_id)in abookings_seatstable is a great safety net: even with a bug elsewhere, the database refuses a double booking. It doesn't handle holds and expiry by itself, so use it together with the status-based flow. - "What isolation level do you need?" The conditional update is safe under the default
READ COMMITTEDin PostgreSQL, because theWHEREis re-checked against the latest row version. A "read, check in code, then write" flow would needSERIALIZABLEor a row lock. - "How do you shard this?" By
showId: all seats of a show live together, so every hold is a single-shard transaction.
What interviewers look for
- Separating Seat from ShowSeat, and a clear state machine.
- An atomic, all-or-nothing hold and a clear stance on optimistic vs. pessimistic locking.
- Hold expiry that doesn't depend on a cleanup job for correctness.
- Handling the payment vs. expiry race, with idempotent confirmation.
- Scaling ideas: cached seat maps, waiting rooms, sharding by show.