From c57031aaeb8c8c2a2332e117067441e2978cc019 Mon Sep 17 00:00:00 2001 From: asmhatre Date: Tue, 17 Nov 2026 01:03:33 +0530 Subject: [PATCH] Add bookmyshow module: seat booking with hold expiry and payment timeout, naive vs pessimistic vs optimistic inventories, race and deadlock demos, JDBC strategies on H2 (8 test classes, 8 transcripts) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b5YFRisPHrLBR2dRu9 --- README.md | 1 + bookmyshow/README.md | 62 ++++++ bookmyshow/output/01-happy-path.txt | 14 ++ bookmyshow/output/02-naive-race.txt | 20 ++ bookmyshow/output/03-lock-ordering.txt | 21 ++ bookmyshow/output/04-contention.txt | 8 + bookmyshow/output/05-random-seats.txt | 24 +++ bookmyshow/output/06-expiry-and-payment.txt | 22 +++ bookmyshow/output/07-pitfalls.txt | 29 +++ bookmyshow/output/08-database-strategies.txt | 9 + bookmyshow/pom.xml | 71 +++++++ bookmyshow/scripts/run-all.sh | 9 + .../bookmyshow/AbstractSeatInventory.java | 72 +++++++ .../interviewlab/bookmyshow/AcquireOrder.java | 9 + .../interviewlab/bookmyshow/Booking.java | 12 ++ .../bookmyshow/BookingOutcome.java | 12 ++ .../bookmyshow/BookingService.java | 103 ++++++++++ .../bookmyshow/BookingStatus.java | 15 ++ .../bookmyshow/FakePaymentGateway.java | 49 +++++ .../bookmyshow/JdbcSeatStore.java | 169 ++++++++++++++++ .../interviewlab/bookmyshow/MutableClock.java | 39 ++++ .../bookmyshow/NaiveInventory.java | 88 +++++++++ .../bookmyshow/OptimisticInventory.java | 150 ++++++++++++++ .../bookmyshow/PaymentGateway.java | 8 + .../bookmyshow/PaymentResult.java | 3 + .../bookmyshow/PessimisticInventory.java | 186 ++++++++++++++++++ .../ankurm/interviewlab/bookmyshow/Seat.java | 3 + .../interviewlab/bookmyshow/SeatCategory.java | 3 + .../bookmyshow/SeatInventory.java | 47 +++++ .../interviewlab/bookmyshow/SeatSlot.java | 56 ++++++ .../interviewlab/bookmyshow/SeatState.java | 11 ++ .../bookmyshow/SeatUnavailableException.java | 10 + .../ankurm/interviewlab/bookmyshow/Show.java | 70 +++++++ .../bookmyshow/ContentionTest.java | 180 +++++++++++++++++ .../bookmyshow/DatabaseSeatTest.java | 84 ++++++++ .../bookmyshow/ExpiryAndPaymentTest.java | 139 +++++++++++++ .../bookmyshow/HappyPathTest.java | 63 ++++++ .../bookmyshow/LockOrderingTest.java | 107 ++++++++++ .../interviewlab/bookmyshow/PitfallsTest.java | 124 ++++++++++++ .../bookmyshow/RaceConditionTest.java | 111 +++++++++++ .../bookmyshow/support/Fixtures.java | 66 +++++++ .../bookmyshow/support/Transcript.java | 43 ++++ 42 files changed, 2322 insertions(+) create mode 100644 bookmyshow/README.md create mode 100644 bookmyshow/output/01-happy-path.txt create mode 100644 bookmyshow/output/02-naive-race.txt create mode 100644 bookmyshow/output/03-lock-ordering.txt create mode 100644 bookmyshow/output/04-contention.txt create mode 100644 bookmyshow/output/05-random-seats.txt create mode 100644 bookmyshow/output/06-expiry-and-payment.txt create mode 100644 bookmyshow/output/07-pitfalls.txt create mode 100644 bookmyshow/output/08-database-strategies.txt create mode 100644 bookmyshow/pom.xml create mode 100755 bookmyshow/scripts/run-all.sh create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AbstractSeatInventory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AcquireOrder.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Booking.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingOutcome.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingService.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingStatus.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/FakePaymentGateway.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/JdbcSeatStore.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/MutableClock.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/NaiveInventory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/OptimisticInventory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentGateway.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentResult.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PessimisticInventory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Seat.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatCategory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatInventory.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatSlot.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatState.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatUnavailableException.java create mode 100644 bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Show.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ContentionTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/DatabaseSeatTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ExpiryAndPaymentTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/HappyPathTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/LockOrderingTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/PitfallsTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/RaceConditionTest.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Fixtures.java create mode 100644 bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Transcript.java diff --git a/README.md b/README.md index 63fadea..e792a1b 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ One module per article. This repository currently holds: | [`library-management`](library-management/) | Library Management System in Java: Console Version to Spring Boot REST API | this commit | | [`matrix`](matrix/) | Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation | this commit | | [`rate-limiter`](rate-limiter/) | Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot | this commit | +| [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit | ## `collections` module diff --git a/bookmyshow/README.md b/bookmyshow/README.md new file mode 100644 index 0000000..c6b7ae0 --- /dev/null +++ b/bookmyshow/README.md @@ -0,0 +1,62 @@ +# bookmyshow + +Companion code for the ankurm.com article **Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings)**. + +A seat-booking core with hold expiry and payment timeout, built three ways: a naive inventory that double-books, +a pessimistic one (per-seat locks) and an optimistic one (compare-and-set). Every figure and console line in the +article is quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. There is no +`docs/` folder: the explanations live in the article itself. + +## Versions + +| Component | Version | Verified against | +|---|---|---| +| JDK | Temurin 25.0.5+8 (LTS) | `java -version` | +| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA; `6.2.0-M1` is a milestone) | +| H2 (tests only) | 2.5.252 | `com.h2database:h2` `maven-metadata.xml` on Maven Central | +| Maven | 3.9.11 | `mvn -version` | + +## Quickstart + +```bash +cd bookmyshow +export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH" +./scripts/run-all.sh # runs every test and regenerates output/*.txt +``` + +The first Maven run must be online so the plugins land in the local cache. Three transcripts contain counts that +depend on thread timing (marked "control" or "timing dependent" inside the file); they differ from run to run by design. + +## The pieces + +| Class | Role | +|---|---| +| `Show`, `Seat`, `SeatCategory` | the screening and its seats; price depends on the seat category | +| `SeatSlot`, `SeatState` | one seat's whole state as an immutable value: state, owner, expiry, version | +| `SeatInventory` | the one interface where seat state changes: `tryHold`, `confirm`, `release` | +| `NaiveInventory` | check-then-act on a `ConcurrentHashMap`; double-books | +| `PessimisticInventory` | one `ReentrantLock` per seat, locks taken in sorted order | +| `OptimisticInventory` | `AtomicReference` per seat, compare-and-set, roll back on conflict | +| `JdbcSeatStore` | the same question in SQL: optimistic version column, `FOR UPDATE`, one conditional `UPDATE` | +| `BookingService` | hold, pay, confirm; refund when the hold is lost during payment | +| `MutableClock`, `FakePaymentGateway` | deterministic time and a payment provider the tests can slow down | + +## The transcripts + +| File | Written by | What it shows | +|---|---|---| +| `output/01-happy-path.txt` | `HappyPathTest` | one user at a time: all three inventories behave identically | +| `output/02-naive-race.txt` | `RaceConditionTest` | the naive inventory granting one seat twice | +| `output/03-lock-ordering.txt` | `LockOrderingTest` | deadlock with unsorted locks, mutual refusal with unsorted optimistic holds | +| `output/04-contention.txt` | `ContentionTest` | 200 threads, one seat (timing dependent control line) | +| `output/05-random-seats.txt` | `ContentionTest` | 400 users, random seats, invariants that must hold | +| `output/06-expiry-and-payment.txt` | `ExpiryAndPaymentTest` | hold expiry, slow payment, resold seat, declined card | +| `output/07-pitfalls.txt` | `PitfallsTest` | partial holds, foreign releases, bad input, double Pay | +| `output/08-database-strategies.txt` | `DatabaseSeatTest` | the same race against H2 (timing dependent control line) | + +`SeatInventory` implementations expose small test seams (`betweenCheckAndAct`, `afterFirstLock`, `afterFirstAcquire`, +`beforeRollback`) so the tests can force an interleaving on every run. They are test hooks, not part of the design. + +## License + +MIT, see the repository root. diff --git a/bookmyshow/output/01-happy-path.txt b/bookmyshow/output/01-happy-path.txt new file mode 100644 index 0000000..cc20f6c --- /dev/null +++ b/bookmyshow/output/01-happy-path.txt @@ -0,0 +1,14 @@ +Happy path, one user at a time (show SH-1, 60 seats, hold TTL 5 minutes) +======================================================================== + +A1 at the start: AVAILABLE v0 +startBooking(asha, A1+A2): BK-0001 PENDING_PAYMENT, Rs 440 +A1 after the hold: HELD by BK-0001 until T+05:00 v1 +A3 untouched: AVAILABLE v0 +startBooking(ravi, A2+A3): refused (seats not available for show SH-1: [A2, A3]) +A3 after ravi's refusal: AVAILABLE v0 +pay(BK-0001): CONFIRMED, booking is CONFIRMED +A1 after payment: BOOKED by BK-0001 v2 +seat summary: {AVAILABLE=58, BOOKED=2, HELD=0} + +Same log produced by NaiveInventory, PessimisticInventory and OptimisticInventory: true diff --git a/bookmyshow/output/02-naive-race.txt b/bookmyshow/output/02-naive-race.txt new file mode 100644 index 0000000..9a99940 --- /dev/null +++ b/bookmyshow/output/02-naive-race.txt @@ -0,0 +1,20 @@ +NaiveInventory: two users request seat C5 at the same moment (barrier forces both reads before either write) +==================================================================================================== + +holds granted for C5: 2 (a seat can only be sold once) +both users now pay: + outcomes (sorted): [CONFIRMED, HOLD_LOST_AFTER_PAYMENT] + customers charged: 2 + customers refunded: 1 +C5 in the end: BOOKED by BK-000x v3 + +Neither thread did anything unusual. Each ran check, then act, and the barrier only decided +that both checks finished before either act began. + +PessimisticInventory, same two users at the same moment: + holds granted for C5: 1 + loser sees: SeatUnavailableException + +OptimisticInventory, same two users at the same moment: + holds granted for C5: 1 + loser sees: SeatUnavailableException diff --git a/bookmyshow/output/03-lock-ordering.txt b/bookmyshow/output/03-lock-ordering.txt new file mode 100644 index 0000000..09839d2 --- /dev/null +++ b/bookmyshow/output/03-lock-ordering.txt @@ -0,0 +1,21 @@ +Two requests for the same two seats, listed in opposite order: H1 asks [A1, A2], H2 asks [A2, A1] +================================================================================================= + +PessimisticInventory, AS_REQUESTED (each thread holds one lock, then waits for the other's): + stuck until a lock wait timed out (300 ms): true + at least one lock wait timed out: true + requests that succeeded: at most 1 (never both; which one is timing dependent) + Without the timeout both threads would wait forever. + +PessimisticInventory, SORTED (both requests lock A1 first, so one simply waits): + requests that succeeded: 1 of 2 + lock waits that timed out: 0 + +OptimisticInventory, AS_REQUESTED (each request takes one seat, then finds the other taken): + results: [false, false] + A1 / A2 afterwards: AVAILABLE / AVAILABLE (versions v2 / v2: held, then handed back) + Both seats are free and both customers were turned away. + +OptimisticInventory, SORTED (both start at A1, so only one can get past the first seat): + requests that succeeded: 1 of 2 + HELD seats afterwards: 2 diff --git a/bookmyshow/output/04-contention.txt b/bookmyshow/output/04-contention.txt new file mode 100644 index 0000000..e7edfbe --- /dev/null +++ b/bookmyshow/output/04-contention.txt @@ -0,0 +1,8 @@ +200 threads released at once, all asking for seat D4, repeated 30 times per inventory +===================================================================================== + +PessimisticInventory: rounds with exactly one winner: 30 of 30 +OptimisticInventory: rounds with exactly one winner: 30 of 30 + +Control, not asserted and timing dependent: NaiveInventory, no barrier inside it: +NaiveInventory: rounds with exactly one winner: 10 of 30 diff --git a/bookmyshow/output/05-random-seats.txt b/bookmyshow/output/05-random-seats.txt new file mode 100644 index 0000000..6a8e9a8 --- /dev/null +++ b/bookmyshow/output/05-random-seats.txt @@ -0,0 +1,24 @@ +400 users, each asking for 1 to 3 random seats of a 60-seat show (seeded plan), all released at once +==================================================================================================== + +seats requested in total (seeded, identical for every inventory): 800 + +PessimisticInventory, SORTED: + no seat granted to two requests: true + every granted request owns all of its seats: true + HELD seats == seats of granted requests: true + AVAILABLE + HELD == 60: true + +OptimisticInventory, SORTED: + no seat granted to two requests: true + every granted request owns all of its seats: true + HELD seats == seats of granted requests: true + AVAILABLE + HELD == 60: true + +OptimisticInventory, AS_REQUESTED: + no seat granted to two requests: true + every granted request owns all of its seats: true + HELD seats == seats of granted requests: true + AVAILABLE + HELD == 60: true + +How many requests were granted differs from run to run (it depends on the interleaving) and is deliberately not printed. diff --git a/bookmyshow/output/06-expiry-and-payment.txt b/bookmyshow/output/06-expiry-and-payment.txt new file mode 100644 index 0000000..fac20cd --- /dev/null +++ b/bookmyshow/output/06-expiry-and-payment.txt @@ -0,0 +1,22 @@ +Hold expiry and payment timeout on a fake clock (TTL 5 minutes, no sleeping) +============================================================================ + +1. Pay one second before the deadline + hold placed T+00:00, expires T+05:00, pay pressed T+04:59 + outcome: CONFIRMED charges: 1 refunds: 0 +2. The deadline passes while Asha is on the payment page (she holds B1 and B2) + T+04:59 B1 reads as HELD + T+05:00 B1 reads as AVAILABLE (stored slot still says HELD: expiry is lazy) + T+05:01 Ravi asks for B1: BK-0002 PENDING_PAYMENT + T+05:02 Asha presses Pay: HOLD_EXPIRED_BEFORE_PAYMENT charges: 0 + B1: HELD by BK-0002 until T+10:01 v2 + B2: AVAILABLE v2 +3. Pay pressed at T+04:59, the gateway takes two minutes, nobody else wants the seat + outcome: HOLD_LOST_AFTER_PAYMENT charges: 1 refunds: [BK-0001] booking: REFUNDED +4. Same slow payment, but Ravi takes B4 while the gateway is still working on Asha's charge + outcome: HOLD_LOST_AFTER_PAYMENT charges: 1 refunds: [BK-0001] booking: REFUNDED + B4: HELD by BK-0002 until T+11:59 v2 +5. The card is declined + outcome: PAYMENT_DECLINED booking: PAYMENT_FAILED B5 now: AVAILABLE + +Same log produced by all three inventories: true diff --git a/bookmyshow/output/07-pitfalls.txt b/bookmyshow/output/07-pitfalls.txt new file mode 100644 index 0000000..7f1ef3e --- /dev/null +++ b/bookmyshow/output/07-pitfalls.txt @@ -0,0 +1,29 @@ +Pitfalls: partial holds, foreign releases, bad input, double Pay +================================================================ + +1. Request [A1, A2, A3] while someone else holds A3 + NaiveInventory result false A1 AVAILABLE v0 A2 AVAILABLE v0 + PessimisticInventory result false A1 AVAILABLE v0 A2 AVAILABLE v0 + OptimisticInventory result false A1 AVAILABLE v2 A2 AVAILABLE v2 + (v0 means the seat was never touched; v2 means it was held and handed back during the attempt) + +2. Someone who does not own the hold tries to release or confirm it + NaiveInventory after Ravi's release and confirm: C1 is HELD by ASHA, Ravi's confirm returned false + PessimisticInventory after Ravi's release and confirm: C1 is HELD by ASHA, Ravi's confirm returned false + OptimisticInventory after Ravi's release and confirm: C1 is HELD by ASHA, Ravi's confirm returned false + +3. A BOOKED seat is not released by release(), even by its owner + NaiveInventory C2 after owner's release: BOOKED, a new hold on it returns false + PessimisticInventory C2 after owner's release: BOOKED, a new hold on it returns false + OptimisticInventory C2 after owner's release: BOOKED, a new hold on it returns false + +4. Bad input (identical for all three inventories) + duplicate seat ids: IllegalArgumentException: duplicate seat id in request: A1 + unknown seat: IllegalArgumentException: unknown seat Z99 for show SH-1 + no seats at all: IllegalArgumentException: no seats requested + unknown show: IllegalArgumentException: unknown show: SH-404 + +5. Pay pressed 50 times at once for the same booking + calls that confirmed: 1 + calls refused with IllegalStateException: 49 + times the card was charged: 1 diff --git a/bookmyshow/output/08-database-strategies.txt b/bookmyshow/output/08-database-strategies.txt new file mode 100644 index 0000000..6f82f64 --- /dev/null +++ b/bookmyshow/output/08-database-strategies.txt @@ -0,0 +1,9 @@ +32 connections released at once, all holding seat D4 of SH-1, repeated 20 times per strategy (H2 2.5.252) +==================================================================================================== + +optimistic (SELECT, then UPDATE ... WHERE version = ?): rounds with exactly one winner: 20 of 20 +pessimistic (SELECT ... FOR UPDATE, then UPDATE): rounds with exactly one winner: 20 of 20 +conditional (one UPDATE ... WHERE state = 'AVAILABLE'): rounds with exactly one winner: 20 of 20 + +Control, not asserted and timing dependent: +naive (SELECT, then UPDATE with no version or lock): rounds with exactly one winner: 3 of 20 diff --git a/bookmyshow/pom.xml b/bookmyshow/pom.xml new file mode 100644 index 0000000..11e34c8 --- /dev/null +++ b/bookmyshow/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.ankurm.interviewlab + bookmyshow + 1.0.0 + jar + + java-interview-lab :: bookmyshow + + Runnable companion code for ankurm.com's "Low-Level Design: BookMyShow Seat Booking in Java" article: seat holds, + naive vs pessimistic vs optimistic inventories, hold expiry, payment timeout and concurrency tests. + + + + 25 + UTF-8 + 6.1.3 + 2.5.252 + + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + + + org.junit.jupiter + junit-jupiter + test + + + com.h2database + h2 + ${h2.version} + test + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.0 + + -Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8 + + + + + diff --git a/bookmyshow/scripts/run-all.sh b/bookmyshow/scripts/run-all.sh new file mode 100755 index 0000000..38df9a6 --- /dev/null +++ b/bookmyshow/scripts/run-all.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online. +# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures +# in the article are assertions: they fail the build the moment they stop being true. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output +mvn -B -q -T1 test +echo "done:"; ls -1 output diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AbstractSeatInventory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AbstractSeatInventory.java new file mode 100644 index 0000000..404f0e9 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AbstractSeatInventory.java @@ -0,0 +1,72 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Instant; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** Show registry, argument validation and summary, shared so the three implementations differ only in how they synchronise. */ +public abstract class AbstractSeatInventory implements SeatInventory { + protected final Clock clock; + private final Map shows = new ConcurrentHashMap<>(); + + protected AbstractSeatInventory(Clock clock) { + this.clock = clock; + } + + @Override + public final void register(Show show) { + shows.put(show.id(), show); + onRegister(show); + } + + protected abstract void onRegister(Show show); + + @Override + public final Show show(String showId) { + Show s = shows.get(showId); + if (s == null) { + throw new IllegalArgumentException("unknown show: " + showId); + } + return s; + } + + @Override + public final Clock clock() { + return clock; + } + + /** Rejects empty requests, unknown seats and duplicate seat ids before any state is touched. */ + protected final void validate(String showId, List seatIds) { + Show s = show(showId); + if (seatIds.isEmpty()) { + throw new IllegalArgumentException("no seats requested"); + } + Set seen = new HashSet<>(); + for (String id : seatIds) { + if (!s.hasSeat(id)) { + throw new IllegalArgumentException("unknown seat " + id + " for show " + showId); + } + if (!seen.add(id)) { + throw new IllegalArgumentException("duplicate seat id in request: " + id); + } + } + } + + @Override + public final Map summary(String showId) { + Instant now = clock.instant(); + Map counts = new EnumMap<>(SeatState.class); + for (SeatState st : SeatState.values()) { + counts.put(st, 0L); + } + for (String id : show(showId).seatIds()) { + counts.merge(slot(showId, id).effectiveState(now), 1L, Long::sum); + } + return counts; + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AcquireOrder.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AcquireOrder.java new file mode 100644 index 0000000..5139813 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/AcquireOrder.java @@ -0,0 +1,9 @@ +package com.ankurm.interviewlab.bookmyshow; + +/** In which order a multi-seat request touches its seats. It sounds like a detail; sections 5 and 6 show it is not. */ +public enum AcquireOrder { + /** Sort the seat ids first, so every request walks the seats in the same global order. */ + SORTED, + /** Walk the seats in whatever order the caller listed them. */ + AS_REQUESTED +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Booking.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Booking.java new file mode 100644 index 0000000..4b38322 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Booking.java @@ -0,0 +1,12 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Instant; +import java.util.List; + +public record Booking(String id, String userId, String showId, List seatIds, int amountRupees, + Instant heldAt, Instant expiresAt, BookingStatus status) { + + public Booking withStatus(BookingStatus s) { + return new Booking(id, userId, showId, seatIds, amountRupees, heldAt, expiresAt, s); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingOutcome.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingOutcome.java new file mode 100644 index 0000000..0771d38 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingOutcome.java @@ -0,0 +1,12 @@ +package com.ankurm.interviewlab.bookmyshow; + +/** What {@link BookingService#pay} reports. Four of the five are different ways of not getting a ticket. */ +public enum BookingOutcome { + CONFIRMED, + /** Pay was pressed after the hold had expired. Nothing was charged. */ + HOLD_EXPIRED_BEFORE_PAYMENT, + /** The gateway declined. The seats were released. Nothing was charged. */ + PAYMENT_DECLINED, + /** The gateway charged the customer, but by then the hold was gone. The charge was refunded. */ + HOLD_LOST_AFTER_PAYMENT +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingService.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingService.java new file mode 100644 index 0000000..6c720d1 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingService.java @@ -0,0 +1,103 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The customer-facing flow: hold seats, pay, confirm. It knows nothing about locks. All concurrency control that + * decides who gets a seat is inside the {@link SeatInventory}; the only concurrency this class handles itself is + * "the same booking being paid twice". + */ +public final class BookingService { + private final SeatInventory inventory; + private final Clock clock; + private final PaymentGateway payments; + private final Duration holdTtl; + private final Map bookings = new ConcurrentHashMap<>(); + private final AtomicLong sequence = new AtomicLong(); + + public BookingService(SeatInventory inventory, Clock clock, PaymentGateway payments, Duration holdTtl) { + this.inventory = inventory; + this.clock = clock; + this.payments = payments; + this.holdTtl = holdTtl; + } + + /** Step 1: put a time-limited hold on the seats. Throws {@link SeatUnavailableException} if any seat is taken. */ + public Booking startBooking(String userId, String showId, List seatIds) { + Show show = inventory.show(showId); + String bookingId = "BK-%04d".formatted(sequence.incrementAndGet()); + if (!inventory.tryHold(showId, seatIds, bookingId, holdTtl)) { + throw new SeatUnavailableException(showId, seatIds); + } + Instant now = clock.instant(); + Booking b = new Booking(bookingId, userId, showId, List.copyOf(seatIds), show.priceOf(seatIds), + now, now.plus(holdTtl), BookingStatus.PENDING_PAYMENT); + bookings.put(bookingId, b); + return b; + } + + /** Step 2: charge and confirm. See {@link BookingOutcome} for the five ways this can end. */ + public BookingOutcome pay(String bookingId) { + Booking b = transition(bookingId, BookingStatus.PENDING_PAYMENT, BookingStatus.PAYMENT_IN_PROGRESS); + + if (!clock.instant().isBefore(b.expiresAt())) { + inventory.release(b.showId(), b.seatIds(), b.id()); + set(bookingId, BookingStatus.EXPIRED); + return BookingOutcome.HOLD_EXPIRED_BEFORE_PAYMENT; + } + + PaymentResult result = payments.charge(b.id(), b.amountRupees()); + if (!result.success()) { + inventory.release(b.showId(), b.seatIds(), b.id()); + set(bookingId, BookingStatus.PAYMENT_FAILED); + return BookingOutcome.PAYMENT_DECLINED; + } + + if (inventory.confirm(b.showId(), b.seatIds(), b.id())) { + set(bookingId, BookingStatus.CONFIRMED); + return BookingOutcome.CONFIRMED; + } + + payments.refund(b.id()); + set(bookingId, BookingStatus.REFUNDED); + return BookingOutcome.HOLD_LOST_AFTER_PAYMENT; + } + + /** The customer walked away: free the seats now rather than waiting for the hold to expire. */ + public void cancel(String bookingId) { + Booking b = transition(bookingId, BookingStatus.PENDING_PAYMENT, BookingStatus.CANCELLED); + inventory.release(b.showId(), b.seatIds(), b.id()); + } + + public Booking booking(String bookingId) { + Booking b = bookings.get(bookingId); + if (b == null) { + throw new IllegalArgumentException("unknown booking: " + bookingId); + } + return b; + } + + /** Atomically moves a booking from one status to another, or throws if it was not in the expected status. */ + private Booking transition(String bookingId, BookingStatus from, BookingStatus to) { + while (true) { + Booking cur = booking(bookingId); + if (cur.status() != from) { + throw new IllegalStateException("booking " + bookingId + " is " + cur.status() + ", expected " + from); + } + Booking next = cur.withStatus(to); + if (bookings.replace(bookingId, cur, next)) { + return next; + } + } + } + + private void set(String bookingId, BookingStatus status) { + bookings.computeIfPresent(bookingId, (k, v) -> v.withStatus(status)); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingStatus.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingStatus.java new file mode 100644 index 0000000..c4f455e --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/BookingStatus.java @@ -0,0 +1,15 @@ +package com.ankurm.interviewlab.bookmyshow; + +public enum BookingStatus { + /** Seats are held; the customer has not pressed Pay yet. */ + PENDING_PAYMENT, + /** Pay was pressed and the gateway is working. A second Pay for the same booking is refused while in this state. */ + PAYMENT_IN_PROGRESS, + CONFIRMED, + /** The hold ran out before payment was attempted. */ + EXPIRED, + PAYMENT_FAILED, + /** The customer was charged but the seats could no longer be confirmed, so the money was returned. */ + REFUNDED, + CANCELLED +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/FakePaymentGateway.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/FakePaymentGateway.java new file mode 100644 index 0000000..9147a9b --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/FakePaymentGateway.java @@ -0,0 +1,49 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * A payment gateway that does whatever the test tells it to. {@link #duringCharge(Runnable)} runs while a charge is + * "in flight", which is how the tests make payment slow: the hook advances the fake clock, or lets another user + * grab the seat, exactly when a real gateway would be waiting on the bank. + */ +public final class FakePaymentGateway implements PaymentGateway { + private final AtomicInteger charges = new AtomicInteger(); + private final List refunds = new CopyOnWriteArrayList<>(); + private final AtomicBoolean declineNext = new AtomicBoolean(); + private volatile Runnable duringCharge = () -> { }; + + public void declineNext() { + declineNext.set(true); + } + + public void duringCharge(Runnable hook) { + this.duringCharge = hook; + } + + public int charges() { + return charges.get(); + } + + public List refunds() { + return refunds; + } + + @Override + public PaymentResult charge(String bookingId, int amountRupees) { + charges.incrementAndGet(); + duringCharge.run(); + if (declineNext.getAndSet(false)) { + return new PaymentResult(false, null); + } + return new PaymentResult(true, "PAY-" + bookingId); + } + + @Override + public void refund(String bookingId) { + refunds.add(bookingId); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/JdbcSeatStore.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/JdbcSeatStore.java new file mode 100644 index 0000000..f1027f4 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/JdbcSeatStore.java @@ -0,0 +1,169 @@ +package com.ankurm.interviewlab.bookmyshow; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.time.Instant; + +/** + * The same seat, held three ways, with a database as the shared state instead of the JVM. This is what the in-memory + * inventories turn into the moment the application runs on more than one server: a JVM lock or an + * {@code AtomicReference} cannot be seen by the other server, but a row can. + * + *

One seat only, on purpose: the point is how each strategy decides who wins, not a complete schema. + */ +public final class JdbcSeatStore { + private final DataSource dataSource; + + public JdbcSeatStore(DataSource dataSource) { + this.dataSource = dataSource; + } + + public void createSchema() throws SQLException { + try (Connection c = dataSource.getConnection(); Statement s = c.createStatement()) { + s.execute(""" + CREATE TABLE IF NOT EXISTS seat ( + show_id VARCHAR(20) NOT NULL, + seat_id VARCHAR(10) NOT NULL, + state VARCHAR(10) NOT NULL, + hold_id VARCHAR(40), + expires_at TIMESTAMP, + version BIGINT NOT NULL, + PRIMARY KEY (show_id, seat_id) + )"""); + } + } + + public void resetSeat(String showId, String seatId) throws SQLException { + try (Connection c = dataSource.getConnection(); Statement s = c.createStatement()) { + s.execute("DELETE FROM seat WHERE show_id = '" + showId + "' AND seat_id = '" + seatId + "'"); + s.execute("INSERT INTO seat VALUES ('" + showId + "', '" + seatId + "', 'AVAILABLE', NULL, NULL, 0)"); + } + } + + /** The control: read the row, decide, then update with no version and no lock. This is check-then-act, in SQL. */ + public boolean holdNaive(String showId, String seatId, String holdId, Instant now, Instant expiresAt) throws SQLException { + try (Connection c = dataSource.getConnection()) { + try (PreparedStatement read = c.prepareStatement( + "SELECT state, expires_at FROM seat WHERE show_id = ? AND seat_id = ?")) { + read.setString(1, showId); + read.setString(2, seatId); + try (ResultSet rs = read.executeQuery()) { + rs.next(); + if (!isFree(rs.getString("state"), rs.getTimestamp("expires_at"), now)) { + return false; + } + } + } + try (PreparedStatement write = c.prepareStatement(""" + UPDATE seat SET state = 'HELD', hold_id = ?, expires_at = ?, version = version + 1 + WHERE show_id = ? AND seat_id = ?""")) { + write.setString(1, holdId); + write.setTimestamp(2, Timestamp.from(expiresAt)); + write.setString(3, showId); + write.setString(4, seatId); + return write.executeUpdate() == 1; + } + } + } + + /** Strategy 1, optimistic: read the row and its version, then update only if the version is still the one we read. */ + public boolean holdOptimistic(String showId, String seatId, String holdId, Instant now, Instant expiresAt) throws SQLException { + try (Connection c = dataSource.getConnection()) { + long version; + try (PreparedStatement read = c.prepareStatement( + "SELECT state, expires_at, version FROM seat WHERE show_id = ? AND seat_id = ?")) { + read.setString(1, showId); + read.setString(2, seatId); + try (ResultSet rs = read.executeQuery()) { + rs.next(); + if (!isFree(rs.getString("state"), rs.getTimestamp("expires_at"), now)) { + return false; + } + version = rs.getLong("version"); + } + } + try (PreparedStatement write = c.prepareStatement(""" + UPDATE seat SET state = 'HELD', hold_id = ?, expires_at = ?, version = version + 1 + WHERE show_id = ? AND seat_id = ? AND version = ?""")) { + write.setString(1, holdId); + write.setTimestamp(2, Timestamp.from(expiresAt)); + write.setString(3, showId); + write.setString(4, seatId); + write.setLong(5, version); + return write.executeUpdate() == 1; + } + } + } + + /** Strategy 2, pessimistic: lock the row with SELECT ... FOR UPDATE, decide while holding the lock, update, commit. */ + public boolean holdPessimistic(String showId, String seatId, String holdId, Instant now, Instant expiresAt) throws SQLException { + try (Connection c = dataSource.getConnection()) { + c.setAutoCommit(false); + try { + try (PreparedStatement lock = c.prepareStatement( + "SELECT state, expires_at FROM seat WHERE show_id = ? AND seat_id = ? FOR UPDATE")) { + lock.setString(1, showId); + lock.setString(2, seatId); + try (ResultSet rs = lock.executeQuery()) { + rs.next(); + if (!isFree(rs.getString("state"), rs.getTimestamp("expires_at"), now)) { + c.rollback(); + return false; + } + } + } + try (PreparedStatement write = c.prepareStatement(""" + UPDATE seat SET state = 'HELD', hold_id = ?, expires_at = ?, version = version + 1 + WHERE show_id = ? AND seat_id = ?""")) { + write.setString(1, holdId); + write.setTimestamp(2, Timestamp.from(expiresAt)); + write.setString(3, showId); + write.setString(4, seatId); + write.executeUpdate(); + } + c.commit(); + return true; + } catch (SQLException e) { + c.rollback(); + throw e; + } + } + } + + /** Strategy 3, one conditional UPDATE: the "check" is the WHERE clause, so there is no gap between check and act. */ + public boolean holdConditionalUpdate(String showId, String seatId, String holdId, Instant now, Instant expiresAt) throws SQLException { + try (Connection c = dataSource.getConnection(); + PreparedStatement write = c.prepareStatement(""" + UPDATE seat SET state = 'HELD', hold_id = ?, expires_at = ?, version = version + 1 + WHERE show_id = ? AND seat_id = ? + AND (state = 'AVAILABLE' OR (state = 'HELD' AND expires_at <= ?))""")) { + write.setString(1, holdId); + write.setTimestamp(2, Timestamp.from(expiresAt)); + write.setString(3, showId); + write.setString(4, seatId); + write.setTimestamp(5, Timestamp.from(now)); + return write.executeUpdate() == 1; + } + } + + public String stateOf(String showId, String seatId) throws SQLException { + try (Connection c = dataSource.getConnection(); + PreparedStatement q = c.prepareStatement("SELECT state, hold_id, version FROM seat WHERE show_id = ? AND seat_id = ?")) { + q.setString(1, showId); + q.setString(2, seatId); + try (ResultSet rs = q.executeQuery()) { + rs.next(); + return rs.getString("state") + " by " + rs.getString("hold_id") + " v" + rs.getLong("version"); + } + } + } + + private static boolean isFree(String state, Timestamp expiresAt, Instant now) { + return state.equals("AVAILABLE") || (state.equals("HELD") && !now.isBefore(expiresAt.toInstant())); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/MutableClock.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/MutableClock.java new file mode 100644 index 0000000..0c68140 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/MutableClock.java @@ -0,0 +1,39 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.concurrent.atomic.AtomicReference; + +/** + * A clock that only moves when told to. Hold expiry is the part of this design that depends on time, and a test that + * calls {@code Thread.sleep(300000)} to wait out a five-minute hold is not a test anyone runs. + */ +public final class MutableClock extends Clock { + private final AtomicReference now; + + public MutableClock(Instant start) { + this.now = new AtomicReference<>(start); + } + + public void advance(Duration d) { + now.updateAndGet(i -> i.plus(d)); + } + + @Override + public Instant instant() { + return now.get(); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/NaiveInventory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/NaiveInventory.java new file mode 100644 index 0000000..017e125 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/NaiveInventory.java @@ -0,0 +1,88 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The version everyone writes first, and the reason this article exists. + * + *

It uses a {@link ConcurrentHashMap}, so no map operation can corrupt the map. It is still wrong: tryHold + * reads every seat, decides, and only then writes. Two threads can both read AVAILABLE before either + * writes. A thread-safe collection does not make a check-then-act sequence safe. + * + *

The {@link #betweenCheckAndAct(Runnable)} hook is a test seam. It runs exactly in the gap between the check and the + * act, which lets the tests make the race happen on every run instead of once in a few thousand. + */ +public final class NaiveInventory extends AbstractSeatInventory { + private final Map> slots = new ConcurrentHashMap<>(); + private volatile Runnable gap = () -> { }; + + public NaiveInventory(Clock clock) { + super(clock); + } + + public void betweenCheckAndAct(Runnable hook) { + this.gap = hook; + } + + @Override + protected void onRegister(Show show) { + Map m = new ConcurrentHashMap<>(); + show.seatIds().forEach(id -> m.put(id, SeatSlot.initial())); + slots.put(show.id(), m); + } + + @Override + public boolean tryHold(String showId, List seatIds, String holdId, Duration ttl) { + validate(showId, seatIds); + Map m = slots.get(showId); + Instant now = clock.instant(); + for (String id : seatIds) { // CHECK + if (m.get(id).effectiveState(now) != SeatState.AVAILABLE) { + return false; + } + } + gap.run(); // <- another thread can act here + Instant expiresAt = now.plus(ttl); + for (String id : seatIds) { // ACT + m.put(id, m.get(id).held(holdId, expiresAt)); + } + return true; + } + + @Override + public boolean confirm(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + Map m = slots.get(showId); + Instant now = clock.instant(); + for (String id : seatIds) { + if (!m.get(id).isHeldBy(holdId, now)) { + return false; + } + } + for (String id : seatIds) { + m.put(id, m.get(id).booked()); + } + return true; + } + + @Override + public void release(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + Map m = slots.get(showId); + for (String id : seatIds) { + if (m.get(id).ownsHold(holdId)) { + m.put(id, m.get(id).released()); + } + } + } + + @Override + public SeatSlot slot(String showId, String seatId) { + return slots.get(showId).get(seatId); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/OptimisticInventory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/OptimisticInventory.java new file mode 100644 index 0000000..e5b0dad --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/OptimisticInventory.java @@ -0,0 +1,150 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +/** + * "Look, then change it only if nobody else did." No locks at all. Each seat is an {@link AtomicReference} to an + * immutable {@link SeatSlot}; taking a seat is {@code compareAndSet(whatIRead, whatIWant)}, which succeeds only if the + * slot is still exactly the object this thread read. That is the in-memory version of + * {@code UPDATE seat SET ... WHERE id = ? AND version = ?}. + * + *

A multi-seat hold takes the seats one by one. If a later seat is taken, the earlier ones are handed back (also with + * compare-and-set, so only our own holds are undone). That brief "taken then handed back" window is the price of not locking: + * another request can be refused because of a hold that is about to be rolled back. {@link AcquireOrder} shows how much + * this matters. + */ +public final class OptimisticInventory extends AbstractSeatInventory { + private final Map>> refs = new ConcurrentHashMap<>(); + private final AcquireOrder order; + private final AtomicInteger casRetries = new AtomicInteger(); + private volatile Runnable afterFirstAcquire = () -> { }; + private volatile Runnable beforeRollback = () -> { }; + + public OptimisticInventory(Clock clock) { + this(clock, AcquireOrder.SORTED); + } + + public OptimisticInventory(Clock clock, AcquireOrder order) { + super(clock); + this.order = order; + } + + /** Test seam: runs once a request has taken its first seat and before it reaches for the second. */ + public void afterFirstAcquire(Runnable hook) { + this.afterFirstAcquire = hook; + } + + /** Test seam: runs when a request has found a seat taken and is about to hand back the seats it already holds. */ + public void beforeRollback(Runnable hook) { + this.beforeRollback = hook; + } + + /** How many times a compare-and-set lost to a concurrent change and the seat was re-read. Timing dependent. */ + public int casRetries() { + return casRetries.get(); + } + + @Override + protected void onRegister(Show show) { + Map> m = new ConcurrentHashMap<>(); + show.seatIds().forEach(id -> m.put(id, new AtomicReference<>(SeatSlot.initial()))); + refs.put(show.id(), m); + } + + private List ordered(List seatIds) { + List ids = new ArrayList<>(seatIds); + if (order == AcquireOrder.SORTED) { + Collections.sort(ids); + } + return ids; + } + + /** A seat this request has taken, with the exact slot it installed, so that rollback can undo precisely that. */ + private record Taken(AtomicReference ref, SeatSlot installed) { } + + @Override + public boolean tryHold(String showId, List seatIds, String holdId, Duration ttl) { + validate(showId, seatIds); + Instant now = clock.instant(); + Instant expiresAt = now.plus(ttl); + List taken = new ArrayList<>(); + for (String id : ordered(seatIds)) { + AtomicReference ref = refs.get(showId).get(id); + boolean got = false; + while (true) { + SeatSlot seen = ref.get(); // LOOK + if (seen.effectiveState(now) != SeatState.AVAILABLE) { + break; // genuinely taken: give up + } + SeatSlot wanted = seen.held(holdId, expiresAt); + if (ref.compareAndSet(seen, wanted)) { // CHANGE, only if unchanged + taken.add(new Taken(ref, wanted)); + got = true; + break; + } + casRetries.incrementAndGet(); // somebody else moved first: look again + } + if (!got) { + beforeRollback.run(); + rollback(taken, SeatSlot::released); + return false; + } + if (taken.size() == 1) { + afterFirstAcquire.run(); + } + } + return true; + } + + private static void rollback(List taken, java.util.function.UnaryOperator undo) { + for (Taken t : taken) { + t.ref().compareAndSet(t.installed(), undo.apply(t.installed())); + } + } + + @Override + public boolean confirm(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + Instant now = clock.instant(); + List booked = new ArrayList<>(); + for (String id : ordered(seatIds)) { + AtomicReference ref = refs.get(showId).get(id); + SeatSlot seen = ref.get(); + SeatSlot wanted = seen.booked(); + if (!seen.isHeldBy(holdId, now) || !ref.compareAndSet(seen, wanted)) { + rollback(booked, SeatSlot::released); // we own these seats, so freeing them is correct: the booking failed + return false; + } + booked.add(new Taken(ref, wanted)); + } + return true; + } + + @Override + public void release(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + for (String id : seatIds) { + AtomicReference ref = refs.get(showId).get(id); + while (true) { + SeatSlot seen = ref.get(); + if (!seen.ownsHold(holdId) || ref.compareAndSet(seen, seen.released())) { + break; + } + } + } + } + + @Override + public SeatSlot slot(String showId, String seatId) { + return refs.get(showId).get(seatId).get(); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentGateway.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentGateway.java new file mode 100644 index 0000000..3fc3c4a --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentGateway.java @@ -0,0 +1,8 @@ +package com.ankurm.interviewlab.bookmyshow; + +/** The only thing the booking flow needs from a payment provider. Real gateways add idempotency keys and webhooks; see the article. */ +public interface PaymentGateway { + PaymentResult charge(String bookingId, int amountRupees); + + void refund(String bookingId); +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentResult.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentResult.java new file mode 100644 index 0000000..297b570 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PaymentResult.java @@ -0,0 +1,3 @@ +package com.ankurm.interviewlab.bookmyshow; + +public record PaymentResult(boolean success, String reference) { } diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PessimisticInventory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PessimisticInventory.java new file mode 100644 index 0000000..3501f76 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/PessimisticInventory.java @@ -0,0 +1,186 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; + +/** + * "Lock before you look." Every seat has its own lock; a request takes the locks of all its seats, checks them all, + * writes them all, and unlocks. While it holds the locks nobody else can read-then-write the same seats, so the + * check-then-act gap of {@link NaiveInventory} is closed. + * + *

Taking several locks introduces a new failure: deadlock. {@link AcquireOrder#SORTED} prevents it by making every + * request lock in the same global order. {@link AcquireOrder#AS_REQUESTED} exists so the tests can show the deadlock; + * it uses {@code tryLock} with a timeout so that a demonstration ends instead of hanging, and counts how often that + * happened in {@link #lockTimeouts()}. + */ +public final class PessimisticInventory extends AbstractSeatInventory { + + /** A seat plus its lock. {@code slot} is only read or written while {@code lock} is held. */ + private static final class Cell { + final ReentrantLock lock = new ReentrantLock(); + SeatSlot slot = SeatSlot.initial(); + } + + private final Map> cells = new ConcurrentHashMap<>(); + private final AcquireOrder order; + private final Duration lockWait; + private final AtomicInteger lockTimeouts = new AtomicInteger(); + private volatile Runnable afterFirstLock = () -> { }; + + public PessimisticInventory(Clock clock) { + this(clock, AcquireOrder.SORTED, Duration.ofSeconds(5)); + } + + public PessimisticInventory(Clock clock, AcquireOrder order, Duration lockWait) { + super(clock); + this.order = order; + this.lockWait = lockWait; + } + + /** Test seam: runs once a request holds its first lock and before it asks for the second. */ + public void afterFirstLock(Runnable hook) { + this.afterFirstLock = hook; + } + + public int lockTimeouts() { + return lockTimeouts.get(); + } + + @Override + protected void onRegister(Show show) { + Map m = new ConcurrentHashMap<>(); + show.seatIds().forEach(id -> m.put(id, new Cell())); + cells.put(show.id(), m); + } + + /** Locks the cells in the configured order; returns null (holding nothing) if a lock could not be had in time. */ + private List lockAll(String showId, List seatIds) throws InterruptedException { + List ids = new ArrayList<>(seatIds); + if (order == AcquireOrder.SORTED) { + Collections.sort(ids); + } + List locked = new ArrayList<>(); + for (String id : ids) { + Cell c = cells.get(showId).get(id); + if (!c.lock.tryLock(lockWait.toMillis(), TimeUnit.MILLISECONDS)) { + lockTimeouts.incrementAndGet(); + unlockAll(locked); + return null; + } + locked.add(c); + if (locked.size() == 1) { + afterFirstLock.run(); + } + } + return locked; + } + + private static void unlockAll(List locked) { + for (Cell c : locked) { + c.lock.unlock(); + } + } + + @Override + public boolean tryHold(String showId, List seatIds, String holdId, Duration ttl) { + validate(showId, seatIds); + List locked; + try { + locked = lockAll(showId, seatIds); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + if (locked == null) { + return false; + } + try { + Instant now = clock.instant(); + for (Cell c : locked) { + if (c.slot.effectiveState(now) != SeatState.AVAILABLE) { + return false; // nothing was written yet, so there is nothing to undo + } + } + Instant expiresAt = now.plus(ttl); + for (Cell c : locked) { + c.slot = c.slot.held(holdId, expiresAt); + } + return true; + } finally { + unlockAll(locked); + } + } + + @Override + public boolean confirm(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + List locked; + try { + locked = lockAll(showId, seatIds); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + if (locked == null) { + return false; + } + try { + Instant now = clock.instant(); + for (Cell c : locked) { + if (!c.slot.isHeldBy(holdId, now)) { + return false; + } + } + for (Cell c : locked) { + c.slot = c.slot.booked(); + } + return true; + } finally { + unlockAll(locked); + } + } + + @Override + public void release(String showId, List seatIds, String holdId) { + validate(showId, seatIds); + List locked; + try { + locked = lockAll(showId, seatIds); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + if (locked == null) { + return; + } + try { + for (Cell c : locked) { + if (c.slot.ownsHold(holdId)) { + c.slot = c.slot.released(); + } + } + } finally { + unlockAll(locked); + } + } + + @Override + public SeatSlot slot(String showId, String seatId) { + Cell c = cells.get(showId).get(seatId); + c.lock.lock(); + try { + return c.slot; + } finally { + c.lock.unlock(); + } + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Seat.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Seat.java new file mode 100644 index 0000000..5aadb2e --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Seat.java @@ -0,0 +1,3 @@ +package com.ankurm.interviewlab.bookmyshow; + +public record Seat(String id, SeatCategory category, int priceRupees) {} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatCategory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatCategory.java new file mode 100644 index 0000000..d1bd942 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatCategory.java @@ -0,0 +1,3 @@ +package com.ankurm.interviewlab.bookmyshow; + +public enum SeatCategory { REGULAR, PREMIUM, RECLINER } diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatInventory.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatInventory.java new file mode 100644 index 0000000..7f9b679 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatInventory.java @@ -0,0 +1,47 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Clock; +import java.time.Duration; +import java.util.List; +import java.util.Map; + +/** + * Owns the state of every seat of every registered show, and is the only place where seat state changes. + * Everything concurrent about BookMyShow lives behind these methods; {@link BookingService} stays single-minded. + * + *

Contract shared by all implementations (pinned by the tests): + *

    + *
  • {@link #tryHold} is all-or-nothing: either every requested seat becomes HELD for {@code holdId}, or none changes + * value that a reader could observe as "held".
  • + *
  • Seat ids must be known to the show and distinct, otherwise {@link IllegalArgumentException}.
  • + *
  • {@link #confirm} and {@link #release} only act on holds owned by {@code holdId}.
  • + *
+ */ +public interface SeatInventory { + + void register(Show show); + + Show show(String showId); + + Clock clock(); + + /** Attempts to hold every seat for {@code holdId} for {@code ttl}. Returns false, changing nothing observable, if any seat is taken. */ + boolean tryHold(String showId, List seatIds, String holdId, Duration ttl); + + /** Turns {@code holdId}'s unexpired holds on all these seats into BOOKED. False (and nothing booked) if any hold is missing, expired or not owned. */ + boolean confirm(String showId, List seatIds, String holdId); + + /** Frees the seats that {@code holdId} still holds. Seats held by anyone else, or already booked, are left alone. */ + void release(String showId, List seatIds, String holdId); + + /** The raw slot, including a HELD value that may be past its expiry. */ + SeatSlot slot(String showId, String seatId); + + /** The state a reader should believe right now, with expiry applied. */ + default SeatState stateOf(String showId, String seatId) { + return slot(showId, seatId).effectiveState(clock().instant()); + } + + /** Count of seats per effective state for one show. */ + Map summary(String showId); +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatSlot.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatSlot.java new file mode 100644 index 0000000..28e3f60 --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatSlot.java @@ -0,0 +1,56 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Instant; + +/** + * The whole mutable truth about one seat of one show, as one immutable value. + * + *

Making it immutable is what lets {@link OptimisticInventory} use compare-and-set: "replace this exact + * object with that one" is a complete, atomic description of a seat changing state. Every transition bumps + * {@code version}, which is the same idea as the version column of a database row. + * + * @param state what the slot says. Note that a HELD slot whose time has passed is effectively available; + * see {@link #effectiveState(Instant)}. + * @param holdId who owns the hold or the booking (a booking id), null while AVAILABLE + * @param expiresAt when a HELD slot stops counting, null otherwise + * @param version number of transitions this seat has been through + */ +public record SeatSlot(SeatState state, String holdId, Instant expiresAt, long version) { + + public static SeatSlot initial() { + return new SeatSlot(SeatState.AVAILABLE, null, null, 0); + } + + /** + * What a reader should believe at {@code now}. A hold is valid strictly before {@code expiresAt}; at the + * expiry instant itself it is already gone. Expiry is lazy: nothing rewrites the slot, readers just do this check. + */ + public SeatState effectiveState(Instant now) { + if (state == SeatState.HELD && !now.isBefore(expiresAt)) { + return SeatState.AVAILABLE; + } + return state; + } + + /** True when {@code holdId} owns a hold that has not expired at {@code now}. This is the check confirm() relies on. */ + public boolean isHeldBy(String holdId, Instant now) { + return state == SeatState.HELD && this.holdId.equals(holdId) && now.isBefore(expiresAt); + } + + /** True when {@code holdId} wrote this hold, expired or not. release() uses this so it can never free someone else's seat. */ + public boolean ownsHold(String holdId) { + return state == SeatState.HELD && this.holdId.equals(holdId); + } + + public SeatSlot held(String holdId, Instant expiresAt) { + return new SeatSlot(SeatState.HELD, holdId, expiresAt, version + 1); + } + + public SeatSlot booked() { + return new SeatSlot(SeatState.BOOKED, holdId, null, version + 1); + } + + public SeatSlot released() { + return new SeatSlot(SeatState.AVAILABLE, null, null, version + 1); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatState.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatState.java new file mode 100644 index 0000000..894aeda --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatState.java @@ -0,0 +1,11 @@ +package com.ankurm.interviewlab.bookmyshow; + +/** The three states a seat can be in for one show. A seat has no "locked" state: a lock is a way of changing state, not a state. */ +public enum SeatState { + /** Nobody has a claim on the seat. */ + AVAILABLE, + /** Someone is paying for it. The claim expires at {@link SeatSlot#expiresAt()}. */ + HELD, + /** Paid for. Permanent for this module (cancellation of confirmed bookings is out of scope). */ + BOOKED +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatUnavailableException.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatUnavailableException.java new file mode 100644 index 0000000..2d958af --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/SeatUnavailableException.java @@ -0,0 +1,10 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.util.List; + +/** Thrown by {@link BookingService#startBooking} when at least one requested seat is held or booked by someone else. */ +public class SeatUnavailableException extends RuntimeException { + public SeatUnavailableException(String showId, List seatIds) { + super("seats not available for show " + showId + ": " + seatIds); + } +} diff --git a/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Show.java b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Show.java new file mode 100644 index 0000000..c88506b --- /dev/null +++ b/bookmyshow/src/main/java/com/ankurm/interviewlab/bookmyshow/Show.java @@ -0,0 +1,70 @@ +package com.ankurm.interviewlab.bookmyshow; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** One screening of one movie on one screen. Seats are fixed at construction; their state lives in a {@link SeatInventory}. */ +public final class Show { + private final String id; + private final String movie; + private final String screen; + private final Instant startsAt; + private final Map seatsById; + private final List orderedIds; + + public Show(String id, String movie, String screen, Instant startsAt, List seats) { + this.id = id; + this.movie = movie; + this.screen = screen; + this.startsAt = startsAt; + Map m = new LinkedHashMap<>(); + for (Seat s : seats) { + m.put(s.id(), s); + } + this.seatsById = Map.copyOf(m); + this.orderedIds = List.copyOf(m.keySet()); + } + + /** + * Builds a rows x cols grid with ids A1..A10, B1..B10 and so on. The last row is RECLINER, the one before it + * PREMIUM, everything above REGULAR, so a booking's price depends on which seats it contains. + */ + public static Show grid(String id, String movie, String screen, Instant startsAt, int rows, int cols) { + if (rows < 3) { + throw new IllegalArgumentException("need at least 3 rows"); + } + List seats = new java.util.ArrayList<>(); + for (int r = 0; r < rows; r++) { + char letter = (char) ('A' + r); + SeatCategory cat = r == rows - 1 ? SeatCategory.RECLINER : r == rows - 2 ? SeatCategory.PREMIUM : SeatCategory.REGULAR; + int price = switch (cat) { + case REGULAR -> 220; + case PREMIUM -> 350; + case RECLINER -> 600; + }; + for (int c = 1; c <= cols; c++) { + seats.add(new Seat("" + letter + c, cat, price)); + } + } + return new Show(id, movie, screen, startsAt, seats); + } + + public String id() { return id; } + public String movie() { return movie; } + public String screen() { return screen; } + public Instant startsAt() { return startsAt; } + public boolean hasSeat(String seatId) { return seatsById.containsKey(seatId); } + public Seat seat(String seatId) { return seatsById.get(seatId); } + /** Seat ids in construction order (row by row). */ + public List seatIds() { return orderedIds; } + + public int priceOf(List seatIds) { + int total = 0; + for (String s : seatIds) { + total += seat(s).priceRupees(); + } + return total; + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ContentionTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ContentionTest.java new file mode 100644 index 0000000..cd2f01d --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ContentionTest.java @@ -0,0 +1,180 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Section 7: many threads, no barriers inside the inventories. What must stay true however the threads interleave. */ +class ContentionTest { + private static final Duration TTL = Duration.ofMinutes(5); + private static final int THREADS = 200; + private static final int ROUNDS = 30; + + /** Releases all tasks at once on platform threads (virtual threads mostly ran one after another on this 2-vCPU box) and returns when every one has finished. */ + private static void stampede(List tasks) throws Exception { + CountDownLatch go = new CountDownLatch(1); + try (ExecutorService pool = Executors.newThreadPerTaskExecutor(Thread.ofPlatform().name("stampede-", 0).factory())) { + List> fs = new ArrayList<>(); + for (Runnable r : tasks) { + fs.add(pool.submit(() -> { + go.await(); + r.run(); + return null; + })); + } + go.countDown(); + for (Future f : fs) { + f.get(60, TimeUnit.SECONDS); + } + } + } + + /** Runs ROUNDS stampedes of THREADS threads at one seat; returns how many rounds ended with exactly one winner. */ + private static int roundsWithExactlyOneWinner(String inventoryName) throws Exception { + int exactlyOne = 0; + for (int round = 0; round < ROUNDS; round++) { + SeatInventory inv = Fixtures.fresh(inventoryName, Fixtures.clock()); + AtomicInteger winners = new AtomicInteger(); + List tasks = new ArrayList<>(); + for (int i = 0; i < THREADS; i++) { + String holdId = "H" + i; + tasks.add(() -> { + if (inv.tryHold(SHOW_ID, List.of("D4"), holdId, TTL)) { + winners.incrementAndGet(); + } + }); + } + stampede(tasks); + if (winners.get() == 1) { + exactlyOne++; + } + } + return exactlyOne; + } + + @Test + void twoHundredThreadsOneSeat() throws Exception { + Transcript t = Transcript.start("04-contention.txt", + THREADS + " threads released at once, all asking for seat D4, repeated " + ROUNDS + " times per inventory"); + int pess = roundsWithExactlyOneWinner("PessimisticInventory"); + int opt = roundsWithExactlyOneWinner("OptimisticInventory"); + assertEquals(ROUNDS, pess); + assertEquals(ROUNDS, opt); + t.line("PessimisticInventory: rounds with exactly one winner: " + pess + " of " + ROUNDS); + t.line("OptimisticInventory: rounds with exactly one winner: " + opt + " of " + ROUNDS); + + int naive = roundsWithExactlyOneWinner("NaiveInventory"); + t.blank(); + t.line("Control, not asserted and timing dependent: NaiveInventory, no barrier inside it:"); + t.line("NaiveInventory: rounds with exactly one winner: " + naive + " of " + ROUNDS); + t.flush(); + } + + private record Request(String holdId, List seats) { } + + private static List plan(long seed, int requests, int maxSeats, List seatIds) { + Random rnd = new Random(seed); + List plan = new ArrayList<>(); + for (int i = 0; i < requests; i++) { + int n = 1 + rnd.nextInt(maxSeats); + Set pick = new java.util.LinkedHashSet<>(); + while (pick.size() < n) { + pick.add(seatIds.get(rnd.nextInt(seatIds.size()))); + } + plan.add(new Request("R" + i, List.copyOf(pick))); + } + return plan; + } + + @Test + void manyUsersRandomSeatsKeepTheInvariants() throws Exception { + List seatIds = Fixtures.show().seatIds(); + List plan = plan(20261120L, 400, 3, seatIds); + int seatsRequested = plan.stream().mapToInt(r -> r.seats().size()).sum(); + + Transcript t = Transcript.start("05-random-seats.txt", + "400 users, each asking for 1 to 3 random seats of a 60-seat show (seeded plan), all released at once"); + t.line("seats requested in total (seeded, identical for every inventory): " + seatsRequested); + + record Variant(String label, Supplier make) { } + List variants = List.of( + new Variant("PessimisticInventory, SORTED", () -> { + SeatInventory i = new PessimisticInventory(Fixtures.clock()); + i.register(Fixtures.show()); + return i; + }), + new Variant("OptimisticInventory, SORTED", () -> { + SeatInventory i = new OptimisticInventory(Fixtures.clock(), AcquireOrder.SORTED); + i.register(Fixtures.show()); + return i; + }), + new Variant("OptimisticInventory, AS_REQUESTED", () -> { + SeatInventory i = new OptimisticInventory(Fixtures.clock(), AcquireOrder.AS_REQUESTED); + i.register(Fixtures.show()); + return i; + })); + + for (Variant v : variants) { + SeatInventory inv = v.make().get(); + List granted = java.util.Collections.synchronizedList(new ArrayList<>()); + List tasks = new ArrayList<>(); + for (Request r : plan) { + tasks.add(() -> { + if (inv.tryHold(SHOW_ID, r.seats(), r.holdId(), TTL)) { + granted.add(r); + } + }); + } + stampede(tasks); + + Set seen = new HashSet<>(); + boolean noSeatTwice = true; + boolean ownsItsSeats = true; + int grantedSeats = 0; + for (Request r : granted) { + for (String s : r.seats()) { + noSeatTwice &= seen.add(s); + SeatSlot slot = inv.slot(SHOW_ID, s); + ownsItsSeats &= slot.state() == SeatState.HELD && slot.holdId().equals(r.holdId()); + grantedSeats++; + } + } + long held = inv.summary(SHOW_ID).get(SeatState.HELD); + long available = inv.summary(SHOW_ID).get(SeatState.AVAILABLE); + assertTrue(noSeatTwice); + assertTrue(ownsItsSeats); + assertEquals(grantedSeats, held); + assertEquals(60 - grantedSeats, available); + assertTrue(!granted.isEmpty()); + + t.blank(); + t.line(v.label() + ":"); + t.line(" no seat granted to two requests: " + noSeatTwice); + t.line(" every granted request owns all of its seats: " + ownsItsSeats); + t.line(" HELD seats == seats of granted requests: " + (held == grantedSeats)); + t.line(" AVAILABLE + HELD == 60: " + (available + held == 60)); + } + t.blank(); + t.line("How many requests were granted differs from run to run (it depends on the interleaving) and is deliberately not printed."); + t.flush(); + } + +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/DatabaseSeatTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/DatabaseSeatTest.java new file mode 100644 index 0000000..32c6510 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/DatabaseSeatTest.java @@ -0,0 +1,84 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.h2.jdbcx.JdbcDataSource; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.ankurm.interviewlab.bookmyshow.RaceConditionTest.runTogether; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Section 10: the same three-way question against a real SQL database (H2 in memory, several connections). */ +class DatabaseSeatTest { + private interface Hold { + boolean run(JdbcSeatStore store, String holdId, Instant now, Instant exp) throws Exception; + } + + private static int roundsWithExactlyOneWinner(JdbcSeatStore store, Hold strategy, int threads, int rounds) throws Exception { + int ok = 0; + Instant now = Instant.parse("2026-11-20T10:00:00Z"); + Instant exp = now.plus(Duration.ofMinutes(5)); + for (int r = 0; r < rounds; r++) { + store.resetSeat("SH-1", "D4"); + AtomicInteger winners = new AtomicInteger(); + List> tasks = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + String holdId = "H" + i; + tasks.add(() -> { + if (strategy.run(store, holdId, now, exp)) { + winners.incrementAndGet(); + } + return null; + }); + } + runTogether(tasks); + if (winners.get() == 1) { + ok++; + } + } + return ok; + } + + @Test + void sameSeatThreeSqlStrategies() throws Exception { + JdbcDataSource ds = new JdbcDataSource(); + ds.setURL("jdbc:h2:mem:bookmyshow;DB_CLOSE_DELAY=-1"); + JdbcSeatStore store = new JdbcSeatStore(ds); + store.createSchema(); + + int threads = 32; + int rounds = 20; + int optimistic = roundsWithExactlyOneWinner(store, + (s, h, n, e) -> s.holdOptimistic("SH-1", "D4", h, n, e), threads, rounds); + int pessimistic = roundsWithExactlyOneWinner(store, + (s, h, n, e) -> s.holdPessimistic("SH-1", "D4", h, n, e), threads, rounds); + int conditional = roundsWithExactlyOneWinner(store, + (s, h, n, e) -> s.holdConditionalUpdate("SH-1", "D4", h, n, e), threads, rounds); + assertEquals(rounds, optimistic); + assertEquals(rounds, pessimistic); + assertEquals(rounds, conditional); + + Transcript t = Transcript.start("08-database-strategies.txt", + threads + " connections released at once, all holding seat D4 of SH-1, repeated " + rounds + " times per strategy (H2 " + h2Version() + ")"); + t.line("optimistic (SELECT, then UPDATE ... WHERE version = ?): rounds with exactly one winner: " + optimistic + " of " + rounds); + t.line("pessimistic (SELECT ... FOR UPDATE, then UPDATE): rounds with exactly one winner: " + pessimistic + " of " + rounds); + t.line("conditional (one UPDATE ... WHERE state = 'AVAILABLE'): rounds with exactly one winner: " + conditional + " of " + rounds); + + int naive = roundsWithExactlyOneWinner(store, + (s, h, n, e) -> s.holdNaive("SH-1", "D4", h, n, e), threads, rounds); + t.blank(); + t.line("Control, not asserted and timing dependent:"); + t.line("naive (SELECT, then UPDATE with no version or lock): rounds with exactly one winner: " + naive + " of " + rounds); + t.flush(); + } + + private static String h2Version() { + return org.h2.engine.Constants.VERSION; + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ExpiryAndPaymentTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ExpiryAndPaymentTest.java new file mode 100644 index 0000000..db19a08 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/ExpiryAndPaymentTest.java @@ -0,0 +1,139 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.describe; +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.t; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Section 8: a hold is a promise with a deadline, and payment is slow. Fake clock, no sleeping. */ +class ExpiryAndPaymentTest { + private static final Duration TTL = Duration.ofMinutes(5); + + private static String now(MutableClock c) { + return t(c.instant()); + } + + private static List scenarios(String inventoryName) { + List log = new ArrayList<>(); + + // 1. paying just inside the deadline --------------------------------------------------------------- + { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(inventoryName, clock); + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking b = svc.startBooking("asha", SHOW_ID, List.of("B1")); + clock.advance(Duration.ofMinutes(4).plusSeconds(59)); + BookingOutcome o = svc.pay(b.id()); + log.add("1. Pay one second before the deadline"); + log.add(" hold placed " + t(b.heldAt()) + ", expires " + t(b.expiresAt()) + ", pay pressed " + now(clock)); + log.add(" outcome: " + o + " charges: " + pay.charges() + " refunds: " + pay.refunds().size()); + assertEquals(BookingOutcome.CONFIRMED, o); + } + + // 2. the deadline passes, someone else takes the seat, the first user comes back ---------------------- + { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(inventoryName, clock); + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking asha = svc.startBooking("asha", SHOW_ID, List.of("B1", "B2")); + clock.advance(Duration.ofMinutes(4).plusSeconds(59)); + log.add("2. The deadline passes while Asha is on the payment page (she holds B1 and B2)"); + log.add(" " + now(clock) + " B1 reads as " + inv.stateOf(SHOW_ID, "B1")); + clock.advance(Duration.ofSeconds(1)); + log.add(" " + now(clock) + " B1 reads as " + inv.stateOf(SHOW_ID, "B1") + + " (stored slot still says " + inv.slot(SHOW_ID, "B1").state() + ": expiry is lazy)"); + clock.advance(Duration.ofSeconds(1)); + Booking ravi = svc.startBooking("ravi", SHOW_ID, List.of("B1")); + log.add(" " + now(clock) + " Ravi asks for B1: " + ravi.id() + " " + ravi.status()); + clock.advance(Duration.ofSeconds(1)); + BookingOutcome o = svc.pay(asha.id()); + log.add(" " + now(clock) + " Asha presses Pay: " + o + " charges: " + pay.charges()); + log.add(" B1: " + describe(inv.slot(SHOW_ID, "B1"))); + log.add(" B2: " + describe(inv.slot(SHOW_ID, "B2"))); + assertEquals(BookingOutcome.HOLD_EXPIRED_BEFORE_PAYMENT, o); + assertEquals(0, pay.charges()); + assertEquals("BK-0002", inv.slot(SHOW_ID, "B1").holdId()); + } + + // 3. payment is slow and the hold runs out while the bank is thinking -------------------------------- + { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(inventoryName, clock); + FakePaymentGateway pay = new FakePaymentGateway(); + pay.duringCharge(() -> clock.advance(Duration.ofMinutes(2))); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking asha = svc.startBooking("asha", SHOW_ID, List.of("B3")); + clock.advance(Duration.ofMinutes(4).plusSeconds(59)); + log.add("3. Pay pressed at " + now(clock) + ", the gateway takes two minutes, nobody else wants the seat"); + BookingOutcome o = svc.pay(asha.id()); + log.add(" outcome: " + o + " charges: " + pay.charges() + " refunds: " + pay.refunds() + + " booking: " + svc.booking(asha.id()).status()); + assertEquals(BookingOutcome.HOLD_LOST_AFTER_PAYMENT, o); + assertEquals(1, pay.charges()); + assertEquals(1, pay.refunds().size()); + } + + // 4. same, but Ravi grabs the seat while the bank is thinking --------------------------------------- + { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(inventoryName, clock); + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking asha = svc.startBooking("asha", SHOW_ID, List.of("B4")); + pay.duringCharge(() -> { + clock.advance(Duration.ofMinutes(2)); + svc.startBooking("ravi", SHOW_ID, List.of("B4")); + }); + clock.advance(Duration.ofMinutes(4).plusSeconds(59)); + log.add("4. Same slow payment, but Ravi takes B4 while the gateway is still working on Asha's charge"); + BookingOutcome o = svc.pay(asha.id()); + log.add(" outcome: " + o + " charges: " + pay.charges() + " refunds: " + pay.refunds() + + " booking: " + svc.booking(asha.id()).status()); + log.add(" B4: " + describe(inv.slot(SHOW_ID, "B4"))); + assertEquals(BookingOutcome.HOLD_LOST_AFTER_PAYMENT, o); + assertEquals("BK-0002", inv.slot(SHOW_ID, "B4").holdId()); + } + + // 5. card declined ------------------------------------------------------------------------------------- + { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(inventoryName, clock); + FakePaymentGateway pay = new FakePaymentGateway(); + pay.declineNext(); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking asha = svc.startBooking("asha", SHOW_ID, List.of("B5")); + BookingOutcome o = svc.pay(asha.id()); + log.add("5. The card is declined"); + log.add(" outcome: " + o + " booking: " + svc.booking(asha.id()).status() + " B5 now: " + inv.stateOf(SHOW_ID, "B5")); + assertEquals(BookingOutcome.PAYMENT_DECLINED, o); + assertEquals(SeatState.AVAILABLE, inv.stateOf(SHOW_ID, "B5")); + } + return log; + } + + @Test + void holdExpiryAndPaymentTimeout() { + List> logs = new ArrayList<>(); + for (String name : Fixtures.NAMES) { + logs.add(scenarios(name)); + } + assertEquals(logs.get(0), logs.get(1)); + assertEquals(logs.get(0), logs.get(2)); + + Transcript tr = Transcript.start("06-expiry-and-payment.txt", + "Hold expiry and payment timeout on a fake clock (TTL 5 minutes, no sleeping)"); + logs.get(0).forEach(tr::line); + tr.blank().line("Same log produced by all three inventories: true"); + tr.flush(); + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/HappyPathTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/HappyPathTest.java new file mode 100644 index 0000000..5802494 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/HappyPathTest.java @@ -0,0 +1,63 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.describe; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Section 3 of the article: with one user at a time, all three inventories behave identically. */ +class HappyPathTest { + + private static List run(SeatInventory inv, MutableClock clock) { + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, Duration.ofMinutes(5)); + List log = new ArrayList<>(); + log.add("A1 at the start: " + describe(inv.slot(SHOW_ID, "A1"))); + + Booking b = svc.startBooking("asha", SHOW_ID, List.of("A1", "A2")); + log.add("startBooking(asha, A1+A2): " + b.id() + " " + b.status() + ", Rs " + b.amountRupees()); + log.add("A1 after the hold: " + describe(inv.slot(SHOW_ID, "A1"))); + log.add("A3 untouched: " + describe(inv.slot(SHOW_ID, "A3"))); + + try { + svc.startBooking("ravi", SHOW_ID, List.of("A2", "A3")); + } catch (SeatUnavailableException e) { + log.add("startBooking(ravi, A2+A3): refused (" + e.getMessage() + ")"); + } + log.add("A3 after ravi's refusal: " + describe(inv.slot(SHOW_ID, "A3"))); + + BookingOutcome outcome = svc.pay(b.id()); + log.add("pay(" + b.id() + "): " + outcome + ", booking is " + svc.booking(b.id()).status()); + log.add("A1 after payment: " + describe(inv.slot(SHOW_ID, "A1"))); + log.add("seat summary: " + Fixtures.summaryAsStrings(inv, SHOW_ID)); + return log; + } + + @Test + void singleThreadedFlowIsIdenticalAcrossImplementations() { + List> logs = new ArrayList<>(); + for (String name : Fixtures.NAMES) { + MutableClock clock = Fixtures.clock(); + logs.add(run(Fixtures.fresh(name, clock), clock)); + } + assertEquals(logs.get(0), logs.get(1)); + assertEquals(logs.get(0), logs.get(2)); + + List log = logs.get(0); + assertTrue(log.get(8).endsWith("{AVAILABLE=58, BOOKED=2, HELD=0}"), log.get(8)); + + Transcript t = Transcript.start("01-happy-path.txt", + "Happy path, one user at a time (show SH-1, 60 seats, hold TTL 5 minutes)"); + log.forEach(t::line); + t.blank().line("Same log produced by NaiveInventory, PessimisticInventory and OptimisticInventory: true"); + t.flush(); + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/LockOrderingTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/LockOrderingTest.java new file mode 100644 index 0000000..aea06cc --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/LockOrderingTest.java @@ -0,0 +1,107 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; + +import static com.ankurm.interviewlab.bookmyshow.RaceConditionTest.runTogether; +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Sections 5 and 6: the order in which a request touches several seats decides whether pessimistic locking deadlocks + * and whether optimistic holding refuses two requests that could have been served one after the other. + */ +class LockOrderingTest { + private static final Duration TTL = Duration.ofMinutes(5); + + private static Runnable barrier(CyclicBarrier b) { + return () -> { + try { + b.await(10, TimeUnit.SECONDS); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }; + } + + private static List> twoCrossedRequests(SeatInventory inv) { + return List.of( + () -> inv.tryHold(SHOW_ID, List.of("A1", "A2"), "H1", TTL), + () -> inv.tryHold(SHOW_ID, List.of("A2", "A1"), "H2", TTL)); + } + + @Test + void orderMattersForBothFamilies() throws Exception { + Transcript t = Transcript.start("03-lock-ordering.txt", + "Two requests for the same two seats, listed in opposite order: H1 asks [A1, A2], H2 asks [A2, A1]"); + + // --- pessimistic, locks taken in the order requested --------------------------------------------------- + MutableClock c1 = Fixtures.clock(); + PessimisticInventory unsorted = new PessimisticInventory(c1, AcquireOrder.AS_REQUESTED, Duration.ofMillis(300)); + unsorted.register(Fixtures.show()); + unsorted.afterFirstLock(barrier(new CyclicBarrier(2))); + long started = System.nanoTime(); + List r1 = runTogether(twoCrossedRequests(unsorted)); + long stalledMillis = (System.nanoTime() - started) / 1_000_000; + long succeeded = r1.stream().filter(b -> b).count(); + assertTrue(stalledMillis >= 290, "both threads were stuck until a lock wait timed out, took " + stalledMillis + " ms"); + assertTrue(unsorted.lockTimeouts() >= 1); + assertTrue(succeeded <= 1); + t.line("PessimisticInventory, AS_REQUESTED (each thread holds one lock, then waits for the other's):"); + t.line(" stuck until a lock wait timed out (300 ms): true"); + t.line(" at least one lock wait timed out: " + (unsorted.lockTimeouts() >= 1)); + t.line(" requests that succeeded: at most 1 (never both; which one is timing dependent)"); + t.line(" Without the timeout both threads would wait forever."); + + // --- pessimistic, sorted ------------------------------------------------------------------------------- + PessimisticInventory sorted = new PessimisticInventory(Fixtures.clock(), AcquireOrder.SORTED, Duration.ofMillis(300)); + sorted.register(Fixtures.show()); + List r2 = runTogether(twoCrossedRequests(sorted)); + assertEquals(1, r2.stream().filter(b -> b).count()); + assertEquals(0, sorted.lockTimeouts()); + t.blank(); + t.line("PessimisticInventory, SORTED (both requests lock A1 first, so one simply waits):"); + t.line(" requests that succeeded: " + r2.stream().filter(b -> b).count() + " of 2"); + t.line(" lock waits that timed out: " + sorted.lockTimeouts()); + + // --- optimistic, taken in the order requested ---------------------------------------------------------- + OptimisticInventory optUnsorted = new OptimisticInventory(Fixtures.clock(), AcquireOrder.AS_REQUESTED); + optUnsorted.register(Fixtures.show()); + optUnsorted.afterFirstAcquire(barrier(new CyclicBarrier(2))); + optUnsorted.beforeRollback(barrier(new CyclicBarrier(2))); // second barrier: both see the other's seat before either hands its own back + List r3 = runTogether(twoCrossedRequests(optUnsorted)); + assertEquals(List.of(false, false), r3); + assertEquals(SeatState.AVAILABLE, optUnsorted.stateOf(SHOW_ID, "A1")); + assertEquals(SeatState.AVAILABLE, optUnsorted.stateOf(SHOW_ID, "A2")); + long v1 = optUnsorted.slot(SHOW_ID, "A1").version(); + long v2 = optUnsorted.slot(SHOW_ID, "A2").version(); + assertEquals(2, v1); + assertEquals(2, v2); + t.blank(); + t.line("OptimisticInventory, AS_REQUESTED (each request takes one seat, then finds the other taken):"); + t.line(" results: " + r3); + t.line(" A1 / A2 afterwards: " + optUnsorted.stateOf(SHOW_ID, "A1") + " / " + optUnsorted.stateOf(SHOW_ID, "A2") + + " (versions v" + v1 + " / v" + v2 + ": held, then handed back)"); + t.line(" Both seats are free and both customers were turned away."); + + // --- optimistic, sorted -------------------------------------------------------------------------------- + OptimisticInventory optSorted = new OptimisticInventory(Fixtures.clock(), AcquireOrder.SORTED); + optSorted.register(Fixtures.show()); + List r4 = runTogether(twoCrossedRequests(optSorted)); + assertEquals(1, r4.stream().filter(b -> b).count()); + t.blank(); + t.line("OptimisticInventory, SORTED (both start at A1, so only one can get past the first seat):"); + t.line(" requests that succeeded: " + r4.stream().filter(b -> b).count() + " of 2"); + assertTrue(optSorted.summary(SHOW_ID).get(SeatState.HELD) == 2); + t.line(" HELD seats afterwards: " + optSorted.summary(SHOW_ID).get(SeatState.HELD)); + t.flush(); + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/PitfallsTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/PitfallsTest.java new file mode 100644 index 0000000..f633eb5 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/PitfallsTest.java @@ -0,0 +1,124 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.ankurm.interviewlab.bookmyshow.RaceConditionTest.runTogether; +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Section 9: the quiet mistakes. Each test pins one behaviour of the correct implementations. */ +class PitfallsTest { + private static final Duration TTL = Duration.ofMinutes(5); + + @Test + void pitfalls() throws Exception { + Transcript t = Transcript.start("07-pitfalls.txt", "Pitfalls: partial holds, foreign releases, bad input, double Pay"); + + // 1. a multi-seat request that fails half way must leave nothing behind --------------------------------- + t.line("1. Request [A1, A2, A3] while someone else holds A3"); + for (String name : Fixtures.NAMES) { + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh(name, clock); + assertTrue(inv.tryHold(SHOW_ID, List.of("A3"), "OTHER", TTL)); + boolean ok = inv.tryHold(SHOW_ID, List.of("A1", "A2", "A3"), "ME", TTL); + assertFalse(ok); + assertEquals(SeatState.AVAILABLE, inv.stateOf(SHOW_ID, "A1")); + assertEquals(SeatState.AVAILABLE, inv.stateOf(SHOW_ID, "A2")); + t.line(" %-21s result %-5s A1 %-9s v%d A2 %-9s v%d".formatted(name, ok, + inv.stateOf(SHOW_ID, "A1"), inv.slot(SHOW_ID, "A1").version(), + inv.stateOf(SHOW_ID, "A2"), inv.slot(SHOW_ID, "A2").version())); + } + t.line(" (v0 means the seat was never touched; v2 means it was held and handed back during the attempt)"); + + // 2. release and confirm only work on your own hold ---------------------------------------------------- + t.blank(); + t.line("2. Someone who does not own the hold tries to release or confirm it"); + for (String name : Fixtures.NAMES) { + SeatInventory inv = Fixtures.fresh(name, Fixtures.clock()); + assertTrue(inv.tryHold(SHOW_ID, List.of("C1"), "ASHA", TTL)); + inv.release(SHOW_ID, List.of("C1"), "RAVI"); + boolean foreignConfirm = inv.confirm(SHOW_ID, List.of("C1"), "RAVI"); + assertFalse(foreignConfirm); + assertEquals("ASHA", inv.slot(SHOW_ID, "C1").holdId()); + assertEquals(SeatState.HELD, inv.stateOf(SHOW_ID, "C1")); + t.line(" %-21s after Ravi's release and confirm: C1 is %s by %s, Ravi's confirm returned %s".formatted( + name, inv.stateOf(SHOW_ID, "C1"), inv.slot(SHOW_ID, "C1").holdId(), foreignConfirm)); + } + + // 3. a booked seat cannot be released by anyone, including its owner ------------------------------------ + t.blank(); + t.line("3. A BOOKED seat is not released by release(), even by its owner"); + for (String name : Fixtures.NAMES) { + SeatInventory inv = Fixtures.fresh(name, Fixtures.clock()); + assertTrue(inv.tryHold(SHOW_ID, List.of("C2"), "ASHA", TTL)); + assertTrue(inv.confirm(SHOW_ID, List.of("C2"), "ASHA")); + inv.release(SHOW_ID, List.of("C2"), "ASHA"); + assertEquals(SeatState.BOOKED, inv.stateOf(SHOW_ID, "C2")); + assertFalse(inv.tryHold(SHOW_ID, List.of("C2"), "RAVI", TTL)); + t.line(" %-21s C2 after owner's release: %s, a new hold on it returns false".formatted(name, inv.stateOf(SHOW_ID, "C2"))); + } + + // 4. bad input is refused before any state changes ----------------------------------------------------- + t.blank(); + t.line("4. Bad input (identical for all three inventories)"); + SeatInventory inv4 = Fixtures.fresh("OptimisticInventory", Fixtures.clock()); + String dup = assertThrows(IllegalArgumentException.class, + () -> inv4.tryHold(SHOW_ID, List.of("A1", "A1"), "X", TTL)).getMessage(); + String unknown = assertThrows(IllegalArgumentException.class, + () -> inv4.tryHold(SHOW_ID, List.of("Z99"), "X", TTL)).getMessage(); + String empty = assertThrows(IllegalArgumentException.class, + () -> inv4.tryHold(SHOW_ID, List.of(), "X", TTL)).getMessage(); + String noShow = assertThrows(IllegalArgumentException.class, + () -> inv4.tryHold("SH-404", List.of("A1"), "X", TTL)).getMessage(); + for (String name : Fixtures.NAMES) { + SeatInventory inv = Fixtures.fresh(name, Fixtures.clock()); + assertEquals(dup, assertThrows(IllegalArgumentException.class, () -> inv.tryHold(SHOW_ID, List.of("A1", "A1"), "X", TTL)).getMessage()); + assertEquals(SeatState.AVAILABLE, inv.stateOf(SHOW_ID, "A1")); + } + t.line(" duplicate seat ids: IllegalArgumentException: " + dup); + t.line(" unknown seat: IllegalArgumentException: " + unknown); + t.line(" no seats at all: IllegalArgumentException: " + empty); + t.line(" unknown show: IllegalArgumentException: " + noShow); + + // 5. pressing Pay twice ---------------------------------------------------------------------------------- + t.blank(); + t.line("5. Pay pressed 50 times at once for the same booking"); + MutableClock clock = Fixtures.clock(); + SeatInventory inv = Fixtures.fresh("OptimisticInventory", clock); + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, TTL); + Booking b = svc.startBooking("asha", SHOW_ID, List.of("D1")); + AtomicInteger confirmed = new AtomicInteger(); + AtomicInteger refused = new AtomicInteger(); + List> clicks = new java.util.ArrayList<>(); + for (int i = 0; i < 50; i++) { + clicks.add(() -> { + try { + if (svc.pay(b.id()) == BookingOutcome.CONFIRMED) { + confirmed.incrementAndGet(); + } + } catch (IllegalStateException e) { + refused.incrementAndGet(); + } + return null; + }); + } + runTogether(clicks); + assertEquals(1, confirmed.get()); + assertEquals(49, refused.get()); + assertEquals(1, pay.charges()); + t.line(" calls that confirmed: " + confirmed.get()); + t.line(" calls refused with IllegalStateException: " + refused.get()); + t.line(" times the card was charged: " + pay.charges()); + t.flush(); + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/RaceConditionTest.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/RaceConditionTest.java new file mode 100644 index 0000000..7838b32 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/RaceConditionTest.java @@ -0,0 +1,111 @@ +package com.ankurm.interviewlab.bookmyshow; + +import com.ankurm.interviewlab.bookmyshow.support.Fixtures; +import com.ankurm.interviewlab.bookmyshow.support.Transcript; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static com.ankurm.interviewlab.bookmyshow.support.Fixtures.SHOW_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** Section 4 and the first half of 5/6: two people, one seat. */ +class RaceConditionTest { + + /** Runs the tasks on separate threads released at the same instant. */ + static List runTogether(List> tasks) throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(tasks.size()); + CountDownLatch go = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for (Callable task : tasks) { + futures.add(pool.submit(() -> { + go.await(); + return task.call(); + })); + } + go.countDown(); + List results = new ArrayList<>(); + for (Future f : futures) { + results.add(f.get(30, TimeUnit.SECONDS)); + } + pool.shutdown(); + return results; + } + + private static Callable tryBooking(BookingService svc, String user, String seat) { + return () -> { + try { + return svc.startBooking(user, SHOW_ID, List.of(seat)).id(); + } catch (SeatUnavailableException e) { + return null; + } + }; + } + + @Test + void naiveCheckThenActGrantsTheSameSeatTwice() throws Exception { + MutableClock clock = Fixtures.clock(); + NaiveInventory inv = new NaiveInventory(clock); + inv.register(Fixtures.show()); + CyclicBarrier bothHaveChecked = new CyclicBarrier(2); + inv.betweenCheckAndAct(() -> { + try { + bothHaveChecked.await(10, TimeUnit.SECONDS); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + FakePaymentGateway pay = new FakePaymentGateway(); + BookingService svc = new BookingService(inv, clock, pay, Duration.ofMinutes(5)); + + List ids = runTogether(List.of(tryBooking(svc, "asha", "C5"), tryBooking(svc, "ravi", "C5"))); + long holdsGranted = ids.stream().filter(java.util.Objects::nonNull).count(); + assertEquals(2, holdsGranted, "the race is made to happen on every run by the barrier"); + + inv.betweenCheckAndAct(() -> { }); + List outcomes = new ArrayList<>(); + for (String id : ids) { + outcomes.add(svc.pay(id)); + } + Collections.sort(outcomes); + assertEquals(List.of(BookingOutcome.CONFIRMED, BookingOutcome.HOLD_LOST_AFTER_PAYMENT), outcomes); + assertEquals(2, pay.charges()); + assertEquals(1, pay.refunds().size()); + + Transcript t = Transcript.start("02-naive-race.txt", + "NaiveInventory: two users request seat C5 at the same moment (barrier forces both reads before either write)"); + t.line("holds granted for C5: " + holdsGranted + " (a seat can only be sold once)"); + t.line("both users now pay:"); + t.line(" outcomes (sorted): " + outcomes); + t.line(" customers charged: " + pay.charges()); + t.line(" customers refunded: " + pay.refunds().size()); + t.line("C5 in the end: " + Fixtures.describe(inv.slot(SHOW_ID, "C5")).replaceAll("BK-000[12]", "BK-000x")); + t.blank(); + t.line("Neither thread did anything unusual. Each ran check, then act, and the barrier only decided"); + t.line("that both checks finished before either act began."); + + for (String name : List.of("PessimisticInventory", "OptimisticInventory")) { + MutableClock c2 = Fixtures.clock(); + SeatInventory safe = Fixtures.fresh(name, c2); + BookingService svc2 = new BookingService(safe, c2, new FakePaymentGateway(), Duration.ofMinutes(5)); + List r = runTogether(List.of(tryBooking(svc2, "asha", "C5"), tryBooking(svc2, "ravi", "C5"))); + long granted = r.stream().filter(java.util.Objects::nonNull).count(); + assertEquals(1, granted); + t.blank(); + t.line(name + ", same two users at the same moment:"); + t.line(" holds granted for C5: " + granted); + t.line(" loser sees: SeatUnavailableException"); + } + t.flush(); + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Fixtures.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Fixtures.java new file mode 100644 index 0000000..db8d345 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Fixtures.java @@ -0,0 +1,66 @@ +package com.ankurm.interviewlab.bookmyshow.support; + +import com.ankurm.interviewlab.bookmyshow.MutableClock; +import com.ankurm.interviewlab.bookmyshow.NaiveInventory; +import com.ankurm.interviewlab.bookmyshow.OptimisticInventory; +import com.ankurm.interviewlab.bookmyshow.PessimisticInventory; +import com.ankurm.interviewlab.bookmyshow.SeatInventory; +import com.ankurm.interviewlab.bookmyshow.SeatSlot; +import com.ankurm.interviewlab.bookmyshow.Show; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** Shared setup so every test starts from the same show, the same clock and the same three inventories. */ +public final class Fixtures { + public static final Instant T0 = Instant.parse("2026-11-20T10:00:00Z"); + public static final String SHOW_ID = "SH-1"; + + private Fixtures() { } + + public static MutableClock clock() { + return new MutableClock(T0); + } + + /** 6 rows x 10 seats: A..D regular (Rs 220), E premium (Rs 350), F recliner (Rs 600). */ + public static Show show() { + return Show.grid(SHOW_ID, "The Last Local", "Screen 3", Instant.parse("2026-11-21T14:00:00Z"), 6, 10); + } + + /** The three implementations by name. Each call to {@link #fresh} builds a new inventory with the show registered. */ + public static final List NAMES = List.of("NaiveInventory", "PessimisticInventory", "OptimisticInventory"); + + public static SeatInventory fresh(String name, MutableClock clock) { + SeatInventory inv = switch (name) { + case "NaiveInventory" -> new NaiveInventory(clock); + case "PessimisticInventory" -> new PessimisticInventory(clock); + case "OptimisticInventory" -> new OptimisticInventory(clock); + default -> throw new IllegalArgumentException(name); + }; + inv.register(show()); + return inv; + } + + /** "T+04:59" style label, relative to the clock's start, so transcripts do not depend on the date the tests ran. */ + public static String t(Instant when) { + long s = Duration.between(T0, when).getSeconds(); + return "T+%02d:%02d".formatted(s / 60, s % 60); + } + + public static String describe(SeatSlot slot) { + return switch (slot.state()) { + case AVAILABLE -> "AVAILABLE v" + slot.version(); + case HELD -> "HELD by %s until %s v%d".formatted(slot.holdId(), t(slot.expiresAt()), slot.version()); + case BOOKED -> "BOOKED by %s v%d".formatted(slot.holdId(), slot.version()); + }; + } + + public static Map summaryAsStrings(SeatInventory inv, String showId) { + Map m = new TreeMap<>(); + inv.summary(showId).forEach((k, v) -> m.put(k.name(), v)); + return m; + } +} diff --git a/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Transcript.java b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Transcript.java new file mode 100644 index 0000000..f22f330 --- /dev/null +++ b/bookmyshow/src/test/java/com/ankurm/interviewlab/bookmyshow/support/Transcript.java @@ -0,0 +1,43 @@ +package com.ankurm.interviewlab.bookmyshow.support; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */ +public final class Transcript { + private final Path path; + private final List lines = new ArrayList<>(); + + private Transcript(Path path, String header) { + this.path = path; + lines.add(header); + lines.add("=".repeat(Math.min(header.length(), 100))); + lines.add(""); + } + + public static Transcript start(String fileName, String header) { + Path dir = Path.of("output"); + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new Transcript(dir.resolve(fileName), header); + } + + public Transcript line(String text) { lines.add(text); return this; } + public Transcript blank() { lines.add(""); return this; } + + public void flush() { + try { + Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +}