Two people tap seat F12 for the 7 PM show at the same second, and both saw it green. In a movie seat booking system design interview, the whole question is what happens to that seat over the next 10 minutes, and who owns it when the payments come back. Here is how I would build it in Spring Boot.
This is how I would design a BookMyShow-style system in an interview. It is not a description of how any real company's system works.
TL;DR
-
A seat hold is one Redis command:
SET hold:{show:42}:F12 <token> NX PX 600000. NX picks one winner; PX expires the hold after 10 minutes. -
Release a hold with compare-and-delete, never a plain
DEL. -
The database decides the sale:
UNIQUE (show_id, seat_id)sells a seat once, even if Redis gets it wrong. -
@Versionon the booking stops the payment webhook and the expiry sweeper from overwriting each other. -
A payment that lands after the hold expired gets the seat only if nobody else has it, or is refunded automatically.
What happens when two people book the same seat at the same time?
Exactly one of them should get a 10-minute hold, and the other should see "seat just taken" at once. One Redis SET with NX picks the hold winner atomically. When payment succeeds, a UNIQUE constraint in the database picks the sale winner, so even a lost Redis key cannot sell the seat twice.
Movie seat booking system design: seats are not stock
In my flash sale post, 500 identical phones are a number, and selling one is a conditional decrement. But F12 is not F13, and nobody wants "any seat". That changes the tools.
|
Flash sale |
Movie seats |
|
|---|---|---|
|
What you sell |
N identical units |
One specific seat |
|
The atomic step |
Decrement only if stock > 0 |
Insert one row per seat |
|
Final word in the database |
|
|
|
What contends |
One hot stock row |
Each popular seat, separately |
|
The hold |
A reserved quantity |
One Redis key per seat, with a TTL |
A labelled example to size it: say 2 lakh people open seat maps across 1,000 shows in the first minute of a big release. That is about 3,300 reads a second, but writes are tiny: one hold per tap, one insert per paid seat. The hard part is two writes for the same seat in the same millisecond.
The data model
CREATE TABLE booking ( id BIGSERIAL PRIMARY KEY, show_id BIGINT NOT NULL, hold_id VARCHAR(36) NOT NULL, hold_expires_at TIMESTAMPTZ NOT NULL, payment_id VARCHAR(64), status VARCHAR(20) NOT NULL, version BIGINT NOT NULL DEFAULT 0);CREATE TABLE booking_seat ( -- the seats a booking asked for booking_id BIGINT NOT NULL REFERENCES booking (id), seat_id VARCHAR(8) NOT NULL);CREATE TABLE sold_seat ( -- the seats actually sold id BIGSERIAL PRIMARY KEY, show_id BIGINT NOT NULL, seat_id VARCHAR(8) NOT NULL, booking_id BIGINT NOT NULL REFERENCES booking (id), CONSTRAINT uq_sold_seat UNIQUE (show_id, seat_id));booking_seat is what a booking asked for; sold_seat is what was sold, and uq_sold_seat makes double booking impossible. Keep it in the migration: @Table(uniqueConstraints = ...) on an entity only matters when Hibernate generates the schema.
Step 1: hold the seat with SET NX PX
SET hold:{show:42}:F12 7c9e6679-7425-40de-944b-e07fc1f90ae7 NX PX 600000-
NX: only set the key if it does not already exist. -
PX 600000: expire it after 600,000 milliseconds, which is 10 minutes. -
Reply:
OKif the key was set; a null reply (nilin redis-cli) if it already existed, and nothing changed. -
One command, so no gap between "is it free?" and "it is mine".
SETNXthenPEXPIREhas a gap: if the app dies between them, the hold never expires. -
The value is a random token per checkout, not
"1", so you can prove later that the hold is yours.
@Servicepublic class SeatHoldService { static final Duration HOLD_TTL = Duration.ofMinutes(10); // The unlock script from the Redis SET docs: delete only if the key still holds our token private static final RedisScript<Long> RELEASE = RedisScript.of(""" if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end """, Long.class); // All or nothing: fail if any seat is held by someone else, then hold every seat private static final RedisScript<Long> HOLD_ALL = RedisScript.of(""" for i = 1, #KEYS do local owner = redis.call("get", KEYS[i]) if owner and owner ~= ARGV[1] then return 0 end end for i = 1, #KEYS do redis.call("set", KEYS[i], ARGV[1], "PX", ARGV[2]) end return 1 """, Long.class); private final StringRedisTemplate redis; public SeatHoldService(StringRedisTemplate redis) { this.redis = redis; } // One seat: SET with NX and a 10-minute expiry, as one command public boolean tryHold(long showId, String seatId, String holdId) { return Boolean.TRUE.equals( redis.opsForValue().setIfAbsent(key(showId, seatId), holdId, HOLD_TTL)); } // Several seats in one checkout: all held, or none public boolean tryHoldAll(long showId, List<String> seatIds, String holdId) { List<String> keys = seatIds.stream().map(seat -> key(showId, seat)).toList(); Long ok = redis.execute(HOLD_ALL, keys, holdId, String.valueOf(HOLD_TTL.toMillis())); return Long.valueOf(1L).equals(ok); } public void release(long showId, String seatId, String holdId) { redis.execute(RELEASE, List.of(key(showId, seatId)), holdId); } // {show:42} is a hash tag: every seat of one show lands in the same cluster slot static String key(long showId, String seatId) { return "hold:{show:" + showId + "}:" + seatId; }}setIfAbsent(key, value, Duration) sends one SET with NX and an expiry. For whole seconds, Spring Data Redis sends EX 600 instead of PX 600000: the same expiry.
Release with compare-and-delete. Your hold expired at 7:10:00, someone else held F12 at 7:10:01, and your "cancel" lands at 7:10:02. A plain DEL deletes their hold. RELEASE, the script from the Redis SET docs, deletes the key only if it still holds your token.
Several seats, all or nothing. Holding four seats one by one can leave a family with two. HOLD_ALL checks every key, then sets them all, and Redis runs a script atomically. On Redis Cluster, a script's keys must share one hash slot, which is what the {show:42} hash tag is for.
The Redis docs discourage SET ... NX as a lock in favour of Redlock's stronger guarantees. Fine here: Redis is not the final word. If a failover loses a hold, Step 2 still sells the seat once.
Step 2: the database has the final word
// Check, then insert: two requests can both pass the check@Transactionalpublic void sell(long showId, String seatId, long bookingId) { if (soldSeats.existsByShowIdAndSeatId(showId, seatId)) { throw new SeatTakenException(bookingId); } soldSeats.save(new SoldSeat(showId, seatId, bookingId));}// No check: UNIQUE (show_id, seat_id) lets exactly one insert win.// The loser gets DataIntegrityViolationException, and its caller refunds.@Transactionalpublic void sell(long showId, String seatId, long bookingId) { soldSeats.saveAndFlush(new SoldSeat(showId, seatId, bookingId));}Without the constraint, two transactions under PostgreSQL's default READ COMMITTED can both run the exists check, both see no row, and both insert. With it, PostgreSQL rejects the second insert with a unique violation (SQLSTATE 23505), and Spring turns that into DataIntegrityViolationException. No locks, no retries, and it covers every code path that writes the table.
Step 3: optimistic locking on the booking
The payment webhook wants CONFIRMED; the expiry sweeper wants EXPIRED. Without protection, the slower one silently overwrites the faster one: the customer paid, sold_seat has their rows, and the booking says EXPIRED.
@Versionprivate long version; // every UPDATE gets "and version = ?"With @Version, Hibernate puts the version in the WHERE clause of every UPDATE. The second writer updates zero rows, and Spring throws OptimisticLockingFailureException instead of losing the first write. In the flash sale post I argued against @Version for stock, where thousands fight over one row. Here it fits: one booking, two writers, rare conflicts.
@Transactionalpublic void confirm(long bookingId, String paymentId) { Booking booking = bookings.findById(bookingId).orElseThrow(); if (booking.getStatus() != BookingStatus.PENDING_PAYMENT && booking.getStatus() != BookingStatus.EXPIRED) { return; // already decided: a retried webhook } boolean holdLapsed = Instant.now().isAfter(booking.getHoldExpiresAt()); if (holdLapsed && !holds.tryHoldAll(booking.getShowId(), booking.getSeatIds(), booking.getHoldId())) { throw new SeatTakenException(bookingId); // someone else holds a seat right now } List<SoldSeat> rows = booking.getSeatIds().stream() .map(seatId -> new SoldSeat(booking.getShowId(), seatId, bookingId)) .toList(); soldSeats.saveAllAndFlush(rows); // UNIQUE (show_id, seat_id) decides here booking.confirm(paymentId); // version checked at commit}// Not @Transactional on purpose: each attempt is its own transaction in BookingTxpublic void onPaymentCaptured(long bookingId, String paymentId) { for (int attempt = 1; attempt <= 3; attempt++) { try { bookingTx.confirm(bookingId, paymentId); return; } catch (OptimisticLockingFailureException e) { // the sweeper changed this booking after we read it: read again, decide again } catch (DataIntegrityViolationException | SeatTakenException e) { bookingTx.markRefundPending(bookingId, paymentId); // a refund worker pays it back return; } } throw new IllegalStateException("Booking " + bookingId + " kept changing, retry the webhook");}BookingTx is a separate bean on purpose: a @Transactional method called on this skips Spring's proxy, trap 1 in my @Transactional post. The exceptions are caught outside the transaction, because after a failed flush it can only roll back.
Step 4: the expiry sweeper
Redis frees the seat at minute 10 by itself. The booking row needs something to move it to EXPIRED.
Why not listen for Redis expiry events? The Redis docs give two reasons. Pub/Sub is fire and forget, so events sent while your listener was disconnected are lost. And the expired event fires when Redis deletes the key, not when the TTL reaches zero, which can lag when many keys have a TTL.
@Scheduled(fixedDelay = 30_000)public void expireStaleBookings() { Instant cutoff = Instant.now().minus(GRACE); List<Long> ids = bookings.findStaleIds(BookingStatus.PENDING_PAYMENT, cutoff, PageRequest.of(0, 200)); for (Long id : ids) { try { bookingTx.expire(id); } catch (OptimisticLockingFailureException paidMeanwhile) { // the payment webhook won this race: leave the booking alone } }}GRACE (2 minutes) lets an in-flight payment land first. @Scheduled needs @EnableScheduling. With several instances, @Version makes double work harmless; at higher volume, claim rows with SELECT ... FOR UPDATE SKIP LOCKED.
Step 5: the payment that succeeds after the hold expired
UPI approvals, bank OTP pages and slow networks mean some payments land after minute 10. Decide the rules first.
|
When the payment lands |
Seat state |
What I do |
|---|---|---|
|
Before the hold expires |
Held by this checkout |
Insert into |
|
After expiry, seat free |
Nobody holds it |
Re-hold, insert, mark |
|
After expiry, seat held |
Someone else's hold |
|
|
After expiry, seat sold |
Row exists in |
Unique violation, then refund |
|
The same webhook again |
Already decided |
Nothing |
My rule: whoever holds the seat right now beats a late payer, and a late payer who finds it free gets it, because they paid and nobody else wanted it. Everything else is a refund, decided in milliseconds and shown on screen.
Make the refund idempotent: one refund record per booking, checked before calling the gateway, so a retry never pays out twice. My idempotency keys post covers that half. If your gateway lets you set a payment timeout, keep it below the hold, say 8 minutes, so most late payments are refused before money moves.
Checklist before you ship
-
The hold value is a random token, not "1"
-
Release uses compare-and-delete, never a plain
DEL -
Multi-seat holds are all or nothing, and the keys share a hash tag
-
UNIQUE (show_id, seat_id)is in the migration, not only on the entity -
The booking has
@Version, and both writers handleOptimisticLockingFailureException -
A repeated webhook changes nothing, and refunds are idempotent
-
The sweeper has a grace period
The 60-second interview answer
“A tap holds the seat in Redis with SET NX PX 600000 and a random token. NX means one tap wins; the TTL frees an abandoned hold in 10 minutes. I release with compare-and-delete, and hold several seats in one Lua script, all or nothing. Redis is the fast path, not the truth. On payment, I insert one row per seat into sold_seat with a unique constraint on show and seat, so a seat is sold once even if Redis loses a hold. A version column stops the webhook and the expiry sweeper overwriting each other. A sweeper, not Redis expiry events, expires unpaid bookings. A late payment gets the seat only if it is still free; otherwise it is refunded automatically.”
Interview questions
Why not lock the seat row with SELECT ... FOR UPDATE?
The hold lasts up to 10 minutes while the user pays. A row lock lives inside a transaction, so you would keep a transaction and a connection open for minutes per user. A TTL hold is a lease that needs no open transaction; the database only does a short insert at the end.
Redis fails over and loses a hold. What happens?
Another user can hold the same seat, and both may pay. The first insert into sold_seat wins; the second hits the unique constraint and is refunded. Rare and unpleasant, but never a double booking.
What to read next
-
500 phones, 1 lakh buyers, 1 second: the stock version, five fixes compared.
-
Designing a Tatkal-style booking system: queues, seat locks and bot defence.
-
Idempotency keys in Spring Boot: making the webhook and refund safe to retry.




Discussion