These are the notes for Low-Level Design (LLD) episode 75: the second half of designing a movie ticket booking app (the kind of app BookMyShow is). Part 1 (episode 74) built cinemas, screens, shows, a seat map and the booking flow for one user. Part 2 is about many users at once: a real race with 50 threads, double-booking prevention with pessimistic and optimistic seat locking, temporary holds with lock expiry, payment integration, booking states, cancellation and refunds, and a concurrency test with multiple threads.
How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. Two kinds of output change from run to run, and the notes say so where it matters: which thread wins a race, and timings in milliseconds (they depend on the machine). Shows, users, prices and refund rules are made up; nothing here describes how the real BookMyShow app is built.
1. The problem: the last samosa and the trial room
| Real life | In the design |
|---|---|
| Two friends both see the last samosa is free, and both grab it | A race condition |
| The shopkeeper serves one customer at a time | A lock (pessimistic) |
| "Grab it, and I'll check at the till if someone beat you" | Optimistic locking |
| "I'll keep this aside for 10 minutes" | A temporary hold with lock expiry |
| Pay at the counter; the bill has return rules | Payment, booking states, refund policy |
2. The words: threads and races
- Thread: one line of work running inside a program. A server runs many threads at once, typically one per user request.
- Thread pool (
ExecutorService): a team of ready threads you hand tasks to:Executors.newFixedThreadPool(50). - Future: a handle to a task's result that you collect later with
get(). - CountDownLatch: a starting gun. Threads call
await()and wait; onecountDown()releases them all at once. - Race condition: a bug where the result depends on which thread runs first.
- Check-then-act: "if it's free, take it" written as two separate steps; between them, another thread can do the same.
- Critical section: code that only one thread may run at a time.
Concurrency was taught in episodes 46 to 50; here we use it on a real design.
3. Attempt 1: check, then book
import java.util.*; import java.util.concurrent.*;
class Show { // attempt: check, then book
final Map<String, String> owner = new HashMap<>(); // seat -> user
boolean book(String seat, String user) throws InterruptedException {
if (owner.containsKey(seat)) return false; // 1. check: is it free?
Thread.sleep(20); // ...the app talks to the database...
owner.put(seat, user); // 2. act: take it
return true; }
}
public class Main { public static void main(String[] args) throws Exception {
Show show = new Show();
ExecutorService pool = Executors.newFixedThreadPool(50); // 50 users tap A1 together
CountDownLatch go = new CountDownLatch(1);
List<Future<Boolean>> tries = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
String user = "user" + i;
tries.add(pool.submit(() -> { go.await(); return show.book("A1", user); })); }
go.countDown(); // ready, steady, go!
int sold = 0; for (Future<Boolean> f : tries) if (f.get()) sold++;
pool.shutdown();
System.out.println("A1 was sold " + sold + " times. It belongs to: " + show.owner.get("A1"));
} }
Real output (the owner at the end changes every run: it's whoever wrote last):
A1 was sold 50 times. It belongs to: user48
Why it failed
All 50 threads ran the check (containsKey) before any of them ran the act (put). The Thread.sleep(20) stands in for the time a real app spends talking to its database; it makes the gap wide enough that the race happens every time. Without it the race still happens, just less often, which is worse: it passes your tests and fails on a busy Friday night.
4. Two fixes: pessimistic and optimistic locking
- Pessimistic locking: expect conflicts, so lock first. In Java, a
synchronizedmethod lets only one thread inside at a time (per object). Safe and simple, but everyone queues, even users booking different seats. - Optimistic locking: expect no conflict, so take no lock for the slow work, and at the end do one atomic check-and-set. Atomic means it can't be split: no other thread can act between the check and the set.
ConcurrentHashMap.putIfAbsent(seat, user)is atomic: it returnsnullonly to the one thread whose put won. This idea is also called compare-and-set (CAS).
import java.util.*; import java.util.concurrent.*;
interface SeatBooker { boolean book(String seat, String user) throws InterruptedException; }
class PessimisticShow implements SeatBooker { // lock FIRST: one thread at a time inside
private final Map<String, String> owner = new HashMap<>();
public synchronized boolean book(String seat, String user) throws InterruptedException {
if (owner.containsKey(seat)) return false;
Thread.sleep(20); // the slow part, now inside the lock
owner.put(seat, user); return true; } }
class OptimisticShow implements SeatBooker { // no lock: try, and check nobody beat you
private final ConcurrentHashMap<String, String> owner = new ConcurrentHashMap<>();
public boolean book(String seat, String user) throws InterruptedException {
Thread.sleep(20); // the slow part, outside any lock
return owner.putIfAbsent(seat, user) == null; } } // atomic: only ONE put can win
public class Main {
static void race(String name, SeatBooker show, boolean same) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(50); // 50 users at the same moment
CountDownLatch go = new CountDownLatch(1);
List<Future<Boolean>> tries = new ArrayList<>();
for (int i = 1; i <= 50; i++) { String u = "user" + i;
tries.add(pool.submit(() -> { go.await(); return show.book(same ? "A1" : "S" + u, u); })); }
long t0 = System.nanoTime(); go.countDown();
int sold = 0; for (Future<Boolean> f : tries) if (f.get()) sold++; pool.shutdown();
System.out.printf("%-12s %-10s sold %2d in %4d ms%n", name, same ? "same seat" : "50 seats", sold,
(System.nanoTime() - t0) / 1_000_000); }
public static void main(String[] args) throws Exception {
race("pessimistic", new PessimisticShow(), true); // everyone wants A1
race("optimistic", new OptimisticShow(), true);
race("pessimistic", new PessimisticShow(), false); // everyone wants a different seat
race("optimistic", new OptimisticShow(), false); } }
Real output (the times change from machine to machine; the pattern does not):
pessimistic same seat sold 1 in 26 ms
optimistic same seat sold 1 in 21 ms
pessimistic 50 seats sold 50 in 1012 ms
optimistic 50 seats sold 50 in 22 ms
- Same seat: both sell A1 exactly once. Double booking is prevented.
- 50 different seats: pessimistic took about a second (50 × 20 ms, one after another, behind one lock); optimistic took about 20 ms (everyone in parallel).
- In real systems the same choice appears in the database: pessimistic =
SELECT ... FOR UPDATE(lock the row); optimistic = a version column:UPDATE seats SET owner = ?, version = 8 WHERE id = 'A1' AND version = 7and retry if 0 rows changed.
| Pessimistic | Optimistic | |
|---|---|---|
| Idea | Lock, then work | Work, then check-and-set |
| Best when | Conflicts are common (a hit movie's opening night) | Conflicts are rare |
| Cost | Waiting in a queue; risk of deadlocks with many locks | Losers must retry or give up |
| Java tool | synchronized, ReentrantLock |
putIfAbsent, AtomicReference.compareAndSet |
5. Temporary holds and lock expiry
Paying takes minutes. If we book only after payment, someone else can pay for the seat first. So the moment a user picks seats, we place a seat lock: a temporary hold for that user. It has lock expiry: it ends by itself after 5 minutes, so users who walk away don't block seats forever. After payment we confirm only if the hold is still alive.
import java.util.*;
record SeatLock(String user, long expiresAt) {} // a temporary hold on one seat
class SeatLockProvider {
static final long HOLD_MINUTES = 5;
private final Map<String, SeatLock> locks = new HashMap<>(); // seat -> who holds it, until when
private final Set<String> booked = new HashSet<>();
private boolean heldByOther(String seat, String user, long now) {
SeatLock l = locks.get(seat);
if (l != null && now >= l.expiresAt()) { locks.remove(seat); return false; } // expired
return l != null && !l.user().equals(user); }
synchronized String hold(List<String> seats, String user, long now) {
for (String s : seats)
if (booked.contains(s) || heldByOther(s, user, now)) return user + ": " + s + " is not free";
for (String s : seats) locks.put(s, new SeatLock(user, now + HOLD_MINUTES));
return user + ": holding " + seats + " until minute " + (now + HOLD_MINUTES); }
synchronized String confirm(List<String> seats, String user, long now) { // after payment
for (String s : seats)
if (heldByOther(s, user, now) || !locks.containsKey(s)) return user + ": hold expired";
seats.forEach(s -> { locks.remove(s); booked.add(s); });
return user + ": CONFIRMED " + seats; }
}
public class Main { public static void main(String[] args) {
SeatLockProvider p = new SeatLockProvider();
System.out.println("min 0: " + p.hold(List.of("A1", "A2"), "Asha", 0));
System.out.println("min 2: " + p.hold(List.of("A2", "A3"), "Ravi", 2)); // A2 is held
System.out.println("min 6: " + p.hold(List.of("A2", "A3"), "Ravi", 6)); // Asha's hold expired
System.out.println("min 7: " + p.confirm(List.of("A1", "A2"), "Asha", 7)); // too late
System.out.println("min 8: " + p.confirm(List.of("A2", "A3"), "Ravi", 8));
} }
Real output:
min 0: Asha: holding [A1, A2] until minute 5
min 2: Ravi: A2 is not free
min 6: Ravi: holding [A2, A3] until minute 11
min 7: Asha: hold expired
min 8: Ravi: CONFIRMED [A2, A3]
- Minute 0: Asha holds A1, A2 until minute 5.
- Minute 2: Ravi is told A2 is not free.
- Minute 6: Asha's hold has expired (it's removed the moment someone checks), so Ravi holds A2, A3.
- Minute 7: Asha's payment comes back too late: hold expired. (In real life: refund her at once; see the mini project.)
- Minute 8: Ravi is confirmed.
- The clock is a plain number passed in, so the test is exact. Real code would use a
Clockinterface, with a fake one in tests. - Expiry here is lazy: checked when someone asks. A scheduler (episode 71) can also sweep expired holds actively.
6. Payments, booking states, cancellation and refunds
- Payment gateway: the outside service that actually charges a UPI account or a card. Payment integration means calling it and handling its answer. We hide it behind an interface,
PaymentGateway, so tests use a fake that never charges anyone (and can decline on purpose). - Booking states:
PENDING_PAYMENT→CONFIRMED→CANCELLED→REFUNDED, orPENDING_PAYMENT→EXPIREDwhen payment fails or the hold ends. - A state machine (episode 37) allows only certain moves;
move(from, to)throws on anything else. - Refund policy: 24 hours or more before the show: 100%. 2 hours or more: 50%. Later: nothing.
import java.util.*;
enum BookingState { PENDING_PAYMENT, CONFIRMED, EXPIRED, CANCELLED, REFUNDED }
interface PaymentGateway { boolean charge(String bookingId, int amount); } // UPI, card... one interface
class Booking {
final String id; final int amount; final long showAt; // showAt: hour of the show
BookingState state = BookingState.PENDING_PAYMENT;
final List<String> history = new ArrayList<>(List.of("PENDING_PAYMENT"));
Booking(String i, int a, long at) { id = i; amount = a; showAt = at; }
void move(BookingState from, BookingState to) { // the state machine: only allowed moves
if (state != from) throw new IllegalStateException(id + ": cannot go " + state + " -> " + to);
state = to; history.add(to.name()); } }
class BookingService {
final PaymentGateway gateway; BookingService(PaymentGateway g) { gateway = g; }
void pay(Booking b) {
boolean paid = gateway.charge(b.id, b.amount);
b.move(BookingState.PENDING_PAYMENT, paid ? BookingState.CONFIRMED : BookingState.EXPIRED); }
int cancel(Booking b, long now) { // refund policy: hours before the show
b.move(BookingState.CONFIRMED, BookingState.CANCELLED);
int refund = b.showAt - now >= 24 ? b.amount : b.showAt - now >= 2 ? b.amount / 2 : 0;
b.move(BookingState.CANCELLED, BookingState.REFUNDED); return refund; } }
public class Main { public static void main(String[] args) {
PaymentGateway fake = (id, amt) -> !id.equals("BK2"); // a fake gateway: BK2's card is declined
BookingService svc = new BookingService(fake);
Booking b1 = new Booking("BK1", 430, 48), b2 = new Booking("BK2", 180, 48);
Booking b3 = new Booking("BK3", 900, 48); // all three shows are at hour 48
svc.pay(b1); svc.pay(b2); svc.pay(b3);
System.out.println("BK1 refund " + svc.cancel(b1, 10) + " BK3 refund " + svc.cancel(b3, 40));
for (Booking b : List.of(b1, b2, b3)) System.out.println(b.id + ": " + String.join(" > ", b.history));
svc.cancel(b2, 10); } }
Real output:
BK1 refund 430 BK3 refund 450
BK1: PENDING_PAYMENT > CONFIRMED > CANCELLED > REFUNDED
BK2: PENDING_PAYMENT > EXPIRED
BK3: PENDING_PAYMENT > CONFIRMED > CANCELLED > REFUNDED
Exception in thread "main" java.lang.IllegalStateException: BK2: cannot go EXPIRED -> CANCELLED
at Booking.move(Main.java:10)
at BookingService.cancel(Main.java:18)
at Main.main(Main.java:29)
- BK1 cancelled at hour 10 for a show at hour 48: 38 hours before, full refund 430.
- BK3 cancelled at hour 40: 8 hours before, half: 450 of 900.
- BK2's card was declined:
PENDING_PAYMENT > EXPIRED. - Cancelling BK2 throws
IllegalStateException: BK2: cannot go EXPIRED -> CANCELLED: no refund for money never paid.
7. The class diagram
User taps seats ─▶ SeatLockProvider.hold(seats, user, now) (synchronized; all or nothing)
SeatLock(user, expiresAt = now + 5 min) · expired? released on the next check (lock expiry)
Pessimistic: lock first (synchronized) Optimistic: try, then putIfAbsent (compare-and-set)
Booking state machine: PENDING_PAYMENT ─pay ok─▶ CONFIRMED ─cancel─▶ CANCELLED ─▶ REFUNDED
└─pay fails / hold expires─▶ EXPIRED (seats go back)
PaymentGateway (interface: UPI, card, fake in tests) · refund: 24h+ 100% · 2h+ 50% · else 0
8. Interview follow-ups
| Question | Answer |
|---|---|
| Many servers, not one JVM? | synchronized protects one process only. Put the lock where all servers can see it: a database row lock, a unique constraint, or a key with a time-to-live in a shared cache such as Redis. |
| Optimistic locking in a database? | A version column; update only WHERE version = <what you read>; 0 rows means someone beat you. |
| A payment retried twice? | An idempotency key (the booking id): the gateway charges it once. |
| The payment result comes after the hold expired? | Refund at once (mini project: hold expired, refund 400 at once). |
| Clearing expired holds? | Lazily when checked, plus a scheduled sweep. |
| A lock per show or per seat? | Per show is simple and enough for a machine-coding round; per seat (or optimistic) scales better. |
9. Common mistakes
| Mistake | What you see (real) | Fix |
|---|---|---|
| Check, then act, with no lock | A1 was sold 50 times |
synchronized, or an atomic putIfAbsent |
| One big lock for everything | pessimistic 50 seats sold 50 in ... about 1000 ms (about a second) |
Optimistic locking, or a lock per show |
| Holds that never expire | seats blocked by users who left | expiresAt + release on check |
| Confirming without checking the hold | an expired hold confirms a seat now held by someone else | Confirm only your own live hold: Asha: hold expired |
| States as free-form strings | a refund for an unpaid booking | A state machine: cannot go EXPIRED -> CANCELLED |
| Calling the slow payment inside the lock | every user waits for one user's payment | Charge outside the lock, re-check inside (mini project) |
Mini project: holds, payments, refunds and a 100-thread test
One BookingSystem with a fake clock, a fake payment gateway, a lock per show, holds with expiry, a state machine, refunds, and a concurrency test: 100 users released together, 10 seats, user i wants seat B(i % 10). The test checks the invariant: exactly 10 confirmed and every seat sold once. (Which user wins each seat changes every run; the counts don't.)
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
enum BookingState { PENDING_PAYMENT, CONFIRMED, EXPIRED, CANCELLED, REFUNDED }
interface Clock { long now(); } // minutes; a fake clock makes tests exact
interface PaymentGateway { boolean charge(String bookingId, int amount); }
record SeatLock(String bookingId, long expiresAt) {}
class Booking {
final String id, user; final List<String> seats; final int amount; final long showAt;
BookingState state = BookingState.PENDING_PAYMENT;
Booking(String id, String user, List<String> seats, int amount, long showAt) {
this.id = id; this.user = user; this.seats = seats; this.amount = amount; this.showAt = showAt;
}
synchronized void move(BookingState from, BookingState to) {
if (state != from) throw new IllegalStateException(id + ": cannot go " + state + " -> " + to);
state = to;
}
}
class Show { // one lock per show, not one for the app
final String id; final long startsAt; final Set<String> seats; final int price;
final Map<String, SeatLock> locks = new HashMap<>();
final Map<String, String> sold = new HashMap<>(); // seat -> booking id
Show(String id, long startsAt, Set<String> seats, int price) {
this.id = id; this.startsAt = startsAt; this.seats = seats; this.price = price;
}
}
class BookingSystem {
static final long HOLD_MINUTES = 5;
final Clock clock; final PaymentGateway gateway;
final Map<String, Booking> bookings = new ConcurrentHashMap<>();
private final AtomicInteger next = new AtomicInteger(1);
BookingSystem(Clock c, PaymentGateway g) { clock = c; gateway = g; }
private boolean free(Show show, String seat, long now) {
if (show.sold.containsKey(seat)) return false;
SeatLock l = show.locks.get(seat);
if (l == null) return true;
if (now >= l.expiresAt()) { // lock expiry
show.locks.remove(seat);
Booking old = bookings.get(l.bookingId());
if (old != null && old.state == BookingState.PENDING_PAYMENT) old.move(BookingState.PENDING_PAYMENT, BookingState.EXPIRED);
return true;
}
return false;
}
Booking hold(Show show, String user, List<String> wanted) {
synchronized (show) { // pessimistic lock on this show only
long now = clock.now();
for (String s : wanted) {
if (!show.seats.contains(s)) throw new IllegalArgumentException(s + " does not exist");
if (!free(show, s, now)) return null;
}
Booking b = new Booking("BK" + next.getAndIncrement(), user, List.copyOf(wanted), wanted.size() * show.price, show.startsAt);
for (String s : wanted) show.locks.put(s, new SeatLock(b.id, now + HOLD_MINUTES));
bookings.put(b.id, b);
return b;
}
}
String pay(Show show, Booking b) {
boolean paid = gateway.charge(b.id, b.amount); // slow call: outside the show lock
synchronized (show) {
long now = clock.now();
boolean stillMine = b.seats.stream().allMatch(s -> {
SeatLock l = show.locks.get(s);
return l != null && l.bookingId().equals(b.id) && now < l.expiresAt();
});
if (!paid || !stillMine) {
b.seats.forEach(s -> { SeatLock l = show.locks.get(s); if (l != null && l.bookingId().equals(b.id)) show.locks.remove(s); });
if (b.state == BookingState.PENDING_PAYMENT) b.move(BookingState.PENDING_PAYMENT, BookingState.EXPIRED);
return b.id + ": " + (!paid ? "payment declined" : "hold expired") + (paid ? ", refund " + b.amount + " at once" : "");
}
b.seats.forEach(s -> { show.locks.remove(s); show.sold.put(s, b.id); });
b.move(BookingState.PENDING_PAYMENT, BookingState.CONFIRMED);
return b.id + ": CONFIRMED " + b.seats + " for " + b.amount;
}
}
int cancel(Show show, Booking b) {
synchronized (show) {
b.move(BookingState.CONFIRMED, BookingState.CANCELLED);
b.seats.forEach(show.sold::remove); // the seats are free again
long hoursLeft = (b.showAt - clock.now()) / 60;
int refund = hoursLeft >= 24 ? b.amount : hoursLeft >= 2 ? b.amount / 2 : 0;
b.move(BookingState.CANCELLED, BookingState.REFUNDED);
return refund;
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
long[] minute = {0};
Clock clock = () -> minute[0];
Set<String> declined = ConcurrentHashMap.newKeySet();
PaymentGateway fake = (id, amt) -> !declined.contains(id);
BookingSystem sys = new BookingSystem(clock, fake);
// 1. holds, expiry and payment, on an exact fake clock
Show s1 = new Show("S1", 48 * 60, Set.of("A1", "A2", "A3"), 200);
Booking asha = sys.hold(s1, "Asha", List.of("A1", "A2"));
System.out.println("min 0: Asha holds " + asha.seats + " as " + asha.id);
minute[0] = 2; System.out.println("min 2: Ravi asks for A2, A3 -> " + (sys.hold(s1, "Ravi", List.of("A2", "A3")) == null ? "not free" : "held"));
minute[0] = 6; Booking ravi = sys.hold(s1, "Ravi", List.of("A2", "A3"));
System.out.println("min 6: Ravi holds " + ravi.seats + " as " + ravi.id + "; " + asha.id + " is " + asha.state);
minute[0] = 7; System.out.println("min 7: " + sys.pay(s1, asha));
minute[0] = 8; System.out.println("min 8: " + sys.pay(s1, ravi));
minute[0] = 30 * 60; System.out.println("hour 30: Ravi cancels, refund " + sys.cancel(s1, ravi) + ", " + ravi.id + " " + ravi.state);
try { sys.cancel(s1, asha); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }
// 2. a concurrency test: 100 users, 10 seats, user i wants seat (i % 10)
minute[0] = 0;
Set<String> ten = new HashSet<>(); for (int i = 0; i < 10; i++) ten.add("B" + i);
Show s2 = new Show("S2", 48 * 60, ten, 150);
ExecutorService pool = Executors.newFixedThreadPool(100);
CountDownLatch go = new CountDownLatch(1);
List<Future<String>> results = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int u = i;
results.add(pool.submit(() -> {
go.await();
Booking b = sys.hold(s2, "user" + u, List.of("B" + (u % 10)));
return b == null ? "no seat" : sys.pay(s2, b);
}));
}
go.countDown();
int confirmed = 0;
for (Future<String> f : results) if (f.get().contains("CONFIRMED")) confirmed++;
pool.shutdown();
System.out.println("concurrency test: confirmed " + confirmed + ", seats sold " + s2.sold.size()
+ " of " + ten.size() + ", every seat sold once: " + (confirmed == s2.sold.size()));
}
}
Real output:
min 0: Asha holds [A1, A2] as BK1
min 2: Ravi asks for A2, A3 -> not free
min 6: Ravi holds [A2, A3] as BK2; BK1 is EXPIRED
min 7: BK1: hold expired, refund 400 at once
min 8: BK2: CONFIRMED [A2, A3] for 400
hour 30: Ravi cancels, refund 200, BK2 REFUNDED
BK1: cannot go EXPIRED -> CANCELLED
concurrency test: confirmed 10, seats sold 10 of 10, every seat sold once: true
Notes on the design:
holdand the confirm part ofpayrun insidesynchronized (show): a pessimistic lock per show, so two different shows never wait for each other.- The slow
gateway.chargeruns outside the lock; inside, we re-check the hold (that's the optimistic idea: do the slow work, verify at the end). - If the money came in but the hold had expired, we refund at once.
- Ravi cancelled at hour 30 for a show at hour 48: 18 hours before, so half of 400 = 200.
Practice
1. Write a test: 100 threads, 10 seats, exactly 10 sold.
Answer
The mini project's part 2 is that test. The important parts: a CountDownLatch so all threads start together, collect every Future, then assert confirmed == 10 and sold.size() == 10. Run it many times (a loop of 100 runs): races don't show up every time.
2. Make OptimisticShow retry: if putIfAbsent loses, try the next free seat in the same row.
Answer
Loop over the row's seat ids; for each, if (owner.putIfAbsent(id, user) == null) return id;; if the loop ends, return null ("sold out"). Each attempt is atomic, so two users can never get the same seat.
3. Why is synchronized on the method of a shared object enough in one JVM but not across two servers?
Answer
synchronized uses a lock inside one JVM's memory. A second server has its own memory and its own lock, so both can enter at once. Use a lock both can see: a database row lock, a unique constraint on (show, seat), or a shared cache key with a time-to-live.
4. Add a rule: no cancellation in the last 30 minutes.
Answer
In cancel, before moving states: if (showAt - now < 30 minutes) throw new IllegalStateException("too late to cancel"). The state stays CONFIRMED.
5. Why is the clock passed in instead of calling System.currentTimeMillis()?
Answer
So tests can control time exactly: "minute 6" is a number we set, not a 6-minute wait. The real app passes a clock that reads the system time.
Quick quiz
A hold lasts 5 minutes. At minute 0 Asha holds B1, at minute 4 Ravi asks for B1, at minute 9 Neha asks for B1. Who is holding B1 after minute 9? (a) Asha (b) Ravi (c) Neha (d) nobody
Answer
(c) Neha. At minute 4 Asha's hold is alive until minute 5, so Ravi is told B1 is not free and gets no hold. At minute 9 Asha's hold has expired, so Neha gets it.
Interview questions
- How do you prevent double booking? Make "is it free? take it" atomic: a lock (pessimistic) or an atomic compare-and-set / version check (optimistic), and in the database a unique constraint on (show, seat).
- Pessimistic vs optimistic locking? Lock first and queue, vs work freely and check at the end; choose by how often conflicts happen.
- Why temporary holds? Payment takes time; the seat must be reserved for the payer while they pay.
- What if a user never pays? The hold expires and the seats are released.
- What are the booking states? PENDING_PAYMENT, CONFIRMED, EXPIRED, CANCELLED, REFUNDED, with only allowed moves.
- How do you integrate payments? Behind an interface; idempotency keys; handle declined, slow and late answers.
- What if payment succeeds after the hold expired? Refund immediately and tell the user.
- How do you test concurrency? Many threads released together by a latch, many repetitions, and invariant checks.
- Where should the lock live with many servers? In shared storage: database or distributed cache, with an expiry.
- How do refunds work? A refund policy by time before the show, applied on cancel, then the REFUNDED state.
Glossary
| Term | Meaning, with an example |
|---|---|
| Thread | One line of work running in a program; one per user request |
| Thread pool / ExecutorService | A team of ready threads: Executors.newFixedThreadPool(50) |
| Future | A handle to a task's result: f.get() |
| CountDownLatch | A starting gun: await() waits, countDown() releases |
| Race condition | The result depends on which thread runs first: A1 sold 50 times |
| Check-then-act | Checking and taking as two steps, with a gap between them |
| Critical section | Code only one thread may run at a time |
| Seat locking | Making sure only one user can hold or buy a seat |
| Double-booking prevention | Never selling one seat to two people |
| Lock | Something only one thread can hold at a time |
| synchronized | Java keyword: one thread at a time in this method or block |
| Pessimistic locking | Lock first, then work |
| Optimistic locking | Work without a lock, then check-and-set at the end |
| Atomic | Can't be split; nobody can act in the middle |
| Compare-and-set (CAS) | Set a value only if it is still what you expect |
| ConcurrentHashMap | A map many threads can use safely |
| putIfAbsent | Put only if the key is missing; returns null to the winner |
| Version column | A number bumped on every update; used for optimistic locking in a database |
| Temporary hold | Seats reserved for one user for a short time |
| Lock expiry | A hold ending by itself after a time: 5 minutes |
| Lazy vs active expiry | Removed when checked vs removed by a scheduled sweep |
| Payment gateway | The outside service that charges UPI or a card |
| Payment integration | Calling the gateway and handling its answer |
| PaymentGateway | Our interface: boolean charge(String bookingId, int amount) |
| Fake | A test stand-in that behaves like the real thing: a gateway that declines BK2 |
| Booking states | PENDING_PAYMENT, CONFIRMED, EXPIRED, CANCELLED, REFUNDED |
| State machine | Only allowed moves between states; others throw |
| Cancellation | A user giving a booking back; seats become free |
| Refund | Money returned; amount set by the refund policy |
| Refund policy | 24h+ before: 100% · 2h+: 50% · later: 0 |
| Idempotency key | An id so a retried payment is charged once |
| Concurrency test | A test that runs many threads at once and checks invariants |
| Invariant | Something that must always be true: every seat sold at most once |
Summary
- Check-then-act with 50 real threads sold one seat 50 times: a race condition.
- Pessimistic locking (
synchronized) and optimistic locking (putIfAbsent) both sell it once; optimistic doesn't make everyone queue. - Temporary holds with lock expiry let users pay without losing their seats, and free seats when they leave.
- Payments sit behind a PaymentGateway interface; a state machine guards booking states, cancellations and refunds.
- A concurrency test with 100 threads checks the invariant: every seat sold once.
- Next episode: design Splitwise: expenses, splits, balances and settling up.