Skip to content

Case study: ticket reservation

Difficulty: Advanced

Key concepts

  • seat state machine
  • all-or-nothing hold
  • lazy expiry
  • injected clock
  • one mutex per show
  • check-then-act
  • no lock during a payment
  • re-check after the payment
  • idempotent confirmation
  • request id
  • refund
  • std::latch
  • group booking
  • How to model a seat as a tiny state machine (available, held, booked) whose illegal moves throw, so that a bug cannot quietly sell a seat that was never held.
  • Why a customer first holds seats for a few minutes, and how a hold of several seats is made all or nothing: check every seat, then mark every seat, under one lock.
  • How holds expire with no timer thread: the service reads an injected clock inside the lock and expires what is due at the start of each call.
  • Why the lock is one std::mutex per show, and when finer locking would be worth its cost.
  • Why the payment is taken with no lock held, the race that opens, and the re-check after the payment that closes it, with a refund when the hold was lost in the meantime.
  • How a request id makes confirmation safe to repeat: a retry gets the first answer and is never charged twice, even while the first try is still paying.
  • How to test all of this, first with a fake payment gateway that plays out the race in one thread, then with real threads started together by a std::latch, and what those tests can and cannot prove.
  • How a change (group bookings) lands as a new way to choose seats that returns an ordinary hold, so that expiry, payment, and idempotency apply to it unchanged.

This page follows the order in How to approach a case study. It assumes Deadlocks and lock ordering, Idempotency, retries, and duplicate handling, and Transaction and persistence boundaries. It also leans on Thread safety and synchronization and Testing concurrent code and its limits. Those pages build each idea on its own; this one needs them together, in a program where many customers want the same seat at the same moment and money moves through a service that is slow and may fail.

“We sell seats for shows. When a popular show opens, thousands of people try at once, and last season two customers were sold the same seat more than once. Some customers were also charged twice when their app timed out and they pressed ‘Pay’ again. Can you design the part that holds seats while a customer pays, and books them?”

Two complaints again. One is about concurrency: two customers saw the same seat as free, and both took it. The other is about retries: one customer asked twice, and the system did the work twice. They look different, but both come from doing a check in one moment and acting on it in another, and assuming nothing happened in between.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
Does a customer pick seats, or ask for “two seats”? They pick seats on a seat map. (Groups come later.) A hold names its seats. Choosing seats for a customer is the change, below.
What happens between picking and paying? The seats are kept for the customer for a few minutes, five by default. A hold with an expiry time. Held seats are not free for anyone else.
If one of the chosen seats is taken, what then? Nothing. Customers pick seats that go together; two out of three is useless. A hold of several seats is all or nothing.
Who takes the money? An outside payment service. It takes a second or two, and sometimes much longer, and it can decline a card. A PaymentGateway interface, called with no lock held, and a fake for tests.
What if the hold runs out while the payment is going through? The customer must not get seats someone else now has. Refund them. A re-check after the payment, and a refund when the hold was lost.
What does the app do when a payment request times out? It sends the same request again, with the same id. It cannot tell a slow answer from a lost one. Every confirm carries a request id chosen by the app, and a repeat gets the first answer.
Can the payment service spot a repeated charge? Yes, if we send it a key with each charge. The request id goes to the gateway as that key too.
How many shows, and how many customers at once? Hundreds of shows on sale; for a big show, thousands of customers in the first minutes. Shows must not wait for each other: one lock per show. Calls must be short under the lock.
Can a customer cancel a booking? Not in this release. A booked seat never changes. (See the Exercise.)
Does the order of arrival decide who gets a seat? Whoever asks first should get it, as far as is reasonable. Whoever gets the lock first wins. The design does not promise fairness beyond that, and says so.
One process or many? For this design, one process. A database comes later. State in memory, protected by mutexes. Many processes would need the database to do this job; see Production limitations.

Three answers decide the shape. “All or nothing” means a hold of several seats must check and mark every seat as one step. “A second or two, and sometimes much longer” means the payment cannot happen under the lock that every other customer of the show needs. “It sends the same request again” means confirm must be safe to repeat, and so must the charge it makes.

Confirmed:

  • Shows with rows of seats, a price per seat, and a hold time.
  • Holding one or more named seats, all or nothing, until the hold expires.
  • Releasing a hold.
  • Confirming a hold: taking the payment and booking the seats.
  • A payment service that may decline, may be slow, and may throw.
  • Many customers at once, on many threads.

Assumed (to confirm with the team; see Assumptions):

  • The app makes a new request id for each attempt to pay, and sends the same id again only when it retries that same attempt.
  • A request id is unique within a show. The service keeps request ids per show.
  • Shows are set up before the service starts taking requests.

Out of scope: seat maps with sections and prices per seat, user accounts, cancellations and refunds that a customer asks for, waiting lists, a database, and several processes. Group bookings arrive as a change, below.

Functional requirements.

  • FR-1 Seats. A show has rows A, B, … of seats numbered from 1. Each seat is available, held, or booked. A seat is booked only after it was held and paid for.
  • FR-2 Hold. A customer can hold one or more seats of a show for a fixed time. Either every seat asked for is held, or none is, and the reply says why not.
  • FR-3 Expiry. A hold that has not been confirmed ends at its expiry time, to the second, and its seats are free again. A booking never expires.
  • FR-4 Release. A customer can give back a hold before it expires.
  • FR-5 Confirm. Confirming a live hold charges its price and books its seats. A declined payment frees the seats at once.
  • FR-6 No seat sold twice. Whatever the timing, a seat is in at most one live hold or booking.
  • FR-7 Paid, but too late. If a hold is lost while its payment is going through (it expired, or it was released), nothing is booked and the payment is refunded.

Non-functional requirements.

  • NFR-1 Safe to repeat. A confirm sent again with the same request id gets the same answer and is charged at most once, even if the first is still in progress.
  • NFR-2 Thread-safe. Any number of threads may call hold, release, and confirm at once.
  • NFR-3 No lock during a payment. A slow payment for one customer never makes another customer of the same show wait for it.
  • NFR-4 Testable without waiting. Time and payment are interfaces, so a five-minute hold is tested to the second without sleeping, and a race is played out on demand.
  • NFR-5 Exact money. Prices are integer cents.

FR-6 is the first complaint, and NFR-1 the second. NFR-3 is the constraint that makes FR-6 hard: once the lock is let go during a payment, the world can change before it is taken again.

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Set up a show.

  • AC-1.1 A new show has every seat available.
  • AC-1.2 A seat moves only along the legal transitions, and an illegal move throws and changes nothing.
  • AC-1.3 A bad layout (no rows, more than 26 rows, more than 99 seats in a row, a negative price, a hold time that is not positive) or a repeated show id is refused.

UC-2 Hold seats.

  • AC-2.1 A hold marks its seats held, until its expiry, and costs the price per seat times the number of seats.
  • AC-2.2 A held seat is refused to everyone else.
  • AC-2.3 A hold of several seats is all or nothing.
  • AC-2.4 A bad request (unknown show, no seats, a seat that does not exist, a seat twice) is refused with a reason and changes nothing.
  • AC-2.5 Release frees the seats, once.

UC-3 Let a hold expire.

  • AC-3.1 A hold expires exactly at its expiry time.
  • AC-3.2 A confirm after expiry is refused and charges nothing.
  • AC-3.3 A confirm one second before expiry books.
  • AC-3.4 An expired hold cannot be released or revived.

UC-4 Confirm, and confirm again.

  • AC-4.1 Confirm charges the hold’s amount and books its seats.
  • AC-4.2 The same request id gets the same result and pays once.
  • AC-4.3 A request id used again for another hold is refused.
  • AC-4.4 A second request id for a confirmed hold is refused.
  • AC-4.5 A refusal is repeated too.
  • AC-4.6 An unknown hold or show is refused.

UC-5 Pay.

  • AC-5.1 A declined payment releases the hold.
  • AC-5.2 A hold that expires during payment is refunded, not booked.
  • AC-5.3 A hold released during payment is refunded, not booked.
  • AC-5.4 A second request id during a payment is refused and not charged.
  • AC-5.5 A decline after the hold expired during payment refunds nothing.
  • AC-5.6 A gateway that throws leaves the hold for a retry.

UC-6 Many customers at once (real threads).

  • AC-6.1 Of many threads holding one seat, exactly one wins.
  • AC-6.2 Overlapping holds of several seats never share a seat.
  • AC-6.3 Concurrent repeats of one request pay once and agree.
  • AC-6.4 Concurrent confirms of one hold book it once.
  • AC-6.5 The lock is not held while the gateway is called.
  • AC-6.6 A repeat during a payment waits for the first answer.
  • AC-6.7 Random customers never double-book, and the money kept matches the bookings.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 Seats move legally. A seat goes available to held, held to available, or held to booked, and nothing else. Kept by can_move and Seat::move_to, the only code that changes a seat’s state.
  • INV-2 A seat and its hold agree. A held seat belongs to exactly one live (active or paying) hold that lists it; a booked seat belongs to exactly one confirmed hold; an available seat belongs to none. Kept by Show, which changes a seat and its hold record in the same locked call. Checked by Show::invariants_hold.
  • INV-3 One hold per paying request. A hold is paying for at most one request id at a time. Kept by begin_confirm, which moves active to paying under the lock and refuses a second id while it is paying.
  • INV-4 Only a hold that is still ours is booked. finish_confirm books only a hold whose status is still paying when the payment returns. Anything else is refunded if the money was taken.
  • INV-5 One answer per request id. Once a request id is decided, its answer never changes, and no second charge is made for it. Kept by decide and the check at the top of begin_confirm.
  • INV-6 Money matches bookings. Approved charges minus refunds equal the price of the bookings. A consequence of INV-3 and INV-4, checked by the random thread test.

The nouns from the answers: show, seat, row, seat map, customer, hold, expiry, price, payment, card, refund, request, retry, booking. Filtered:

  • Show is a Show: its layout, its seats, its holds, and its confirm requests, behind one mutex.
  • Seat is a Seat (state and holder) named by a SeatId (row letter and number). Row and seat map are just the layout.
  • Hold is a Hold value returned to the customer, and a private HoldRecord inside the show that remembers how it ended.
  • Expiry is a time in the hold, compared with a Clock.
  • Payment, card, and refund become the PaymentGateway interface and its PaymentResult.
  • Request and retry become a RequestId and the show’s record of each one.
  • Booking is a Booking value.
  • Customer is not a class. Nothing in the rules depends on who the customer is, only on which hold and which request id they use.
Classes in step 1. Filled diamond: owns. Plain arrow: uses, not owned
Text description of the diagram

BookingService owns its shows, each in a unique_ptr, and holds references to a Clock and a PaymentGateway that it does not own. It offers add_show, hold, release, and confirm. Show owns a mutex, a condition variable, a vector of Seat, a map from HoldId to a hold record, and a map from RequestId to a request record. It offers hold, release, begin_confirm, finish_confirm, and abandon_confirm, returns Hold and Booking values, and reads the clock. Seat holds a SeatState and the HoldId of its holder, and offers hold, release, and book. Hold has an id, its seats, an expiry time, and an amount. Booking has a number, its seats, an amount, and a payment reference. Clock is an interface with now; ManualClock implements it. PaymentGateway is an interface with charge and refund; FakePaymentGateway implements it. BookingService, not Show, calls the gateway.

Diagram source (Mermaid)
classDiagram
class BookingService {
  -const Clock& clock_
  -PaymentGateway& payments_
  -map~ShowId, unique_ptr~ shows_
  +add_show(id, rows, seats_per_row, price)
  +hold(show, seats) HoldResult
  +release(show, HoldId) bool
  +confirm(request, show, HoldId, card) ConfirmResult
}
class Show {
  -mutex mutex_
  -condition_variable done_
  -vector~Seat~ seats_
  -map~HoldId, HoldRecord~ holds_
  -map~RequestId, RequestRecord~ requests_
  +hold(seats) HoldResult
  +release(HoldId) bool
  +begin_confirm(request, HoldId) variant
  +finish_confirm(request, HoldId, PaymentResult) Finished
  +abandon_confirm(request, HoldId)
}
class Seat {
  -SeatState state_
  -HoldId holder_
  +hold(HoldId)
  +release()
  +book()
}
class Hold {
  +HoldId id
  +vector~SeatId~ seats
  +TimePoint expires_at
  +Cents amount
}
class Booking {
  +uint64_t number
  +vector~SeatId~ seats
  +Cents amount
  +string payment_reference
}
class Clock {
  <<interface>>
  +now() TimePoint*
}
class PaymentGateway {
  <<interface>>
  +charge(key, amount, card) PaymentResult*
  +refund(reference)*
}
BookingService *-- Show : shows_
Show *-- Seat : seats_
Show ..> Hold : returns
Show ..> Booking : returns
Show --> Clock : reads
BookingService --> Clock : passes on
BookingService --> PaymentGateway : charges, refunds
Clock <|.. ManualClock
PaymentGateway <|.. FakePaymentGateway

Ownership is short to state. The service owns its shows. A Show owns its seats and its records, and cannot be copied or moved, because it owns a mutex; that is why the service keeps each one in a std::unique_ptr. The clock and the gateway are owned by whoever builds the service, the composition root, and must outlive it. A Hold or a Booking handed to a customer is a plain value: a copy, sharing nothing with the service.

Notice which class calls the gateway. Show never does. It knows seats and holds and nothing about money leaving a card. The service calls the gateway between two calls to the show, and that one choice is what lets the show’s lock be free during the payment.

The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Group bookings are added in When the requirements change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

seat.hpp
// The three states a seat can be in. A seat is held for one customer for a
// few minutes while they pay; the hold's expiry time lives in the hold (see
// Hold in booking.hpp), because every seat in one hold expires together.
enum class SeatState { available, held, booked };
inline std::string_view to_string(SeatState state) {
switch (state) {
case SeatState::available: return "available";
case SeatState::held: return "held";
case SeatState::booked: return "booked";
}
return "?";
}
// The only legal moves:
// available -> held a customer holds it
// held -> available the hold is released, expires, or payment fails
// held -> booked the hold is confirmed after payment
// A booked seat never changes (there is no cancellation), and a seat can
// never go straight from available to booked: it must be held first, so
// every booking went through a hold and a payment.
constexpr bool can_move(SeatState from, SeatState to) {
switch (from) {
case SeatState::available: return to == SeatState::held;
case SeatState::held: return to == SeatState::available || to == SeatState::booked;
case SeatState::booked: return false;
}
return false;
}
The states of one seat, and the calls that move it
Text description of the diagram

A seat starts available. A hold moves it to held, but only when every seat in the same request is free. From held it goes back to available when the hold is released, when it expires, or when its payment is declined, and on to booked when the payment is approved and the hold is still being paid for. Booked is final in step 1: there is no cancellation. There is no arrow from available straight to booked.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> available
available --> held : hold, all seats of the request free
held --> available : release, expiry, or a declined payment
held --> booked : finish_confirm, the payment approved and the hold still paying
booked --> [*]

Three states, and the missing arrows matter as much as the ones drawn. No arrow goes from available to booked, so every booking went through a hold, and so through a payment. No arrow leaves booked, so nothing in step 1 can un-sell a seat. can_move is constexpr, a plain function of two values, which makes the whole table testable in a few lines (AC-1.2).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

seat.hpp
// One seat: its state and, while it is held or booked, which hold owns it.
// The state can change only through hold, release, and book, and each of
// those goes through move_to, which refuses an illegal move. The Show
// checks every rule before calling these, so a throw here means a bug in
// the Show, not a customer mistake; that is why it is std::logic_error.
class Seat {
public:
[[nodiscard]] SeatState state() const { return state_; }
// The hold that owns the seat; HoldId{} while the seat is available.
[[nodiscard]] HoldId holder() const { return holder_; }
void hold(HoldId by) {
move_to(SeatState::held);
holder_ = by;
}
void release() {
move_to(SeatState::available);
holder_ = HoldId{};
}
// Keeps holder_, so a booked seat still says which hold became its booking.
void book() { move_to(SeatState::booked); }
private:
void move_to(SeatState next) {
if (!can_move(state_, next)) {
throw std::logic_error("illegal seat move from " + std::string(to_string(state_)) +
" to " + std::string(to_string(next)));
}
state_ = next;
}
SeatState state_ = SeatState::available;
HoldId holder_;
};

Seat keeps the table honest: hold, release, and book all go through move_to, which throws before changing anything. The throw is a std::logic_error, because the Show checks every customer-facing rule first; a throw here means the show has a bug. That is the point of a state machine at this size. It turns “a seat was sold that nobody held” from a silent wrong answer into a loud failure in the first test that reaches it. For the general idea, see State machines and invalid-state prevention.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking.hpp
// What a customer gets back from a successful hold: which seats, until
// when, and what confirming will cost. A plain value: copying it does not
// copy or share any state inside the service.
struct Hold {
HoldId id;
ShowId show;
std::vector<SeatId> seats;
TimePoint expires_at;
Cents amount = 0;
friend bool operator==(const Hold&, const Hold&) = default;
};
// What a customer gets back from a successful confirm.
struct Booking {
std::uint64_t number = 0; // 1, 2, 3, ... within one show
ShowId show;
HoldId hold;
std::vector<SeatId> seats;
Cents amount = 0;
std::string payment_reference;
friend bool operator==(const Booking&, const Booking&) = default;
};

Hold and Booking are value objects: what the customer gets back, copied out of the show. A customer cannot change the service’s records through them, and a test can compare them with ==.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking.hpp
// Why a hold was refused.
enum class HoldError {
unknown_show,
no_seats, // the request named no seats
unknown_seat, // a seat that is not in this show
duplicate_seat, // the same seat twice in one request
seat_held, // someone else holds one of the seats
seat_booked, // one of the seats is already sold
};
// Why a confirm did not produce a booking.
enum class ConfirmError {
unknown_show,
unknown_hold,
hold_expired, // the hold ran out before confirm was called
hold_released, // released by the customer or by a failed payment
already_confirmed, // a different request id already confirmed this hold
payment_in_progress, // another request id is paying for this hold now
request_reused, // this request id was already used for a different hold
payment_declined, // the gateway said no; the seats were released
hold_lost_during_payment, // paid, but the hold expired or was released
// while the payment was in flight; refunded
};

Every refusal has its own name. “No” is not enough for a customer who needs to know whether to pick another seat (seat_held), start again (hold_expired), or wait (payment_in_progress), and it is not enough for a test that must tell those cases apart.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

result.hpp
// Either a value or the reason there is none: a small stand-in for C++23
// std::expected, which the compilers this site targets do not all have yet.
// A refusal (a seat already held, a hold that expired) is an ordinary
// answer here, not an exception, so callers must look at it: [[nodiscard]]
// makes the compiler warn when a result is ignored.
// T and E must be different types, so that the variant can tell them apart.
template <typename T, typename E>
class [[nodiscard]] Expected {
public:
// Both constructors are implicit on purpose, so a function can simply
// `return booking;` or `return ConfirmError::hold_expired;`.
Expected(T value) : value_(std::move(value)) {}
Expected(E error) : value_(error) {}
[[nodiscard]] bool has_value() const { return std::holds_alternative<T>(value_); }
explicit operator bool() const { return has_value(); }
// value() throws std::bad_variant_access if this holds an error, and
// error() throws it if this holds a value. Check has_value() first.
[[nodiscard]] const T& value() const { return std::get<T>(value_); }
[[nodiscard]] E error() const { return std::get<E>(value_); }
friend bool operator==(const Expected&, const Expected&) = default;
private:
std::variant<T, E> value_;
};

A seat already held is an ordinary answer on a busy evening, not an error in the program, so it is a value, not an exception. Expected is a small stand-in for C++23 std::expected, and [[nodiscard]] on the class makes the compiler warn when a caller ignores one. Exceptions are left for what really is unexpected: a bad layout, an illegal seat move, and a payment gateway that throws.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

clock.hpp
// Where the service gets the time, to stamp a hold with its expiry and to
// decide later whether that expiry has passed. The tests and the demo pass
// ManualClock and move time by hand, so a five-minute hold is checked to the
// second and no test ever sleeps.
using TimePoint = std::chrono::system_clock::time_point;
class Clock {
public:
virtual ~Clock() = default;
[[nodiscard]] virtual TimePoint now() const = 0;
protected:
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
class SystemClock final : public Clock {
public:
[[nodiscard]] TimePoint now() const override { return std::chrono::system_clock::now(); }
};
// A clock that moves only when advance is called. In the thread tests one
// thread advances it while others read it, so the time is kept in a
// std::atomic: every read sees either the old time or the new one, never a
// torn value, and the read and the write are not a data race.
class ManualClock final : public Clock {
public:
explicit ManualClock(TimePoint start) : ticks_(start.time_since_epoch().count()) {}
[[nodiscard]] TimePoint now() const override {
// Rebuild a time point from the stored tick count.
return TimePoint{TimePoint::duration{ticks_.load()}};
}
// Throws std::invalid_argument for a negative step.
void advance(std::chrono::seconds step) {
if (step.count() < 0) throw std::invalid_argument("time only moves forward here");
// += on a std::atomic is one indivisible read-add-write.
ticks_ += std::chrono::duration_cast<TimePoint::duration>(step).count();
}
private:
std::atomic<TimePoint::rep> ticks_;
};

The show never calls std::chrono::system_clock itself; it asks an injected Clock. That is what lets ac_3_1 hold a seat, move the clock 299 seconds, see the seat still held, move it one more second, and see it free, all in a few microseconds. ManualClock keeps its time in a std::atomic, because in the thread tests one thread moves the clock while others read it. Without the atomic, that would be a data race, even though every read happens under some show’s lock: the clock is not guarded by that lock.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

payment.hpp
// The outside payment service. It is slow (a network call) and can say no,
// which is why BookingService never calls it while holding a show's lock.
struct PaymentResult {
bool approved = false;
std::string reference; // the gateway's id for the charge; empty if declined
};
class PaymentGateway {
public:
virtual ~PaymentGateway() = default;
// key is the confirm request id. A real gateway uses it to spot a
// retried charge and not take the money twice. Called from many threads
// at once, so an implementation must be thread-safe.
virtual PaymentResult charge(const RequestId& key, Cents amount, const std::string& card) = 0;
virtual void refund(const std::string& reference) = 0;
protected:
PaymentGateway() = default;
PaymentGateway(const PaymentGateway&) = default;
PaymentGateway& operator=(const PaymentGateway&) = default;
};

Two things in this contract shape everything else. charge is slow and may fail, so it is called with no lock held. And it takes a key: the request id, so that a real gateway that sees the same key twice can answer the second time without charging again. The service does its own deduplication too (NFR-1), and the two work together: the service stops repeats it can see, and the key covers a repeat that reaches the gateway anyway, for example after the service itself has restarted.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

payment.hpp
// A stub for tests and the demo. It approves every card except those passed
// to decline, and records each charge and refund so a test can count them.
// during_charge, if set, runs inside charge before the charge is recorded:
// it stands for the time the real network call takes, and a test uses it to
// move the clock or act as another customer while a payment is in flight.
class FakePaymentGateway final : public PaymentGateway {
public:
struct Charge {
RequestId key;
Cents amount = 0;
std::string card;
};
// Setup only: call these before any thread uses the gateway.
void decline(std::string card) { declined_.insert(std::move(card)); }
void during_charge(std::function<void()> hook) { hook_ = std::move(hook); }
PaymentResult charge(const RequestId& key, Cents amount, const std::string& card) override {
// The hook runs without the fake's own lock, so it may call back
// into the booking service, and even into charge, without deadlock.
// One call it must not make on this thread: a confirm with the same
// request id, which would wait for this very payment for good.
if (hook_) hook_();
const std::lock_guard lock(mutex_);
charges_.push_back({key, amount, card});
if (declined_.contains(card)) return {false, ""};
return {true, "pay-" + std::to_string(charges_.size())};
}
void refund(const std::string& reference) override {
const std::lock_guard lock(mutex_);
refunds_.push_back(reference);
}
// Copies, taken under the lock, so a test can read them while other
// threads may still be charging.
[[nodiscard]] std::vector<Charge> charges() const {
const std::lock_guard lock(mutex_);
return charges_;
}
[[nodiscard]] std::vector<std::string> refunds() const {
const std::lock_guard lock(mutex_);
return refunds_;
}
private:
std::set<std::string> declined_;
std::function<void()> hook_;
mutable std::mutex mutex_; // guards charges_ and refunds_
std::vector<Charge> charges_;
std::vector<std::string> refunds_;
};

The fake is a test double with one unusual feature: during_charge. The hook runs inside charge, at the moment a real payment would be waiting on the network, and with the show’s lock free. A test can put anything there: move the clock past the hold’s expiry, let another customer take the seat, release the hold, or send a confirm with a second request id. It turns a race that happens one time in a million into a test that happens every time, on one thread, in the same order. The hook runs before the fake takes its own mutex, so code in the hook can call back into the service, and even into charge, without a deadlock. The one call it must not make on its own thread is a confirm with the same request id: that repeat would wait in begin_confirm for this very payment, which cannot finish until the hook returns. A repeat of the same id has to come from another thread, as in AC-6.6.

Note what the fake records: every charge, declined or not, numbered in order. The reference of an approved charge is pay- and its position in that list, so a declined charge uses up a number too. In the demo, Erin’s charge is the third, pay-3.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.hpp
// One performance: its seats, the holds on them, and the confirm requests
// seen so far. Every public function that reads or changes them takes the
// show's one mutex for its whole body (begin_confirm lets go of it only
// while it waits; see there), so each call is atomic with respect to every
// other call on the same show: two customers can never both see a seat as
// free and both take it. id, rows, and seats_per_row need no lock: they
// never change after construction.
//
// Why one mutex per show, and not one per seat or one for the whole
// service: a hold of several seats must check and mark all of them as one
// step, and one lock per show makes that trivial, with no lock ordering to
// get wrong. Different shows do not share a lock, so they never wait for
// each other. The cost is that two customers of the same show wait for
// each other briefly; every locked step is work in memory (at most a walk
// over the show's seats and hold records) and never a network call, so the
// wait is short.
//
// The show reads the clock itself, inside the lock, at the start of every
// call, so a decision is always made with the time it is made at. Expiry
// is lazy: there is no timer thread. Each call that acts on seats or holds
// first expires every hold whose time has passed (expire_due), so no
// decision is made on a stale hold (abandon_confirm, which only hands a
// hold back, is the one exception; see expire_due).
//
// A Show is neither copyable nor movable (it owns a mutex);
// BookingService keeps each one in a std::unique_ptr.
class Show {
public:
// Throws std::invalid_argument unless 1 <= rows <= 26,
// 1 <= seats_per_row <= 99, price_per_seat >= 0, and hold_for > 0.
// The clock is not owned and must outlive the show.
Show(ShowId id, int rows, int seats_per_row, Cents price_per_seat, const Clock& clock,
std::chrono::seconds hold_for);
[[nodiscard]] const ShowId& id() const { return id_; }
[[nodiscard]] int rows() const { return rows_; }
[[nodiscard]] int seats_per_row() const { return seats_per_row_; }
// Holds every seat in seats until now + hold_for, or none of them.
// Refuses no_seats, unknown_seat, duplicate_seat, seat_held, or
// seat_booked; a refusal changes nothing.
HoldResult hold(const std::vector<SeatId>& seats);
// Gives the seats of a hold back. Returns false, and changes nothing, if
// the hold is unknown, expired, released, or confirmed. A hold being
// paid for can be released; its payment is then refunded.
bool release(HoldId hold_id);
// Confirming is split in two around the payment, so the lock is not held
// while the gateway is called. BookingService::confirm calls
// begin_confirm -> either a final answer, or PaymentDue
// (the charge, with no lock held)
// finish_confirm -> the final answer, and whether to refund
// If the charge throws, it calls abandon_confirm instead of finish.
struct PaymentDue {
Cents amount = 0;
};
std::variant<ConfirmResult, PaymentDue> begin_confirm(const RequestId& request,
HoldId hold_id);
struct Finished {
ConfirmResult result;
bool refund = false; // true: the charge succeeded but must be given back
};
Finished finish_confirm(const RequestId& request, HoldId hold_id, const PaymentResult& paid);
void abandon_confirm(const RequestId& request, HoldId hold_id);
// The seat's state after expiring due holds; std::nullopt if no such seat.
std::optional<SeatState> state_of(SeatId seat);
// How many seats are in the given state, after expiring due holds.
std::size_t count(SeatState state);
// For tests: true if every held or booked seat belongs to a hold that
// lists it and is in a matching status, and every active, paying, or
// confirmed hold still owns all of its seats.
[[nodiscard]] bool invariants_hold() const;
private:
// What happened to a hold. A hold record is kept after it ends, so a
// late confirm can be told why it failed (expired, released) rather
// than just "unknown". In this teaching version records are never
// deleted; a real service would delete old ones after a while.
enum class HoldStatus { active, paying, expired, released, confirmed };
struct HoldRecord {
Hold hold;
HoldStatus status = HoldStatus::active;
};
// One per confirm request id. result is empty while that request's
// payment is in flight, and set for good once the request is decided.
// (abandon_confirm erases the record of a request whose charge threw.)
struct RequestRecord {
HoldId hold;
std::optional<ConfirmResult> result;
};
// The private helpers below all expect mutex_ to be locked already.
[[nodiscard]] bool contains(SeatId seat) const;
[[nodiscard]] std::size_t index_of(SeatId seat) const;
Seat& seat_at(SeatId seat) { return seats_[index_of(seat)]; }
void expire_due(TimePoint now);
void free_seats(const Hold& hold);
ConfirmResult decide(const RequestId& request, HoldId hold_id, ConfirmResult result);
const ShowId id_;
const int rows_;
const int seats_per_row_;
const Cents price_per_seat_;
const Clock& clock_;
const std::chrono::seconds hold_for_;
// mutex_ guards everything below it. done_ wakes callers that are
// waiting for another call with the same request id to finish.
mutable std::mutex mutex_;
std::condition_variable done_;
std::vector<Seat> seats_; // row by row: A1, A2, ..., B1, ...
std::map<HoldId, HoldRecord> holds_;
std::map<RequestId, RequestRecord> requests_;
std::uint64_t next_hold_ = 1;
std::uint64_t next_booking_ = 1;
};

The comment at the top is the design in a paragraph. Three choices in it deserve a closer look.

One mutex per show. Every public function that reads or changes seats, holds, or requests takes mutex_ for its whole body, so each call is one indivisible step for that show. That makes the hardest requirement, FR-6, almost free: a hold checks its seats and marks them inside one call, and no other call on the same show can run in between. It also makes all-or-nothing (FR-2) free, because there is only one lock to take, and so no lock ordering to get wrong. Different shows have different mutexes, so a slow evening at one show never makes another wait.

When finer locking would be worth it. The cost of one lock per show is that every customer of that show takes turns. With a few thousand seats and calls that do work in memory only (the longest is a walk over the show’s seats and hold records), the turns are short, and that is the right trade. The walk over hold records grows with every hold ever made, which is one of the Production limitations. It stops being right when measurements show customers of one very large show waiting on this mutex, for example a stadium of 80,000 seats in the first minute of sale. Then one lock per section, or per row, lets customers in different sections proceed at once. The price is real: a hold that spans sections must lock several mutexes, always in a fixed order (see Ordering by id when the set of locks is known only at run time), expiry and the request records need a home of their own, and choosing seats for a group (step 2) has to look across sections. Do it when a measurement asks for it, not before.

The show reads the clock, inside the lock. Every call asks clock_.now() after it has the lock, and expires what is due before it does anything else. A decision is therefore made with the time at which it is made, not a time read before waiting for the lock; see Expiry with the time of the decision.

Two private records carry the history. A HoldRecord keeps a hold after it ends, with how it ended, so a late confirm hears “the hold has expired” rather than “no such hold”. A RequestRecord keeps the answer given to each request id, which is what makes a repeat safe. In this teaching version, neither is ever deleted; see Production limitations.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
HoldResult Show::hold(const std::vector<SeatId>& seats) {
// lock_guard locks here and unlocks when the function returns, by any
// path. Everything until then is one atomic step for this show.
const std::lock_guard lock(mutex_);
const TimePoint now = clock_.now();
expire_due(now);
if (seats.empty()) return HoldError::no_seats;
// Pass 1: check every seat and change nothing. An early return here
// leaves the show exactly as it was, which is what makes a hold of
// several seats all-or-nothing.
std::set<SeatId> seen;
for (const SeatId seat : seats) {
if (!contains(seat)) return HoldError::unknown_seat;
// insert returns {position, inserted}; false means a repeat.
if (!seen.insert(seat).second) return HoldError::duplicate_seat;
switch (seat_at(seat).state()) {
case SeatState::available: break;
case SeatState::held: return HoldError::seat_held;
case SeatState::booked: return HoldError::seat_booked;
}
}
// Pass 2: every seat was free and, because the lock is still held, no
// other thread can have taken one since pass 1. Record the hold, then
// mark the seats. Only the two lines that make the record allocate, so
// if one throws (out of memory), no seat has been marked yet.
const HoldId new_id{next_hold_++};
const Hold made{new_id, id_, seats, now + hold_for_,
price_per_seat_ * static_cast<Cents>(seats.size())};
holds_.emplace(new_id, HoldRecord{made, HoldStatus::active});
for (const SeatId seat : seats) seat_at(seat).hold(new_id);
return made;
}
How this code works: Show::hold, twice, in the step 1 demo

The demo’s show “evening” has 2 rows of 4 seats at $25.00, and holds last 5 minutes. The clock starts at 19:00 on 5 December 2026.

Alice asks for A1 A2. The lock is taken, now is 19:00, and expire_due finds nothing to expire.

Pass Seat contains First time in the request? State What happens
1 A1 yes yes available go on
1 A2 yes yes available go on
2 A1 hold(HoldId{1})
2 A2 hold(HoldId{1})

next_hold_++ gives 1 and leaves 2 for the next hold. The hold is {1, "evening", {A1, A2}, 19:05, 5000}: 2 seats times 2500 cents. The demo prints “hold 1 on A1 A2, $50.00”.

Bob asks for A2 A3.

Pass Seat contains First time in the request? State What happens
1 A2 yes yes held return seat_held

Pass 1 stops at A2. A3 is never looked at, nothing was marked, and next_hold_ is still 2, so the next hold, Carol’s, is hold 2. The demo then asks for A3’s state and gets “available”: Bob’s refusal took nothing.

Two things make this all or nothing:

  1. Pass 1 changes nothing. Every early return leaves the show as it was. The std::set named seen exists only to catch a seat listed twice; without it, pass 2 would call hold on the same seat twice and the second call would throw.
  2. Pass 2 cannot fail part way. When it starts, every seat is known to exist, to be listed once, and to be available, and the lock has been held since pass 1 looked. So every Seat::hold is a legal move. The only lines that can throw are the two that make the hold record, which allocate memory, and they run before any seat is marked: if memory runs out, the call throws and no seat has changed.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
// Lazy expiry: called, under the lock, at the start of every public
// function that reads or changes seats or holds, with two exceptions: the
// test check invariants_hold, and abandon_confirm, which only turns paying
// back into active (the next call expires that hold if its time has
// passed). A hold lasts up to, but not including, its expiry instant, so
// at exactly expires_at it is gone. A hold whose payment is in flight
// (paying) expires too; finish_confirm then sees that, and asks for a
// refund if the charge was approved.
void Show::expire_due(TimePoint now) {
for (auto& entry : holds_) {
HoldRecord& record = entry.second;
const bool live =
record.status == HoldStatus::active || record.status == HoldStatus::paying;
if (live && now >= record.hold.expires_at) {
free_seats(record.hold);
record.status = HoldStatus::expired;
}
}
}

There is no timer. A hold whose time has passed is still marked active until the next call on that show, and that call expires it before doing anything else. No one can tell the difference: every call that could observe the hold runs expire_due first, so no call ever sees a hold that should have ended. This is lazy expiry, and it has three advantages over a timer thread: no extra thread to start, stop, and synchronize; no race between a timer and a confirm at the expiry instant, because both happen under the same lock in some order; and tests that never sleep.

The comparison is now >= expires_at, so a hold of 300 seconds is held at 299 seconds and gone at 300 (AC-3.1). One honest cost: expire_due walks every hold record, including ended ones, on every call. That is fine for a teaching example and a show with a few thousand holds; Production limitations says what a real service would do instead.

Note the second kind of hold that expires: paying. A hold does not stop its clock because its customer is paying. If the payment takes longer than the hold has left, the hold expires during it, and the seats can go to someone else. What happens to that customer’s money is finish_confirm’s job.

The statuses of one hold record inside the show
Text description of the diagram

A hold starts active. begin_confirm moves it to paying when a request claims it, and abandon_confirm moves it back to active if the charge threw. An active hold becomes expired when its time is up, and so does a paying hold whose time runs out during the payment. An active hold becomes released when the customer releases it; a paying hold becomes released if the customer releases it during the payment, or if the payment is declined. A paying hold becomes confirmed when the payment is approved and the hold is still paying. Expired, released, and confirmed are final, and the record is kept.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> active : hold
active --> paying : begin_confirm claims it
paying --> active : abandon_confirm, the charge threw
active --> expired : expire_due, time is up
paying --> expired : expire_due, time is up during the payment
active --> released : release
paying --> released : release during the payment, or the payment declined
paying --> confirmed : finish_confirm, approved and still paying
expired --> [*]
released --> [*]
confirmed --> [*]

The seat’s three states are what other customers see. The hold’s five statuses are what the show needs to answer a confirm correctly, and paying is the one that does the work: it is how the show knows, after a payment, whether the hold is still the one that was paid for.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking_service.cpp
// Three steps, and the show's lock is held only in the first and the last:
// 1. begin_confirm (locked): answer a repeat, or refuse, or claim the hold.
// 2. charge (no lock): the slow network call. Holding the lock here would
// make every customer of this show wait for one customer's bank.
// 3. finish_confirm (locked): re-check the hold, then book or give back.
// Dropping the lock in step 2 opens a race: while the money is being taken
// the hold can expire and its seats be held, or even booked, by someone
// else. Step 3 closes it by booking only if the hold is still `paying`; if
// not, the charge is refunded and nothing is booked.
ConfirmResult BookingService::confirm(const RequestId& request, const ShowId& show,
HoldId hold_id, const std::string& card) {
Show* target = find(show);
if (target == nullptr) return ConfirmError::unknown_show;
auto begun = target->begin_confirm(request, hold_id);
// get_if gives a pointer to the ConfirmResult if that is what begin
// returned (a repeat or a refusal), and nullptr if it returned PaymentDue.
if (const auto* answer = std::get_if<ConfirmResult>(&begun)) return *answer;
const Cents amount = std::get<Show::PaymentDue>(begun).amount;
PaymentResult paid;
try {
paid = payments_.charge(request, amount, card);
} catch (...) {
// Without this, the request would stay "in flight" forever and any
// repeat of it would wait in begin_confirm for good.
target->abandon_confirm(request, hold_id);
throw;
}
// Structured binding: names the two members of Show::Finished.
auto [result, refund] = target->finish_confirm(request, hold_id, paid);
// Also outside the lock. If refund threw, the customer would be owed
// money with no record of it; a real service would first save the owed
// refund durably and retry it until it succeeds.
if (refund) payments_.refund(paid.reference);
return result;
}

Confirm is the function the rest of the design exists to make safe. It is split into three parts, and the lock is held only in the first and the last.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
std::variant<ConfirmResult, Show::PaymentDue> Show::begin_confirm(const RequestId& request,
HoldId hold_id) {
// unique_lock, not lock_guard, because wait below must unlock and
// relock it.
std::unique_lock lock(mutex_);
// Idempotency first. If this request id is being paid for right now by
// another thread (record with no result yet), wait until it is decided.
// wait unlocks while asleep, relocks on waking, and re-checks the
// condition each time, so a spurious wake-up just waits again.
done_.wait(lock, [&] {
const auto seen = requests_.find(request);
return seen == requests_.end() || seen->second.result.has_value();
});
if (const auto seen = requests_.find(request); seen != requests_.end()) {
// The id was used before: give the same answer, booking or refusal,
// and never charge again. The same id for another hold is a client
// bug; refuse it and leave the stored answer alone.
if (seen->second.hold != hold_id) return ConfirmResult{ConfirmError::request_reused};
return *seen->second.result;
}
expire_due(clock_.now());
const auto found = holds_.find(hold_id);
if (found == holds_.end()) return decide(request, hold_id, ConfirmError::unknown_hold);
HoldRecord& record = found->second;
switch (record.status) {
case HoldStatus::active: break;
// Not stored with decide: the other payment may still fail, so this
// request id may be retried later and get a different answer.
case HoldStatus::paying: return ConfirmResult{ConfirmError::payment_in_progress};
case HoldStatus::expired: return decide(request, hold_id, ConfirmError::hold_expired);
case HoldStatus::released: return decide(request, hold_id, ConfirmError::hold_released);
case HoldStatus::confirmed:
return decide(request, hold_id, ConfirmError::already_confirmed);
}
// Claim the hold for this request: paying stops a second request id
// from charging for the same seats, and the empty result makes repeats
// of this request id wait above.
record.status = HoldStatus::paying;
requests_.insert_or_assign(request, RequestRecord{hold_id, std::nullopt});
return PaymentDue{record.hold.amount};
}

Part 1, begin_confirm, locked. It does one of three things:

  1. Answers a repeat. If this request id was decided before, it returns the stored answer, booking or refusal, and the caller never reaches the gateway. If the id is still in flight on another thread, it waits on the condition variable done_ until that answer exists, then returns it. The wait gives the lock up while asleep, so the first thread can finish.
  2. Refuses. An unknown, expired, released, or confirmed hold gets its reason, and the answer is stored with decide, so a repeat gets it too (AC-4.5). Two refusals are not stored, on purpose. request_reused is a client bug about a different hold, and must not overwrite the answer already stored for this id. payment_in_progress is temporary: the other request’s payment may fail, and then this id, sent again, should get a chance.
  3. Claims the hold. It moves the hold to paying, which stops any other request id, and stores the request with no result yet, which makes repeats of this id wait. Then it returns PaymentDue with the amount, and lets go of the lock.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
Show::Finished Show::finish_confirm(const RequestId& request, HoldId hold_id,
const PaymentResult& paid) {
const std::lock_guard lock(mutex_);
expire_due(clock_.now());
// at() cannot throw here: begin_confirm found this hold, and records
// are never erased.
HoldRecord& record = holds_.at(hold_id);
// The re-check that closes the race. The lock was free during the
// charge, so the hold may have expired meanwhile (and its seats been
// held by another customer), or been released. Only a hold that is
// still `paying` still owns its seats; anything else must not book.
const bool still_ours = record.status == HoldStatus::paying;
if (!paid.approved) {
// No money was taken. Give the seats back now rather than leave
// them blocked until the hold expires.
if (still_ours) {
free_seats(record.hold);
record.status = HoldStatus::released;
}
return {decide(request, hold_id, ConfirmError::payment_declined), false};
}
if (!still_ours) {
// Money was taken for seats this customer no longer has: refund.
return {decide(request, hold_id, ConfirmError::hold_lost_during_payment), true};
}
for (const SeatId seat : record.hold.seats) seat_at(seat).book();
record.status = HoldStatus::confirmed;
Booking booking{next_booking_++, id_, hold_id, record.hold.seats, record.hold.amount,
paid.reference};
return {decide(request, hold_id, std::move(booking)), false};
}

Part 2, the charge, no lock. BookingService::confirm calls payments_.charge with the request id as its key. For the second or more that this takes, every other customer of the show carries on.

Part 3, finish_confirm, locked. It takes the lock again, expires what is due, and asks the one question that matters: is this hold still paying? While the lock was free, the hold could have expired (and its seats been taken by another customer), or been released. Only a hold still paying still owns its seats.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
void Show::abandon_confirm(const RequestId& request, HoldId hold_id) {
const std::lock_guard lock(mutex_);
// Forget the request, so a retry with the same id starts again, and
// give the hold back to the customer if it is still paying: no call has
// expired or released it meanwhile. There is no expire_due here, so a
// hold already past its time becomes active, and the next call expires it.
requests_.erase(request);
const auto found = holds_.find(hold_id);
if (found != holds_.end() && found->second.status == HoldStatus::paying) {
found->second.status = HoldStatus::active;
}
done_.notify_all(); // waiters for this request id re-check and go on
}

If the charge throws, there is no PaymentResult to finish with. confirm catches the exception, calls abandon_confirm, and throws it on. Without that, the request record would stay “in flight” for ever, and every repeat of the id would wait in begin_confirm for good. abandon_confirm forgets the request and puts a still-paying hold back to active, so the customer can try again with the same id (AC-5.6). That is safe because the gateway received the same key: if the exception came after the charge was made, a real gateway that deduplicates by key would not charge twice.

How this code works: Every way out of BookingService::confirm

For one confirm of a hold, here is each path, what was charged, and what the caller gets.

Situation when the call arrives begin_confirm Charged? finish_confirm sees Answer Refund?
this id was decided, for this hold the stored answer no not called the first answer, again no
this id was used for another hold request_reused, not stored no not called request_reused no
this id is in flight on another thread waits, then the stored answer (if that try’s charge threw, goes on as a fresh try) no not called the first try’s answer no
no such hold unknown_hold, stored no not called unknown_hold no
hold paying for another id payment_in_progress, not stored no not called payment_in_progress no
hold expired, released, or confirmed its reason, stored no not called that reason no
hold active claims it: paying; PaymentDue yes declined, still paying: frees the seats payment_declined no
hold active claims it yes declined, hold lost meanwhile payment_declined no
hold active claims it yes approved, hold lost meanwhile hold_lost_during_payment yes
hold active claims it yes approved, still paying: books the seats the Booking no
hold active claims it threw not called; abandon_confirm instead the exception, rethrown no

Three things to notice:

  1. Only one row books, and it is the one where the hold was still paying after an approved payment. That is INV-4.
  2. Only one row refunds, and it is the one where money was taken for seats the customer no longer has. That is FR-7.
  3. “Charged?” is “yes” only for a request that claimed an active hold, and a hold can be claimed by one request at a time (INV-3). So for any hold, at most one charge is in flight, and for any request id, at most one charge is ever made, unless the gateway threw and the id is tried again; then the gateway’s key is what prevents a second charge.

The refund itself is also made with no lock held, after finish_confirm returns. If refund threw, the exception would reach the caller and the owed refund would be recorded nowhere. A real service would write “refund owed” to durable storage first and retry it until it succeeds; this example does not, and says so in its comment and in Production limitations.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking_service.hpp
// The front door: finds the show and, for confirm, runs the payment between
// the two locked halves of the show's work.
//
// Ownership: the service owns its shows (each in a std::unique_ptr, since a
// Show holds a mutex and cannot move). It does not own the clock or the
// gateway; they are references and must outlive the service.
//
// Threads: hold, release, confirm, and the queries may be called from any
// number of threads at once. add_show is setup: call it before the service
// is shared, because it changes the map of shows that the other functions
// read without a lock.
class BookingService {
public:
BookingService(const Clock& clock, PaymentGateway& payments, std::chrono::seconds hold_for)
: clock_(clock), payments_(payments), hold_for_(hold_for) {}
// Throws std::invalid_argument for a repeated id or a bad layout (see Show).
void add_show(const ShowId& id, int rows, int seats_per_row, Cents price_per_seat);
HoldResult hold(const ShowId& show, const std::vector<SeatId>& seats);
// False if the show or hold is unknown, or the hold has already ended
// (expired, released, or confirmed). A hold being paid for can be released.
bool release(const ShowId& show, HoldId hold_id);
// Pays for and books a hold. Safe to repeat with the same request id:
// the payment is taken at most once, and every call returns the result
// of the first. card is passed to the gateway. If the gateway throws,
// the exception propagates, the hold is kept (unless it ran out
// meanwhile), and the same request id may be retried.
ConfirmResult confirm(const RequestId& request, const ShowId& show, HoldId hold_id,
const std::string& card);
std::optional<SeatState> state_of(const ShowId& show, SeatId seat) const;
// For tests and the demo. nullptr if there is no such show.
[[nodiscard]] Show* find(const ShowId& show) const;
private:
const Clock& clock_;
PaymentGateway& payments_;
const std::chrono::seconds hold_for_;
std::map<ShowId, std::unique_ptr<Show>> shows_;
};

BookingService finds the show and runs the three parts of confirm. Its own map of shows is read without a lock, which is safe only because add_show is setup, called before the service is shared. The comment says so: a contract about threads is part of the interface, as in Thread-safety contracts. A service that had to add shows while selling would need a std::shared_mutex around that map, or a map built once and swapped.

Rule Where it lives
Which seat moves are legal can_move, enforced by Seat::move_to
A hold is all or nothing Show::hold: pass 1 checks, pass 2 marks, one lock
When a hold ends Show::expire_due, run first in every call, with clock_.now()
One request at a time pays for a hold begin_confirm, the paying status
A repeat gets the first answer begin_confirm’s wait and lookup; decide
Book only a hold that is still ours finish_confirm’s still_ours
Refund money taken for a lost hold finish_confirm says so; BookingService::confirm does it
No lock during the payment BookingService::confirm, between the two locked calls
A thrown charge leaves the hold usable BookingService::confirm’s catch, abandon_confirm

Take the last customer in the step 1 demo. Erin holds B1, and Erin’s bank is slow: while the payment is in flight, the hold runs out and Frank holds the same seat.

A hold that expires while its payment is in flight, and the refund
Text description of the diagram

Erin’s app asks the service to confirm hold 4 with request id erin-1. The service calls begin_confirm on the show, which takes the lock, finds hold 4 active, marks it paying, lets go of the lock, and returns payment due of 2500 cents. The service asks the gateway to charge 2500 with key erin-1. The charge is slow, and the clock reaches 19:10, the hold’s expiry. Meanwhile Frank’s app asks to hold B1. The show takes the lock, expire_due ends hold 4, B1 is free, and Frank gets hold 5 on B1. The gateway then approves Erin’s charge with reference pay-3. The service calls finish_confirm, which takes the lock and finds hold 4 expired rather than paying, stores the answer, and asks for a refund. The service refunds pay-3 and tells Erin that the confirm was refused and refunded.

Diagram source (Mermaid)
sequenceDiagram
participant E as Erin's app
participant S as BookingService
participant H as Show
participant G as gateway
participant F as Frank's app
E->>S: confirm(erin-1, hold 4)
S->>H: begin_confirm(erin-1, 4)
Note over H: lock, hold 4 active so now paying, unlock
H-->>S: PaymentDue 2500
S->>G: charge(erin-1, 2500, card)
Note over G: slow, and meanwhile the hold runs out
F->>S: hold(B1)
S->>H: hold(B1)
Note over H: lock, expire_due ends hold 4, B1 free, hold 5, unlock
H-->>F: hold 5 on B1
G-->>S: approved, pay-3
S->>H: finish_confirm(erin-1, 4, approved)
Note over H: lock, hold 4 expired not paying, store answer, unlock
H-->>S: hold_lost_during_payment, refund
S->>G: refund(pay-3)
S-->>E: refused, refunded

Step by step, in the code (the times are the demo’s clock):

  1. At 19:05, hold({B1}) makes hold 4, expiring at 19:10. Hold 3, Dan’s, was released by Dan’s declined payment, so B1 is free.
  2. confirm("erin-1", "evening", 4, good_card) calls begin_confirm. The request id is new, expire_due(19:05) ends nothing, hold 4 is active, so it becomes paying, and {4, no result} is stored under erin-1. It returns PaymentDue{2500}.
  3. charge runs the demo’s hook first. The hook moves the clock 5 minutes to 19:10 and calls service.hold("evening", {B1}) on the same thread. That call takes the show’s lock, which it could not do if confirm still held it: a std::mutex locked twice by one thread is undefined behaviour, and in practice a hang.
  4. Inside that hold, expire_due(19:10) finds hold 4 paying with 19:10 >= 19:10, frees B1, and marks hold 4 expired. Pass 1 finds B1 available; pass 2 makes hold 5 for Frank, expiring at 19:15. The demo prints “frank holds B1: hold 5 on B1, $25.00”.
  5. Back in charge, the fake records the third charge and approves it as pay-3.
  6. finish_confirm finds hold 4 expired, so still_ours is false. The payment was approved, so it stores hold_lost_during_payment for erin-1 and returns refund = true. B1 is untouched: it is Frank’s.
  7. confirm calls refund("pay-3") with no lock held, and returns the refusal. The demo prints “charges: 3, refunds: 1”, and the map shows B1 as h, Frank’s hold.

Now move the moment of expiry. If the hold had expired before begin_confirm, Erin would get hold_expired and no charge (AC-3.2). If it had expired after finish_confirm, the seat would already be booked, and bookings do not expire (AC-3.3). If the payment had been declined, there would be nothing to refund (AC-5.5). Every timing ends with either a booking that was paid for, or no booking and no money kept.

Each design choice above answers a mistake that is easy to make. Here are six of them, each next to the correction the example uses. The flawed sketches are short on purpose, and each one was compiled (syntax only) against the step 1 headers; none is part of the example.

  • No State pattern classes. A seat has three states and three moves, with no behaviour that differs per state beyond “is this move allowed”. A table and an enum say that in a few lines; a class per state would add files and hide the table. See State for when the classes do pay.
  • No timer thread. Lazy expiry, for the reasons above.
  • No lock per seat. One mutex per show, until a measurement says otherwise (see The show).
  • No exceptions for refusals. A taken seat is a normal answer, so it is a value. Exceptions are for bugs and for a gateway that fails.
  • No database. Everything is in memory in one process. That is the largest gap between this example and a real box office, and Production limitations is honest about what it costs.

The example has two steps, each a complete program with its own tests:

  • Step 1 is the design above: seats, holds with expiry, confirm with payment, idempotent repeats, and the race with expiry.
  • Step 2 is the change: group bookings, where the service chooses the seats. See When the requirements change.

A good order for building step 1 yourself, with each part tested before the next one leans on it:

  1. SeatState and can_move, with the table test (AC-1.2). No show, no clock.
  2. Show::hold and release on one thread, with the injected clock from the start, and expiry right after (AC-2.x, AC-3.x).
  3. The fake gateway, with its decline list and its during_charge hook.
  4. Confirm, single-threaded. Write the first race test (AC-5.2) with the hook early: it is what shows that confirm must be split into begin_confirm and finish_confirm.
  5. Request ids and stored answers (AC-4.x), then the wait for an in-flight request (AC-6.6), then abandon_confirm (AC-5.6).
  6. The thread tests last (AC-6.x). By then every race they could find should already have a single-threaded test with the hook that plays it out on purpose.

The demo runs one show, “evening”, of 2 rows of 4 seats at $25.00, with holds of 5 minutes, and a clock that starts at 19:00 on 5 December 2026. Six customers meet each rule once, and Erin meets the hardest one.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
ManualClock clock{sys_days{2026y / 12 / 5} + 19h};
FakePaymentGateway payments;
payments.decline(bad_card);
BookingService service{clock, payments, 5min};
service.add_show("evening", 2, 4, 2500);
Show& show = *service.find("evening");
const HoldResult alice = service.hold("evening", {{'A', 1}, {'A', 2}});
report("alice holds A1 A2", alice);
report("bob holds A2 A3", service.hold("evening", {{'A', 2}, {'A', 3}}));
std::cout << "A3 after bob's refusal: " << to_string(show.state_of({'A', 3}).value()) << "\n";
report("alice confirms (alice-1)",
service.confirm("alice-1", "evening", alice.value().id, good_card));
report("alice's app retries (alice-1)",
service.confirm("alice-1", "evening", alice.value().id, good_card));
std::cout << "charges so far: " << payments.charges().size() << "\n";
const HoldResult carol = service.hold("evening", {{'B', 1}});
report("carol holds B1", carol);
clock.advance(5min);
std::cout << "five minutes pass\n";
report("carol confirms (carol-1)",
service.confirm("carol-1", "evening", carol.value().id, good_card));
const HoldResult dan = service.hold("evening", {{'B', 1}, {'B', 2}});
report("dan holds B1 B2", dan);
report("dan confirms with a declined card (dan-1)",
service.confirm("dan-1", "evening", dan.value().id, bad_card));
std::cout << "B1 after dan: " << to_string(show.state_of({'B', 1}).value()) << "\n";
// Erin's bank is slow: while their payment is in flight, their hold runs
// out and frank holds the same seat.
const HoldResult erin = service.hold("evening", {{'B', 1}});
report("erin holds B1", erin);
bool slow = true; // only erin's charge is slow
payments.during_charge([&] {
if (!slow) return;
slow = false;
clock.advance(5min);
std::cout << " (during erin's payment, five minutes pass)\n";
report(" frank holds B1", service.hold("evening", {{'B', 1}}));
});
report("erin confirms (erin-1)",
service.confirm("erin-1", "evening", erin.value().id, good_card));
std::cout << "charges: " << payments.charges().size()
<< ", refunds: " << payments.refunds().size() << "\n";
std::cout << "seats (. available, h held, X booked):\n";
print_map(show);
std::cout << "invariants hold: " << (show.invariants_hold() ? "yes" : "no") << "\n";
}
Expected output
alice holds A1 A2: hold 1 on A1 A2, $50.00
bob holds A2 A3: refused, a seat is held by someone else
A3 after bob's refusal: available
alice confirms (alice-1): booking 1 for A1 A2, $50.00, payment pay-1
alice's app retries (alice-1): booking 1 for A1 A2, $50.00, payment pay-1
charges so far: 1
carol holds B1: hold 2 on B1, $25.00
five minutes pass
carol confirms (carol-1): refused, the hold has expired
dan holds B1 B2: hold 3 on B1 B2, $50.00
dan confirms with a declined card (dan-1): refused, the payment was declined
B1 after dan: available
erin holds B1: hold 4 on B1, $25.00
(during erin's payment, five minutes pass)
frank holds B1: hold 5 on B1, $25.00
erin confirms (erin-1): refused, the hold ran out during payment; the payment was refunded
charges: 3, refunds: 1
seats (. available, h held, X booked):
A XX..
B h...
invariants hold: yes

Read the output against the rules:

  • Bob asks for A2 A3 while Alice holds A2. Bob is refused, and A3, which was free, is still free afterwards: all or nothing (FR-2).
  • Alice’s app retries with the same request id, alice-1, and gets the same booking, booking 1 with payment pay-1. “charges so far: 1” shows that the retry did not pay again (NFR-1).
  • Carol waits five minutes, and the confirm is refused with no charge: Carol’s hold ended at 19:05, and the clock read 19:05.
  • Dan’s card is declined, and B1 is available straight away, not after Dan’s hold would have run out.
  • Erin is the verification trace above. Erin’s hold, hold 4, expires while the bank is slow; Frank holds B1 as hold 5; Erin’s charge, pay-3, is refunded. That is why the totals read 3 charges (Alice, Dan’s declined one, Erin) and 1 refund.
  • The seat map shows A1 A2 booked by Alice and B1 held by Frank. Everything else is free: Carol’s and Dan’s holds ended.

Step 1 has 31 tests, one or more for each acceptance criterion, and they all share one small helper.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// One show "s" of 2 rows of 4 seats at $10.00 each, holds of 300 seconds,
// a manual clock, and a fake gateway that declines bad_card.
struct World {
ManualClock clock{start};
FakePaymentGateway payments;
BookingService service{clock, payments, 300s};
explicit World(int rows = 2, int per_row = 4) {
payments.decline(bad_card);
service.add_show("s", rows, per_row, 1000);
}
Show& show() { return *service.find("s"); }
HoldResult hold(const std::vector<SeatId>& seats) { return service.hold("s", seats); }
ConfirmResult confirm(const RequestId& request, HoldId hold_id,
const std::string& with = card) {
return service.confirm(request, "s", hold_id, with);
}
SeatState state(SeatId seat) { return service.state_of("s", seat).value(); }
};

World builds a fresh service for each test: a show “s” of 2 rows of 4 seats at $10.00, holds of 300 seconds, a manual clock, and a fake gateway that declines bad_card. No test shares state with another, and none sleeps.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_1_2_a_seat_moves_only_along_legal_transitions) {
using enum SeatState;
LLD_CHECK(can_move(available, held));
LLD_CHECK(can_move(held, available));
LLD_CHECK(can_move(held, booked));
LLD_CHECK(!can_move(available, available));
LLD_CHECK(!can_move(available, booked)); // never booked without a hold
LLD_CHECK(!can_move(held, held));
LLD_CHECK(!can_move(booked, available)); // no cancellation in step 1
LLD_CHECK(!can_move(booked, held));
LLD_CHECK(!can_move(booked, booked));
Seat seat;
LLD_CHECK_THROWS(seat.book(), std::logic_error);
LLD_CHECK_THROWS(seat.release(), std::logic_error);
seat.hold(HoldId{7});
LLD_CHECK_THROWS(seat.hold(HoldId{8}), std::logic_error);
LLD_CHECK_EQ(seat.holder().value, std::uint64_t{7}); // the failed hold changed nothing
seat.book();
LLD_CHECK_THROWS(seat.release(), std::logic_error);
LLD_CHECK_EQ(seat.state(), booked);
}

All nine pairs of states, checked against the three legal moves, then illegal moves on a real Seat, to show that each one throws and that a failed move changes nothing.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_2_3_a_hold_of_several_seats_is_all_or_nothing) {
World world;
const HoldResult taken = world.hold({{'A', 3}});
// A3 is held, so asking for A1 A2 A3 takes nothing, not just A1 and A2.
LLD_CHECK_EQ(world.hold({{'A', 1}, {'A', 2}, {'A', 3}}).error(), HoldError::seat_held);
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::available);
LLD_CHECK_EQ(world.state({'A', 2}), SeatState::available);
LLD_CHECK(world.confirm("r1", taken.value().id).has_value());
LLD_CHECK_EQ(world.hold({{'A', 2}, {'A', 3}}).error(), HoldError::seat_booked);
LLD_CHECK_EQ(world.state({'A', 2}), SeatState::available);
LLD_CHECK_EQ(world.show().count(SeatState::held), std::size_t{0});
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_3_1_a_hold_expires_exactly_at_its_expiry_time) {
World world;
LLD_CHECK(world.hold({{'A', 1}}).has_value());
world.clock.advance(299s);
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::held);
LLD_CHECK_EQ(world.hold({{'A', 1}}).error(), HoldError::seat_held);
world.clock.advance(1s); // now == expires_at: the hold is over
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::available);
LLD_CHECK(world.hold({{'A', 1}}).has_value());
LLD_CHECK(world.show().invariants_hold());
}
LLD_TEST(ac_3_2_confirm_after_expiry_is_refused_and_charges_nothing) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
world.clock.advance(300s);
LLD_CHECK_EQ(world.confirm("r1", hold.value().id).error(), ConfirmError::hold_expired);
LLD_CHECK_EQ(world.confirm("r1", hold.value().id).error(), ConfirmError::hold_expired);
LLD_CHECK_EQ(world.confirm("r2", hold.value().id).error(), ConfirmError::hold_expired);
LLD_CHECK(world.payments.charges().empty());
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::available);
}
LLD_TEST(ac_3_3_confirm_one_second_before_expiry_books) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
world.clock.advance(299s);
LLD_CHECK(world.confirm("r1", hold.value().id).has_value());
world.clock.advance(1h); // a booking does not expire
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::booked);
}

The expiry tests are where the injected clock pays for itself. They move the clock to the second before expiry and to the second of expiry, which a test that sleeps could never hit exactly.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_4_2_the_same_request_id_gets_the_same_result_and_pays_once) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
const ConfirmResult first = world.confirm("r1", hold.value().id);
world.clock.advance(1h); // long after the hold would have expired
const ConfirmResult again = world.confirm("r1", hold.value().id);
LLD_CHECK(first.has_value());
LLD_CHECK(again == first);
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}
LLD_TEST(ac_4_3_a_request_id_reused_for_another_hold_is_refused) {
World world;
const HoldResult one = world.hold({{'A', 1}});
const HoldResult two = world.hold({{'A', 2}});
LLD_CHECK(world.confirm("r1", one.value().id).has_value());
LLD_CHECK_EQ(world.confirm("r1", two.value().id).error(), ConfirmError::request_reused);
LLD_CHECK_EQ(world.state({'A', 2}), SeatState::held);
// The stored answer for r1 is untouched.
LLD_CHECK(world.confirm("r1", one.value().id).has_value());
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}
LLD_TEST(ac_4_4_a_second_request_id_for_a_confirmed_hold_is_refused) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
LLD_CHECK(world.confirm("r1", hold.value().id).has_value());
LLD_CHECK_EQ(world.confirm("r2", hold.value().id).error(), ConfirmError::already_confirmed);
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}
LLD_TEST(ac_4_5_a_refusal_is_repeated_too) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
LLD_CHECK_EQ(world.confirm("r1", hold.value().id, bad_card).error(),
ConfirmError::payment_declined);
// Same id, now with a good card: still the first answer, no new charge.
LLD_CHECK_EQ(world.confirm("r1", hold.value().id, card).error(),
ConfirmError::payment_declined);
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}

Each test checks two things: the answer, and the number of charges the fake recorded. An idempotent call that returns the right answer but pays twice would pass the first check and fail the second.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// The race that dropping the lock opens, played out in one thread: the
// gateway's hook runs while the payment is "in flight" with no lock held.
LLD_TEST(ac_5_2_a_hold_that_expires_during_payment_is_refunded_not_booked) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
HoldResult other = HoldError::no_seats; // replaced inside the hook
world.payments.during_charge([&] {
world.clock.advance(300s); // the hold runs out...
other = world.hold({{'A', 1}}); // ...and another customer takes the seat
});
LLD_CHECK_EQ(world.confirm("r1", hold.value().id).error(),
ConfirmError::hold_lost_during_payment);
LLD_CHECK(other.has_value());
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::held); // still the other customer's
LLD_CHECK_EQ(world.show().count(SeatState::booked), std::size_t{0});
const auto refunds = world.payments.refunds();
LLD_CHECK_EQ(refunds.size(), std::size_t{1});
LLD_CHECK_EQ(refunds.at(0), std::string("pay-1"));
LLD_CHECK(world.show().invariants_hold());
// The other customer can still confirm the seat.
world.payments.during_charge(nullptr);
LLD_CHECK(world.confirm("r2", other.value().id).has_value());
}
LLD_TEST(ac_5_3_a_hold_released_during_payment_is_refunded_not_booked) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
world.payments.during_charge([&] { LLD_CHECK(world.service.release("s", hold.value().id)); });
LLD_CHECK_EQ(world.confirm("r1", hold.value().id).error(),
ConfirmError::hold_lost_during_payment);
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::available);
LLD_CHECK_EQ(world.payments.refunds().size(), std::size_t{1});
}
LLD_TEST(ac_5_4_a_second_request_id_during_payment_is_refused_not_charged) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
ConfirmResult during = ConfirmError::unknown_hold; // replaced inside the hook
bool first_call = true;
world.payments.during_charge([&] {
if (!first_call) return;
first_call = false;
during = world.confirm("r2", hold.value().id);
});
LLD_CHECK(world.confirm("r1", hold.value().id).has_value());
LLD_CHECK_EQ(during.error(), ConfirmError::payment_in_progress);
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
// payment_in_progress was not stored, so r2 now gets the current answer.
LLD_CHECK_EQ(world.confirm("r2", hold.value().id).error(), ConfirmError::already_confirmed);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_5_5_a_decline_after_the_hold_expired_during_payment_refunds_nothing) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
world.payments.during_charge([&] { world.clock.advance(300s); });
LLD_CHECK_EQ(world.confirm("r1", hold.value().id, bad_card).error(),
ConfirmError::payment_declined);
LLD_CHECK(world.payments.refunds().empty());
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::available);
LLD_CHECK(world.show().invariants_hold());
}
LLD_TEST(ac_5_6_a_gateway_that_throws_leaves_the_hold_for_a_retry) {
World world;
const HoldResult hold = world.hold({{'A', 1}});
bool fail = true;
world.payments.during_charge([&] {
if (fail) {
fail = false;
throw std::runtime_error("network down");
}
});
LLD_CHECK_THROWS(world.confirm("r1", hold.value().id), std::runtime_error);
LLD_CHECK_EQ(world.state({'A', 1}), SeatState::held);
LLD_CHECK(world.payments.charges().empty());
// The same request id starts again rather than waiting for ever.
LLD_CHECK(world.confirm("r1", hold.value().id).has_value());
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}

These are the most important tests in the case study, and none of them starts a thread. The during_charge hook runs in the middle of the confirm, at the exact moment the lock is free, and does what another customer might have done there: moves the clock past expiry, releases the hold, or sends a second request id. The race happens every time, in the same order, and a failure points at one line. Real threads can only hope to hit that moment.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Sixteen threads wait at a latch, so they all try to hold seat A1 at the
// same moment. Exactly one may win, every round.
LLD_TEST(ac_6_1_many_threads_holding_one_seat_exactly_one_wins) {
constexpr int threads = 16;
for (int round = 0; round < 50; ++round) {
World world;
std::vector<HoldResult> results(threads, HoldError::no_seats);
{
std::latch start_together(threads);
std::vector<std::jthread> pool;
for (int t = 0; t < threads; ++t) {
// Each thread writes only its own element of results, so the
// writes do not race; the join below publishes them.
pool.emplace_back([&world, &results, &start_together, t] {
start_together.arrive_and_wait();
results[static_cast<std::size_t>(t)] = world.hold({{'A', 1}});
});
}
} // jthreads join here
int winners = 0;
for (const HoldResult& result : results) {
if (result.has_value()) {
++winners;
} else {
LLD_CHECK_EQ(result.error(), HoldError::seat_held);
}
}
LLD_CHECK_EQ(winners, 1);
LLD_CHECK(world.show().invariants_hold());
}
}
// Overlapping pairs: A1A2, A2A3, A3A4, A4A1 and so on, all at once. However
// the threads interleave, no seat may end up in two holds.
LLD_TEST(ac_6_2_overlapping_multi_seat_holds_never_share_a_seat) {
constexpr int threads = 8;
for (int round = 0; round < 50; ++round) {
World world;
std::vector<HoldResult> results(threads, HoldError::no_seats);
{
std::latch start_together(threads);
std::vector<std::jthread> pool;
for (int t = 0; t < threads; ++t) {
pool.emplace_back([&world, &results, &start_together, t] {
const char row = t < 4 ? 'A' : 'B';
const std::vector<SeatId> pair{{row, t % 4 + 1}, {row, (t + 1) % 4 + 1}};
start_together.arrive_and_wait();
results[static_cast<std::size_t>(t)] = world.hold(pair);
});
}
}
std::set<SeatId> taken;
std::size_t held = 0;
for (const HoldResult& result : results) {
if (!result.has_value()) continue;
for (const SeatId seat : result.value().seats) {
LLD_CHECK(taken.insert(seat).second); // never a seat twice
++held;
}
}
LLD_CHECK_EQ(world.show().count(SeatState::held), held);
LLD_CHECK(held >= 4); // at least one pair wins in each row
LLD_CHECK(world.show().invariants_hold());
}
}
How this code works: How the latch makes threads start together

Take AC-6.1, the 16 threads that all want A1.

  1. std::latch start_together(threads) is a counter set to 16. arrive_and_wait takes one off and then blocks until it reaches 0.
  2. Each std::jthread starts, and its first act is arrive_and_wait. The first 15 to arrive block; the 16th brings the count to 0, and all 16 are released together. Without the latch, the first thread could finish its hold before the last one has even been created, and the test would be a sequence, not a race.
  3. Each thread writes only results[t], its own element. Sixteen writes to sixteen different elements are not a data race.
  4. The closing brace destroys the vector of jthreads, and each destructor joins its thread. After the join, the main thread may read every result: joining a thread makes its writes visible.
  5. The checks: exactly one result is a hold, and the other 15 are seat_held. Then invariants_hold() checks that the seat map and the hold records agree.

The test repeats that 50 times with a fresh World each round, because one round tests one interleaving.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Eight threads confirm with the same request id (a client retrying while
// the first try is still running). One charge, and every thread gets the
// same booking: the later ones wait in begin_confirm for the first, or
// read its stored answer if they arrive after it is decided.
LLD_TEST(ac_6_3_concurrent_repeats_of_one_request_pay_once_and_agree) {
constexpr int threads = 8;
for (int round = 0; round < 30; ++round) {
World world;
const HoldId hold = world.hold({{'A', 1}}).value().id;
std::vector<ConfirmResult> results(threads, ConfirmError::unknown_hold);
{
std::latch start_together(threads);
std::vector<std::jthread> pool;
for (int t = 0; t < threads; ++t) {
pool.emplace_back([&world, &results, &start_together, hold, t] {
start_together.arrive_and_wait();
results[static_cast<std::size_t>(t)] = world.confirm("same", hold);
});
}
}
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
for (const ConfirmResult& result : results) {
LLD_CHECK(result.has_value());
LLD_CHECK(result == results.front());
}
}
}
// Eight threads confirm one hold with eight different request ids. Exactly
// one booking and one charge; the others are told why not.
LLD_TEST(ac_6_4_concurrent_confirms_of_one_hold_book_it_once) {
constexpr int threads = 8;
for (int round = 0; round < 30; ++round) {
World world;
const HoldId hold = world.hold({{'A', 1}, {'A', 2}}).value().id;
std::vector<ConfirmResult> results(threads, ConfirmError::unknown_hold);
{
std::latch start_together(threads);
std::vector<std::jthread> pool;
for (int t = 0; t < threads; ++t) {
pool.emplace_back([&world, &results, &start_together, hold, t] {
start_together.arrive_and_wait();
results[static_cast<std::size_t>(t)] =
world.confirm("r" + std::to_string(t), hold);
});
}
}
int booked = 0;
for (const ConfirmResult& result : results) {
if (result.has_value()) {
++booked;
} else {
LLD_CHECK(result.error() == ConfirmError::already_confirmed ||
result.error() == ConfirmError::payment_in_progress);
}
}
LLD_CHECK_EQ(booked, 1);
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
LLD_CHECK_EQ(world.show().count(SeatState::booked), std::size_t{2});
}
}
// The show's lock must be free while the gateway works. Inside the charge,
// another thread asks for a seat's state, which needs the lock. If the lock
// were held, that thread could not finish and wait_for would time out. The
// future lives outside the hook, so even then the test does not deadlock:
// the thread finishes once confirm drops the lock.
LLD_TEST(ac_6_5_the_lock_is_not_held_while_the_gateway_is_called) {
World world;
const HoldId hold = world.hold({{'A', 1}}).value().id;
std::future<std::optional<SeatState>> probe;
bool answered = false;
world.payments.during_charge([&] {
probe = std::async(std::launch::async, [&world] {
return world.service.state_of("s", {'A', 2});
});
answered = probe.wait_for(10s) == std::future_status::ready;
});
LLD_CHECK(world.confirm("r1", hold).has_value());
LLD_CHECK(answered);
LLD_CHECK(probe.get() == SeatState::available);
}
// A repeat of a request, on another thread, started while the first try's
// payment is in flight. The hook then keeps the payment in flight for
// 200 ms and checks that the repeat has not answered: its answer cannot
// exist yet, so it must be waiting in begin_confirm. A repeat that did not
// wait (that said payment_in_progress, say) would answer well within that
// time. If the machine is so busy that the repeat has not even reached the
// show by then, it reads the stored answer later and the test still
// passes, without having exercised the wait; it can never fail falsely.
LLD_TEST(ac_6_6_a_repeat_during_payment_waits_for_the_first_answer) {
World world;
const HoldId hold = world.hold({{'A', 1}}).value().id;
std::future<ConfirmResult> repeat;
bool answered_early = true;
bool first_call = true;
world.payments.during_charge([&] {
if (!first_call) return;
first_call = false;
repeat = std::async(std::launch::async,
[&world, hold] { return world.confirm("r1", hold); });
answered_early = repeat.wait_for(200ms) == std::future_status::ready;
});
const ConfirmResult first = world.confirm("r1", hold);
LLD_CHECK(first.has_value());
LLD_CHECK(!answered_early);
LLD_CHECK(repeat.get() == first); // woken by the first answer, and the same
LLD_CHECK_EQ(world.payments.charges().size(), std::size_t{1});
}

AC-6.6 shows how easy it is to write a thread test that never tests what its name says. An earlier version started the repeat in the hook and let the payment finish at once. In a scratch copy built by hand with g++, with begin_confirm changed so that an in-flight repeat answers payment_in_progress instead of waiting, that version passed in 50 runs out of 50: starting a thread takes longer than the rest of the payment, so the repeat always arrived after the answer was stored and never met the wait. The version above keeps the payment in flight for 200 ms and checks that the repeat has not answered by then; the same broken begin_confirm failed it in 20 runs out of 20. A correct begin_confirm can never fail it, because the repeat’s answer does not exist until the payment returns. It is still a timing argument, not a proof: on a machine too busy to start the repeat within 200 ms, the test passes without having reached the wait.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Eight customers, each doing 300 random holds, confirms (some with a
// declined card), and releases, while another thread moves the clock on so
// holds can expire mid-flight. The schedule differs on every run; the
// checks are the invariants that must hold for every schedule.
LLD_TEST(ac_6_7_random_customers_never_double_book_and_money_matches) {
World world(3, 5);
constexpr int customers = 8;
std::vector<std::vector<Booking>> bookings(customers);
{
std::latch start_together(customers + 1);
std::vector<std::jthread> pool;
for (int c = 0; c < customers; ++c) {
pool.emplace_back([&world, &bookings, &start_together, c] {
std::mt19937 random(static_cast<std::mt19937::result_type>(c + 1));
std::uniform_int_distribution<int> row(0, 2), number(1, 5), size(1, 3), act(0, 3);
start_together.arrive_and_wait();
for (int step = 0; step < 300; ++step) {
std::vector<SeatId> seats;
const int wanted = size(random);
for (int i = 0; i < wanted; ++i) {
seats.push_back({static_cast<char>('A' + row(random)), number(random)});
}
const HoldResult hold = world.hold(seats);
if (!hold.has_value()) continue;
const int choice = act(random);
if (choice == 0) {
static_cast<void>(world.service.release("s", hold.value().id));
} else if (choice <= 2) {
const std::string request = std::to_string(c) + "-" + std::to_string(step);
const ConfirmResult result = world.confirm(
request, hold.value().id, choice == 1 ? card : bad_card);
if (result.has_value()) {
bookings[static_cast<std::size_t>(c)].push_back(result.value());
}
} // choice 3: walk away and let the hold expire
}
});
}
pool.emplace_back([&world, &start_together] {
start_together.arrive_and_wait();
for (int tick = 0; tick < 200; ++tick) world.clock.advance(60s);
});
}
std::set<SeatId> sold;
Cents booked_amount = 0;
std::size_t booked_seats = 0;
for (const auto& list : bookings) {
for (const Booking& booking : list) {
booked_amount += booking.amount;
for (const SeatId seat : booking.seats) {
LLD_CHECK(sold.insert(seat).second); // the invariant: never sold twice
++booked_seats;
}
}
}
LLD_CHECK_EQ(world.show().count(SeatState::booked), booked_seats);
// Money kept = approved charges minus refunds = what the bookings cost.
std::map<std::string, Cents> approved;
std::size_t index = 0;
for (const auto& charge : world.payments.charges()) {
++index; // the fake numbers references by position: pay-1, pay-2, ...
if (charge.card == card) approved["pay-" + std::to_string(index)] = charge.amount;
}
for (const std::string& refund : world.payments.refunds()) approved.erase(refund);
Cents kept = 0;
for (const auto& entry : approved) kept += entry.second;
LLD_CHECK_EQ(kept, booked_amount);
LLD_CHECK(world.show().invariants_hold());
}

AC-6.7 is a stress test: eight customers make 300 random requests each, while a ninth thread moves the clock on 200 times by a minute, so holds can expire between a hold and its confirm, or during a payment. Whether, and how often, that happens differs on every run, and the test does not count it; the single-threaded hook tests are what make sure those paths run. It does not check particular answers, which differ on every run. It checks the two rules that must hold for every run: no seat is sold twice, and the money kept (approved charges minus refunds) equals what the bookings cost.

What the thread tests prove, and what they cannot

Section titled “What the thread tests prove, and what they cannot”

They show that, on the runs that happened, with the interleavings the operating system chose, no seat was sold twice, no request paid twice, and the money added up. That is real evidence, but it is a sample:

  • A pass is not a proof. A rare interleaving may never happen on the test machine. See Why passing tests do not prove correctness. That is why every race this design knows about also has a single-threaded test with the hook, which hits it every time.
  • ThreadSanitizer sees only what ran. The tsan preset runs these tests under ThreadSanitizer; it reports a data race on a path that executed, and says nothing about a path that did not.
  • No fairness, no speed. Nothing here shows that a customer who asks first gets the seat, or how long anyone waits. std::mutex promises neither, and the tests do not measure either.
  • One process. The tests cover threads sharing memory, not two servers sharing a database.

The example’s checks, last run for the review on 2026-11-28: the gcc-debug, clang-debug, and asan-ubsan presets build both steps and pass every test and both demos, and the tsan preset ran both test programs 10 times in a row with no failure. A mutation check (changing the code on purpose and seeing a test fail) was reported as 14 of 14 mutants killed when the example was written; it was not rerun for this page.

The box office comes back after the first month:

“Families and school trips keep phoning us because the app makes them pick seats one at a time, and someone else takes the seat next to theirs while they are choosing. Let a group ask for a number of seats, ‘four together’ or ‘five anywhere’, and let the system pick.”

One new requirement:

  • FR-8 A customer can hold a group of seats by size alone. If the group asks to sit together, the seats are side by side in one row; otherwise they may be anywhere. The service chooses the seats by a fixed, documented rule, and the group is held, paid for, and expires as one unit.

Two questions are worth asking before writing any code:

  • Which seats, when several blocks fit? Answer agreed with the box office: the front-most row that has a block, and in it the lowest seat numbers. A fixed rule means the same request on the same seat map always gets the same seats, so a test can name them.
  • What if “together” is impossible but “anywhere” would work? The service refuses with a reason, and the customer decides whether to ask again without “together”. The service does not quietly split the group.

UC-7 Hold a group.

  • AC-7.1 A group anywhere gets the first free seats in row order.
  • AC-7.2 A group together gets the first block in the earliest row.
  • AC-7.3 A block never spans two rows.
  • AC-7.4 A group together may fill a row, but not exceed it.
  • AC-7.5 A group that cannot be met is refused and changes nothing.
  • AC-7.6 Seats of expired holds are free for a group.
  • AC-7.7 A group confirms as one booking and one charge.
  • AC-7.8 A group expires, and is released, together.
  • AC-7.9 A declined group payment releases every seat.
  • AC-7.10 A group hold lost during payment is refunded and books nothing.

UC-8 Many groups at once.

  • AC-8.1 Concurrent groups together get disjoint blocks.
  • AC-8.2 Concurrent groups anywhere never share a seat.
  • AC-8.3 Groups and single seats overlap safely.
  • AC-8.4 Concurrent group confirms, with expiry, never double-book.
File Change in step 2
booking.hpp GroupRequest; four new HoldError values and their messages
show.hpp, show.cpp hold_group, first_block, first_free, is_free; place_hold split out of hold
booking_service.* hold_group, which finds the show and passes the request on
everything else unchanged: seat.hpp, clock.hpp, payment.hpp, result.hpp, and the whole confirm path

The confirm path, begin_confirm, finish_confirm, and abandon_confirm, did not change by a single line of code. That is the strongest evidence that step 1’s design was split in the right places.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking.hpp
// Step 2: a group asks for a number of seats rather than naming them, and
// may ask for them side by side in one row. The service picks the seats by
// a fixed rule (see Show::hold_group), so the same request on the same
// seat map always gets the same seats.
struct GroupRequest {
int size = 1;
bool adjacent = false;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

booking.hpp
// Why a hold was refused.
enum class HoldError {
unknown_show,
no_seats, // the request named no seats
unknown_seat, // a seat that is not in this show
duplicate_seat, // the same seat twice in one request
seat_held, // someone else holds one of the seats
seat_booked, // one of the seats is already sold
// Step 2, group holds:
invalid_group_size, // a group of fewer than one seat
group_wider_than_row, // an adjacent group larger than a whole row
not_enough_seats, // fewer free seats in the show than the group needs
no_adjacent_block, // no row has that many free seats side by side
};
// Why a confirm did not produce a booking.
enum class ConfirmError {
unknown_show,
unknown_hold,
hold_expired, // the hold ran out before confirm was called
hold_released, // released by the customer or by a failed payment
already_confirmed, // a different request id already confirmed this hold
payment_in_progress, // another request id is paying for this hold now
request_reused, // this request id was already used for a different hold
payment_declined, // the gateway said no; the seats were released
hold_lost_during_payment, // paid, but the hold expired or was released
// while the payment was in flight; refunded
};

Four new refusals, each with its own reason. group_wider_than_row is separate from no_adjacent_block on purpose: one says “this can never work in this hall”, the other “not right now”.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

show.cpp
HoldResult Show::hold_group(GroupRequest group) {
// One lock for choosing and marking: between "these seats are free" and
// "these seats are held" no other thread can take one of them. Choosing
// first and then calling hold() would never double-book (hold checks
// again), but another thread could take a chosen seat in between, and
// the group would be refused even though other seats were free.
const std::lock_guard lock(mutex_);
const TimePoint now = clock_.now();
expire_due(now); // so seats of expired holds count as free
if (group.size < 1) return HoldError::invalid_group_size;
if (group.adjacent && group.size > seats_per_row_) return HoldError::group_wider_than_row;
const std::optional<std::vector<SeatId>> chosen =
group.adjacent ? first_block(group.size) : first_free(group.size);
if (!chosen) return group.adjacent ? HoldError::no_adjacent_block : HoldError::not_enough_seats;
return place_hold(*chosen, now);
}
// The adjacent rule. Walks each row from seat 1, counting free seats in a
// row ("run"); a taken seat resets the count to 0. The first time the run
// reaches size, the block is the size seats ending here. Rows are tried
// front to back, so the earliest row wins, and within it the lowest seats.
std::optional<std::vector<SeatId>> Show::first_block(int size) const {
for (int row = 0; row < rows_; ++row) {
const char letter = static_cast<char>('A' + row);
int run = 0; // starts again in each row: a block never spans two rows
for (int number = 1; number <= seats_per_row_; ++number) {
run = is_free({letter, number}) ? run + 1 : 0;
if (run == size) {
std::vector<SeatId> block;
// The block ending at number starts size - 1 seats earlier.
for (int first = number - size + 1; first <= number; ++first) {
block.push_back({letter, first});
}
return block;
}
}
}
return std::nullopt; // no row has size free seats side by side
}
// The not-adjacent rule: the first size free seats in row order.
std::optional<std::vector<SeatId>> Show::first_free(int size) const {
std::vector<SeatId> picked;
for (int row = 0; row < rows_; ++row) {
for (int number = 1; number <= seats_per_row_; ++number) {
const SeatId seat{static_cast<char>('A' + row), number};
if (!is_free(seat)) continue;
picked.push_back(seat);
if (std::ssize(picked) == size) return picked;
}
}
return std::nullopt; // fewer free seats than the group needs
}

The comment at the top of hold_group is the design decision. The show could expose “find me a block” and let the caller then call hold with the seats it was given. That would never double-book, because hold checks again. But between the two calls another customer could take one of the chosen seats, and the group would be refused although other blocks were free. Choosing and marking under the same lock means a group is refused only when, at that moment, no block exists.

place_hold is the second half of step 1’s hold, moved into its own function so that both hold and hold_group use it. It is pass 2: it marks seats already known to be free, under a lock the caller already holds, and makes the Hold.

How this code works: first_block in the step 2 demo

The demo’s show “matinee” has 3 rows of 6 seats at $20.00. Alice holds A3 first. Then a group asks for 4 together.

first_block(4) walks row A from seat 1, counting the free seats in a row:

Seat Free? run after run == 4?
A1 yes 1 no
A2 yes 2 no
A3 no 0 no
A4 yes 1 no
A5 yes 2 no
A6 yes 3 no

Row A ends with run at 3. run starts again at 0 for row B, which is why a block never spans two rows (AC-7.3): A5, A6, B1, B2 are four free seats in a row of the list, but not of the hall.

Seat Free? run after run == 4?
B1 yes 1 no
B2 yes 2 no
B3 yes 3 no
B4 yes 4 yes

The block ends at B4, so it starts at 4 - 4 + 1 = 1: B1 B2 B3 B4, hold 2, $80.00.

Next, 3 together: row A again gives runs 1, 2, 0, 1, 2, 3, and the run reaches 3 at A6, so the block is A4 A5 A6, hold 3. The first two seats of row A were free too, but a block of two is not enough, and the rule never considers a later row while an earlier row has a block.

Then 7 together is refused before any search: 7 is more than the 6 seats in a row, so it is group_wider_than_row.

Then 5 anywhere: first_free(5) walks in row order, skipping every taken seat. It takes A1 and A2, skips A3 to A6 and B1 to B4, and takes B5, B6, and C1: hold 4, $100.00. Spread over three rows, which is what “anywhere” allows.

hold_group returns the same Hold as hold: one id, one list of seats, one expiry time, one amount. Everything after it works on a Hold, so the group gets, with no new code:

  • Expiry together, because the hold has one expires_at and expire_due frees all its seats at once (AC-7.8).
  • One payment, because begin_confirm charges hold.amount, which is the group’s total (AC-7.7).
  • Idempotency, because the request id is about the confirm, not about how the hold was made.
  • The race with expiry, because finish_confirm re-checks the hold, whatever made it (AC-7.10).

The tempting alternative is a new GroupHold that owns several Hold objects, one per seat. Then each of those rules would need writing again, for “all of them” instead of “it”, and each would be a new place for a partial group to slip through.

Step 2 has 45 tests: step 1’s 31 and 14 new ones. Thirty of the old tests are unchanged; the random stress test, AC-6.7, now makes half of its holds groups, some of them side by side. The world gains a group() helper that calls hold_group on show “s”.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_7_1_a_group_anywhere_gets_the_first_free_seats_in_row_order) {
World world;
LLD_CHECK(world.hold({{'A', 2}}).has_value());
const HoldResult booked = world.hold({{'A', 3}});
LLD_CHECK(world.confirm("r1", booked.value().id).has_value());
// A2 is held and A3 booked, so they are skipped; the group spills into B.
const HoldResult group = world.group(3, false);
LLD_CHECK(seats_of(group) == (Seats{{'A', 1}, {'A', 4}, {'B', 1}}));
LLD_CHECK_EQ(group.value().amount, Cents{3000});
LLD_CHECK(world.show().invariants_hold());
}
LLD_TEST(ac_7_2_a_group_together_gets_the_first_block_in_the_earliest_row) {
World world(3, 6);
LLD_CHECK(world.hold({{'A', 1}}).has_value());
// Row A has A2..A6 free: the lowest block of 2 is A2 A3.
LLD_CHECK(seats_of(world.group(2, true)) == (Seats{{'A', 2}, {'A', 3}}));
LLD_CHECK(world.hold({{'A', 5}}).has_value());
// Row A now has only A4 and A6 free, which are not side by side, so a
// pair goes to row B, and a single to A4.
LLD_CHECK(seats_of(world.group(2, true)) == (Seats{{'B', 1}, {'B', 2}}));
LLD_CHECK(seats_of(world.group(1, true)) == (Seats{{'A', 4}}));
// A block of 4 skips the gap B1 B2 and starts at B3.
LLD_CHECK(seats_of(world.group(4, true)) == (Seats{{'B', 3}, {'B', 4}, {'B', 5}, {'B', 6}}));
LLD_CHECK(world.show().invariants_hold());
}
LLD_TEST(ac_7_3_a_block_never_spans_two_rows) {
World world; // 2 rows of 4
LLD_CHECK(world.hold({{'A', 1}, {'A', 2}, {'B', 3}, {'B', 4}}).has_value());
// A3 A4 B1 B2 are four free seats, and A4-B1 are next to each other in
// storage, but not in the hall: no block of 3 exists.
LLD_CHECK_EQ(world.group(3, true).error(), HoldError::no_adjacent_block);
LLD_CHECK_EQ(world.show().count(SeatState::available), std::size_t{4});
// Anywhere, the same four seats are enough.
LLD_CHECK(seats_of(world.group(4, false)) ==
(Seats{{'A', 3}, {'A', 4}, {'B', 1}, {'B', 2}}));
}
LLD_TEST(ac_7_4_a_group_together_may_fill_a_row_but_not_exceed_it) {
World world;
LLD_CHECK(seats_of(world.group(4, true)) ==
(Seats{{'A', 1}, {'A', 2}, {'A', 3}, {'A', 4}}));
LLD_CHECK_EQ(world.group(5, true).error(), HoldError::group_wider_than_row);
LLD_CHECK(seats_of(world.group(4, true)) ==
(Seats{{'B', 1}, {'B', 2}, {'B', 3}, {'B', 4}}));
LLD_CHECK_EQ(world.group(1, true).error(), HoldError::no_adjacent_block);
LLD_CHECK_EQ(world.group(1, false).error(), HoldError::not_enough_seats);
}
LLD_TEST(ac_7_5_a_group_that_cannot_be_met_is_refused_and_changes_nothing) {
World world;
LLD_CHECK_EQ(world.group(0, false).error(), HoldError::invalid_group_size);
LLD_CHECK_EQ(world.group(-2, true).error(), HoldError::invalid_group_size);
LLD_CHECK_EQ(world.group(9, false).error(), HoldError::not_enough_seats);
LLD_CHECK_EQ(world.service.hold_group("nope", {1, false}).error(), HoldError::unknown_show);
LLD_CHECK(world.hold({{'A', 1}}).has_value());
LLD_CHECK_EQ(world.group(8, false).error(), HoldError::not_enough_seats);
LLD_CHECK_EQ(world.show().count(SeatState::available), std::size_t{7});
LLD_CHECK_EQ(world.show().count(SeatState::held), std::size_t{1});
// Exactly as many as are free is enough.
LLD_CHECK(world.group(7, false).has_value());
LLD_CHECK_EQ(world.show().count(SeatState::available), std::size_t{0});
}
LLD_TEST(ac_7_6_seats_of_expired_holds_are_free_for_a_group) {
World world;
LLD_CHECK(world.hold({{'A', 2}}).has_value());
world.clock.advance(299s);
LLD_CHECK(seats_of(world.group(4, true)) ==
(Seats{{'B', 1}, {'B', 2}, {'B', 3}, {'B', 4}}));
world.clock.advance(1s); // A2's hold ends; the B hold (made at 299s) does not
LLD_CHECK(seats_of(world.group(4, true)) ==
(Seats{{'A', 1}, {'A', 2}, {'A', 3}, {'A', 4}}));
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Eight groups of 3 together, at once, in 2 rows of 4. Whatever the order,
// the first winner gets A1-A3, the second B1-B3, and the rest are refused.
LLD_TEST(ac_8_1_concurrent_groups_together_get_disjoint_blocks) {
for (int round = 0; round < 50; ++round) {
World world;
const auto results = race(8, [&world](int) { return world.group(3, true); });
std::vector<Seats> won;
for (const HoldResult& result : results) {
if (result.has_value()) {
won.push_back(result.value().seats);
} else {
LLD_CHECK_EQ(result.error(), HoldError::no_adjacent_block);
}
}
LLD_CHECK_EQ(won.size(), std::size_t{2});
std::set<Seats> blocks(won.begin(), won.end());
LLD_CHECK(blocks == (std::set<Seats>{{{'A', 1}, {'A', 2}, {'A', 3}},
{{'B', 1}, {'B', 2}, {'B', 3}}}));
LLD_CHECK(world.show().invariants_hold());
}
}
// Eight groups of 3 anywhere: 8 seats hold two groups, never a seat twice.
LLD_TEST(ac_8_2_concurrent_groups_anywhere_never_share_a_seat) {
for (int round = 0; round < 50; ++round) {
World world;
const auto results = race(8, [&world](int) { return world.group(3, false); });
std::set<SeatId> taken;
int winners = 0;
for (const HoldResult& result : results) {
if (!result.has_value()) {
LLD_CHECK_EQ(result.error(), HoldError::not_enough_seats);
continue;
}
++winners;
for (const SeatId seat : result.value().seats) LLD_CHECK(taken.insert(seat).second);
}
LLD_CHECK_EQ(winners, 2);
LLD_CHECK_EQ(world.show().count(SeatState::held), std::size_t{6});
LLD_CHECK(world.show().invariants_hold());
}
}
// Groups together, groups anywhere, and single seats, overlapping, at once.
// Every block that wins is side by side in one row, and no seat is held
// twice, whatever the interleaving.
LLD_TEST(ac_8_3_mixed_groups_and_single_seats_overlap_safely) {
for (int round = 0; round < 50; ++round) {
World world(2, 6);
const auto results = race(12, [&world](int t) {
if (t % 3 == 0) return world.group(4, true);
if (t % 3 == 1) return world.group(2, false);
return world.hold({{static_cast<char>('A' + t % 2), t % 6 + 1}});
});
std::set<SeatId> taken;
for (int t = 0; t < 12; ++t) {
const HoldResult& result = results[static_cast<std::size_t>(t)];
if (!result.has_value()) continue;
const Seats seats = result.value().seats;
for (const SeatId seat : seats) LLD_CHECK(taken.insert(seat).second);
if (t % 3 == 0) {
LLD_CHECK_EQ(seats.size(), std::size_t{4});
for (std::size_t i = 1; i < seats.size(); ++i) {
LLD_CHECK_EQ(seats[i].row, seats[0].row);
LLD_CHECK_EQ(seats[i].number, seats[i - 1].number + 1);
}
}
}
LLD_CHECK_EQ(world.show().count(SeatState::held), taken.size());
LLD_CHECK(world.show().invariants_hold());
}
}
// Two groups confirm and pay at once, while the clock moves past the first
// group's expiry and two other customers try to take its seats. Bookings
// never overlap, and no seat a booking has is held by anyone else.
LLD_TEST(ac_8_4_concurrent_group_confirms_with_expiry_never_double_book) {
for (int round = 0; round < 30; ++round) {
World world;
const HoldId first = world.group(4, true).value().id; // A1-A4
world.clock.advance(150s);
const HoldId second = world.group(4, true).value().id; // B1-B4
std::vector<ConfirmResult> confirms(2, ConfirmError::unknown_hold);
std::vector<HoldResult> grabs(2, HoldError::no_seats);
{
std::latch start_together(4);
std::vector<std::jthread> pool;
pool.emplace_back([&, first] {
start_together.arrive_and_wait();
confirms[0] = world.confirm("g1", first);
});
pool.emplace_back([&, second] {
start_together.arrive_and_wait();
confirms[1] = world.confirm("g2", second);
});
pool.emplace_back([&] {
start_together.arrive_and_wait();
world.clock.advance(150s); // the first group's hold ends now
grabs[0] = world.group(4, true);
});
pool.emplace_back([&] {
start_together.arrive_and_wait();
grabs[1] = world.hold({{'A', 1}});
});
}
LLD_CHECK(confirms[1].has_value()); // B's hold has 150 s left
std::set<SeatId> sold;
for (const ConfirmResult& result : confirms) {
if (!result.has_value()) continue;
for (const SeatId seat : result.value().seats) LLD_CHECK(sold.insert(seat).second);
}
for (const HoldResult& grab : grabs) {
if (!grab.has_value()) continue;
for (const SeatId seat : grab.value().seats) LLD_CHECK(!sold.contains(seat));
}
LLD_CHECK_EQ(world.show().count(SeatState::booked), sold.size());
LLD_CHECK(world.show().invariants_hold());
}
}

The thread tests use the same latch pattern as step 1. AC-8.1 is a good example of why a fixed rule helps testing: eight threads each ask for 3 together in 2 rows of 4. Whatever order they run in, exactly two win, the others get no_adjacent_block, and the two blocks are A1 to A3 and B1 to B3, so the test can check the exact seats, not just “no overlap”.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
int main() {
ManualClock clock{sys_days{2026y / 12 / 5} + 19h};
FakePaymentGateway payments;
payments.decline(bad_card);
BookingService service{clock, payments, 5min};
service.add_show("matinee", 3, 6, 2000);
Show& show = *service.find("matinee");
const auto group = [&](GroupRequest request) {
const HoldResult result = service.hold_group("matinee", request);
report("group of " + group_name(request), result);
return result;
};
report("alice holds A3", service.hold("matinee", {{'A', 3}}));
const HoldResult four = group({4, true});
const HoldResult three = group({3, true});
static_cast<void>(group({7, true})); // printed; not used later
const HoldResult five = group({5, false});
static_cast<void>(group({0, false})); // printed; not used later
std::cout << "seats (. available, h held, X booked):\n";
print_map(show);
report("the group of four confirms (g4-1)",
service.confirm("g4-1", "matinee", four.value().id, good_card));
report("its app retries (g4-1)",
service.confirm("g4-1", "matinee", four.value().id, good_card));
std::cout << "charges so far: " << payments.charges().size() << "\n";
std::cout << "the group of five releases its hold: "
<< (service.release("matinee", five.value().id) ? "released" : "nothing to release")
<< "\n";
clock.advance(5min);
std::cout << "five minutes pass\n";
report("the group of three confirms (g3-1)",
service.confirm("g3-1", "matinee", three.value().id, good_card));
print_map(show);
const HoldResult six = group({6, true});
report("the group of six pays with a declined card (g6-1)",
service.confirm("g6-1", "matinee", six.value().id, bad_card));
static_cast<void>(group({15, false})); // printed; not used later
print_map(show);
std::cout << "charges: " << payments.charges().size()
<< ", refunds: " << payments.refunds().size() << "\n";
std::cout << "invariants hold: " << (show.invariants_hold() ? "yes" : "no") << "\n";
}
Expected output
alice holds A3: hold 1 on A3, $20.00
group of 4 together: hold 2 on B1 B2 B3 B4, $80.00
group of 3 together: hold 3 on A4 A5 A6, $60.00
group of 7 together: refused, the group is wider than a row
group of 5 anywhere: hold 4 on A1 A2 B5 B6 C1, $100.00
group of 0 anywhere: refused, a group needs at least one seat
seats (. available, h held, X booked):
A hhhhhh
B hhhhhh
C h.....
the group of four confirms (g4-1): booking 1 for B1 B2 B3 B4, $80.00, payment pay-1
its app retries (g4-1): booking 1 for B1 B2 B3 B4, $80.00, payment pay-1
charges so far: 1
the group of five releases its hold: released
five minutes pass
the group of three confirms (g3-1): refused, the hold has expired
A ......
B XXXX..
C ......
group of 6 together: hold 5 on A1 A2 A3 A4 A5 A6, $120.00
the group of six pays with a declined card (g6-1): refused, the payment was declined
group of 15 anywhere: refused, not enough free seats
A ......
B XXXX..
C ......
charges: 2, refunds: 0
invariants hold: yes

Read it against the rules:

  • The first seat map is the walkthrough above: A3 is Alice’s, A4 to A6 are the group of three, B1 to B4 the group of four, and A1, A2, B5, B6, C1 the group of five.
  • The group of four confirms with one charge, pay-1, and its retry pays nothing more.
  • Five minutes pass, and every hold still unpaid ends at once: the group of three, and Alice’s A3. The group of five had already been released. The group of three is refused when it confirms late.
  • The group of six gets the whole of row A, now free again. Its card is declined, and all six seats come back together.
  • The group of 15 is refused: only 14 seats are free (18 minus the 4 booked), so it is not_enough_seats.
  • The totals: 2 charges (the group of four, and the declined group of six) and no refunds.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask how long a hold lasts, whether a hold can span several seats, what the payment service promises, and what a retry looks like. “If the app times out and sends confirm again, is that the same request or a new one?”
5 min Sketch Seat, Show, BookingService, and the Clock and PaymentGateway interfaces. Say who owns what, and where the lock is. “One mutex per show. Different shows never wait for each other.”
10–15 min Write the seat state table, then hold: check every seat, then mark every seat, under one lock. State INV-1 and INV-2. “Pass 1 only looks, so it can stop anywhere. Pass 2 cannot fail part way.”
10 min Split confirm into three parts. Walk the race: the hold expires during the payment and someone else takes the seat. “After the payment I check again whether the hold is still ours. If not, the money goes back.”
About 5 min Take a change: group bookings, or cancellation. “A group is one ordinary hold, so expiry, payment, and retries already work for it.”

What is usually expected at each level

Level Usually expected
Junior Shows and seats; a seat state enum; a hold with an expiry time; confirm that books held seats; a lock around the seat map; a few tests.
Mid-level All of the above, plus: all-or-nothing holds; an injected clock; refusals as values with reasons; a payment interface with a fake; no lock during the payment; the re-check after it.
Senior All of the above, plus: idempotent confirm keyed by a request id, with in-flight repeats waiting; the refund when a hold is lost during payment; what happens when the gateway throws; what the thread tests can and cannot show; when to use finer locks; what a database changes.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

Why not lock each seat separately?

Because a hold of several seats would have to take several locks, in a fixed order, to stay all or nothing, and expiry and the request records would still need a lock of their own. One lock per show is simpler and fast enough for any normal hall. Finer locks pay only when measurements show customers of one huge show waiting on it.

Why not keep the lock during the payment? It removes the race.

It does, and it makes every customer of the show wait for one bank, one at a time, and it calls code you do not control while holding a lock, which is how deadlocks are made. The race it removes is handled by one re-check and a refund instead.

The payment was approved, but the hold expired during it. Why refund instead of booking anyway?

Because the seats may already belong to someone else: an expired hold frees its seats at once, and another customer may have held them in the meantime, as Frank did in the demo. Booking anyway would sell a seat twice. A design that wanted to honour a late payment would have to stop expiry for a hold while it is paying, and then needs a deadline on the payment itself.

What does the request id protect against that the gateway’s key does not?

The request id lets the service answer a repeat without calling the gateway at all, and lets a repeat that arrives during the payment wait for the first answer instead of racing it. The key protects against a repeat that reaches the gateway anyway. Both are needed: the service’s records protect the seats, and the key protects the money.

Your thread tests pass. Is the code thread-safe?

The tests are evidence, not proof. They sample some interleavings, and ThreadSanitizer checks only the paths that ran. The stronger argument is the design: every access to a show’s data is under its one mutex, and every known race has a single-threaded test that plays it out on purpose with the payment hook.

How would this change with two servers?

The mutex protects memory in one process; two servers do not share it. The seat states and request records would move into a database, and “check and mark under one lock” would become a transaction, or a conditional update such as “set held where state is available”. The three-part confirm stays the same, with the payment outside any transaction.

  • Hold and request records are never deleted. The show keeps every hold it ever made and every request id it ever saw, so memory grows with every customer, and expire_due walks every hold on every call. A real service would keep holds in order of expiry (for example in a std::multimap keyed by expires_at), and keep request records for a stated time, such as 24 hours, after which a repeat is treated as new.
  • A refund that throws is lost. confirm calls refund after finish_confirm. If it throws, the exception reaches the caller and nothing remembers that money is owed. A real service would record “refund owed” durably before calling the gateway, and retry until it succeeds, as in The outbox and the relay.
  • One process, in memory. Shows, holds, and requests live in one process and are lost on restart. There is no database and no distributed locking; two servers running this code would each sell every seat.
  • No fairness under contention. std::mutex does not serve threads in the order they arrived, so a customer who asked first may lose the seat to one who asked a moment later. A real box office for a big sale would add a queue in front of the show.
  • Request ids are per show. The same id used at two shows is two requests. A real client would make ids unique across the service.
  • Shows are added only at setup. add_show must be called before the service is shared between threads.
  • One price per show. Every seat costs the same, and there are no discounts, fees, or seat categories.
  • Out of memory while storing an answer. hold makes its record before it marks any seat, so a failed allocation there changes nothing. finish_confirm is not as careful: if building or storing the answer throws after the seats are booked, the exception reaches the caller with the money taken, the request stays “in flight”, and a repeat of it would wait for good. A real service would prepare the answer before changing anything, or treat out of memory as fatal.
  • A charge that throws after taking money. abandon_confirm assumes the gateway, seeing the same key again, will not charge twice. The fake does not deduplicate by key, so this case is covered by the contract, not by a test.
Requirement Design element Code Tests Status
FR-1 seats SeatState, can_move, Seat, the show’s layout step 1 seat.hpp, show.* ac_1_1_… to ac_1_3_… Tested
FR-2 hold Show::hold, two passes, HoldError step 1 show.cpp, booking.hpp ac_2_1_… to ac_2_4_… Tested
FR-3 expiry expire_due, the injected Clock step 1 show.cpp, clock.hpp ac_3_1_… to ac_3_4_… Tested
FR-4 release Show::release step 1 show.cpp ac_2_5_…, ac_3_4_… Tested
FR-5 confirm begin_confirm, the charge, finish_confirm, Booking step 1 show.cpp, booking_service.cpp ac_4_1_…, ac_4_6_…, ac_5_1_… Tested
FR-6 no seat sold twice one mutex per show; check and mark in one call; paying step 1 show.* ac_2_2_…, ac_6_1_…, ac_6_2_…, ac_6_4_…, ac_6_7_… Tested
FR-7 paid, but too late still_ours, the refund in confirm step 1 show.cpp, booking_service.cpp ac_5_2_…, ac_5_3_…, ac_5_5_… Tested
NFR-1 safe to repeat RequestRecord, decide, the wait on done_, abandon_confirm step 1 show.* ac_4_2_… to ac_4_5_…, ac_5_4_…, ac_5_6_…, ac_6_3_…, ac_6_6_… Tested
NFR-2 thread-safe mutex_ in every public Show call step 1 show.* ac_6_1_… to ac_6_7_…, under the tsan preset Tested
NFR-3 no lock during a payment three-part confirm step 1 booking_service.cpp ac_6_5_… Tested
NFR-4 testable without waiting Clock, PaymentGateway, and fakes step 1 clock.hpp, payment.hpp every test Tested
NFR-5 exact money Cents step 1 booking.hpp ac_4_1_…, ac_6_7_… Tested
FR-8 group bookings GroupRequest, hold_group, first_block, first_free step 2 booking.hpp, show.cpp ac_7_1_… to ac_7_10_…, ac_8_1_… to ac_8_4_… Tested

Exercise: Let a customer cancel a booking

The box office now wants cancellations: a customer can cancel a confirmed booking, the seats become available again, and the payment is refunded, once. Start from step 1.

  1. Which change to the seat state table does this need, and what else does that change make legal by accident?
  2. Where is the payment reference kept, so the show knows what to refund?
  3. What should a second cancel of the same booking do? And a confirm repeated with the original request id, after the cancel?
  4. Where does the refund happen, and with which lock held?
  5. Write it, with a test for each answer, and a thread test of concurrent cancels.
Show the explained answer
  1. can_move(booked, available) becomes true: a cancellation. But Seat::release also moves to available, and checks only the table, so a release of a booked seat is now legal too. Give release its own guard (“release needs a held seat”), and add a separate Seat::cancel that requires booked and clears the holder. Widening a transition table widens every function that uses it.
  2. In the hold record. Add std::string payment; to HoldRecord, set to paid.reference when finish_confirm books, and add a cancelled status to HoldStatus. The compiler then helps: -Wswitch reports that begin_confirm’s switch does not handle the new status (a new confirm of a cancelled hold is refused).
  3. A second cancel refunds nothing. Show::cancel returns already_cancelled when the status is already cancelled, so the status itself makes cancel safe to repeat. A confirm repeated with the original request id still returns the stored booking: that answer is a fact about what happened then, not about the seat now. A new request id for the cancelled hold is refused.
  4. Outside the lock, as in confirm. Show::cancel locks, checks, frees the seats, marks the hold cancelled, and returns the payment reference. BookingService::cancel then calls refund with no lock held. The limitation stays: a refund that throws is not saved.
  5. Sketch of the show’s half:

IllustrativeA fragment for explanation; not compiled on its own.

// The error a cancel can return instead of a payment reference
// (in booking.hpp, beside HoldError and ConfirmError).
enum class CancelError { unknown_hold, not_booked, already_cancelled };
Expected<std::string, CancelError> Show::cancel(HoldId hold_id) {
const std::lock_guard lock(mutex_); // one indivisible step, like hold
expire_due(clock_.now()); // the same first step as every call
const auto found = holds_.find(hold_id);
if (found == holds_.end()) return CancelError::unknown_hold;
HoldRecord& record = found->second;
// A second cancel finds `cancelled` and refunds nothing: cancel is
// safe to repeat because the status records that it happened.
if (record.status == HoldStatus::cancelled) return CancelError::already_cancelled;
if (record.status != HoldStatus::confirmed) return CancelError::not_booked;
for (const SeatId seat : record.hold.seats) seat_at(seat).cancel();
record.status = HoldStatus::cancelled;
return record.payment; // the caller refunds it, with no lock held
}

invariants_hold also has to skip cancelled holds, as it skips expired and released ones, and AC-1.2’s line for booked to available flips from “not legal” to “legal”.

When the page was written, this answer was checked in a scratch copy of step 1; that copy is not part of the repository, and the check was not rerun for the review. As reported then, with these changes and three new tests (cancel frees the seats and refunds once; only a booking can be cancelled; 8 threads cancelling one booking at once, 30 rounds, refund once), all 34 tests passed under GCC and Clang with AddressSanitizer and UndefinedBehaviorSanitizer, and under GCC with ThreadSanitizer in three runs.

  • Give each seat a state enum and one table of legal moves, and make an illegal move throw. Most double-booking bugs become loud.
  • Check every seat, then mark every seat, under one lock. That single rule gives all-or-nothing holds and no seat sold twice.
  • Read the time inside the lock, from an injected clock, and expire lazily at the start of every call. No timer threads, and tests that never sleep.
  • Never hold a lock during a payment. Claim the hold, unlock, charge, lock, and check again whether the hold is still yours. If it is not, refund.
  • Key every confirm by a request id. Store the answer, make an in-flight repeat wait for it, and send the id to the gateway as its key.
  • Play races out on one thread with a hook in the fake, and use real threads as a second, weaker line of evidence.
  • A group is one ordinary hold, so everything built for holds already works for groups.