Skip to content

Part 9 · Blueprint 55

High-Concurrency Ticket Booking System

15 min reading · Sources · Editorial review pending

A queue reduces demand but does not make seat allocation exclusive.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Rate Limiting Algorithms: Token Bucket to Sliding Window, Idempotency Keys & Distributed Retries, Distributed Transactions: 2PC vs. Saga Orchestration.

Sixty-second mental model

Problem: A queue reduces demand but does not make seat allocation exclusive.

Use: Commit a hold under inventory authority and reconcile payment before release.

Design boundary: Allocate scarce seats under concurrent requests and expiring holds. A waiting room shapes demand; it is not the authority granting the seat. Payment must reconcile with hold expiry.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing ticket reservations. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one hold means and which component owns the seat inventory.

Think of numbered holds at a box office. Separate the requester from seat inventory, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.

Architecture and worked reasoning

Design boundary: Allocate scarce seats under concurrent requests and expiring holds. A waiting room shapes demand; it is not the authority granting the seat. Payment must reconcile with hold expiry.

Responsibilities on the request path

Ticket reservations: responsibilities and request directionAllocate scarce seats under concurrent requests and expiring holds. A waiting room shapes demand; it is not the authority granting the seat. Payment must reconcile with hold expiry.Waiting roomSeat authorityHold recordPayment flow
Allocate scarce seats under concurrent requests and expiring holds. A waiting room shapes demand; it is not the authority granting the seat. Payment must reconcile with hold expiry.

Workload and limiting resource

Hypothetical sale has 10,000 seats and 100,000 contenders. Admitting 1,000 requests/s takes at least 100 seconds to admit everyone, but cannot create more than 10,000 distinct seat confirmations. A 2-minute hold at 100 newly held seats/s would request 12,000 simultaneous holds before accounting for confirmations/expiry.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Ticket reservations: mutation boundaryAdmit bounded contenders. Then: Conditionally change an available seat to a specific hold. Then: Confirm from payment evidence or expire under a race-safe state transition.Step 1
Admit bounded contenders.
Step 2
Conditionally change an available seat to a specific hold.
Step 3
Confirm from payment evidence or expire under a race-safe state transition.
Admit bounded contenders. Then: Conditionally change an available seat to a specific hold. Then: Confirm from payment evidence or expire under a race-safe state transition.
  1. Admit bounded contenders.
  2. Conditionally change an available seat to a specific hold.
  3. Confirm from payment evidence or expire under a race-safe state transition.

Observation and recovery path

Ticket reservations: observation boundaryRead seat availability as advisory discovery. Then: Resolve the caller’s own hold identity. Then: Expose confirmed/expired/pending states without inventing availability.Step 1
Read seat availability as advisory discovery.
Step 2
Resolve the caller’s own hold identity.
Step 3
Expose confirmed/expired/pending states without inventing availability.
Read seat availability as advisory discovery. Then: Resolve the caller’s own hold identity. Then: Expose confirmed/expired/pending states without inventing availability.
  1. Read seat availability as advisory discovery.
  2. Resolve the caller’s own hold identity.
  3. Expose confirmed/expired/pending states without inventing availability.

Failure that changes the decision

Hypothetical scenario: Hold expiry and payment success race. A guarded transition must decide whether to confirm, refund/reconcile or reject; clocks at independent workers must not allocate the same seat twice.

Attempt this decision before reading the explanation

Can caching a seat map prevent double booking?

No. A map helps discovery. A conditional authoritative allocation enforces uniqueness when multiple callers act on the same apparent availability.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. Northwind recognizes retries of one reservation, but now two different buyers request its last unit. Each intention has a different identifier. Dev reads the available quantity before inserting each reservation; Priya pauses both requests just after that read.

Move from operation identity to a local business invariant. Define the condition that must survive concurrent legitimate intentions, then put its decision and state change inside the chosen transaction boundary. These reservation examples are separate from the browsing workload.

Before you continue: Can idempotency alone prevent two different buyers from reserving the same unit?

That can stop one intention from repeating without deciding between different intentions. Both may still race over the same limited quantity.

This addresses the shared condition. Work through the interleaving and selected isolation behavior before claiming that a read followed by a write is sufficient.

Idempotency binds repeated attempts to one intention. It does not decide whether two distinct intentions can both succeed. The business invariant here is that accepted active reservations cannot exceed the allocatable units of the selected item. Returning an old receipt correctly does not protect that quantity against another buyer.

Start with the rows representing authority: available quantity, accepted reservation, operation identity and any durable downstream intent. If they can share one PostgreSQL transaction, define their transition together. Moving a stock check into another service would add a coordination problem before there is evidence that the local boundary is inadequate.

The obvious read-then-write approach is vulnerable even when each individual statement is valid. Both callers can read an eligible quantity before either records its reservation. A transaction is necessary for a grouped decision, but the isolation level and predicates determine which concurrent histories remain possible. Merely surrounding statements with a transaction label does not describe those histories.

One possible design stores the available count in the item’s authoritative row. A transaction conditionally decreases it only when sufficient quantity remains, inserts the reservation and binds the successful result to its logical operation. Failure of any required local change aborts the grouped transition. A failed conditional update means insufficient current authority for that request; an uncertain commit response remains a recovery problem tied to the same operation.

The condition must be enforced when the database performs the change. An application-side check of a stale copy does not supply equivalent protection. For this design the item row is a deliberate coordination point. Contention there reflects competing demands for a scarce unit, rather than a flaw that can be removed simply by giving every worker its own counter.

Hypothetical scenario. The rule permits at most one active reservation per tenant. Two transactions insert different reservation rows after each snapshot reports zero active rows. A row-level uniqueness rule on reservation identity cannot protect the shared predicate because the written identities differ.

One possible PostgreSQL design represents the active-only uniqueness condition with an appropriate unique index; another serializes through a tenant-owned guard row; serializable isolation is another option with required retry handling. The chosen design must match the real predicate, including expiry and status transitions. Do not assume a generic lock on any row protects records that have not yet been inserted.

A retry after serialization failure must replay the transaction's decision from fresh evidence, not just resubmit its final insert. Keep external side effects outside a retryable local transaction unless a separate protected protocol makes them safe. Contention is both a workload issue and evidence that the authority boundary is doing real coordination.

Hypothetical worked example. Choose one available unit and two concurrent requests, each asking for one unit. If both independently accept their old observation, accepted quantity is 1 + 1 = 2. It exceeds capacity by 2 − 1 = 1 unit. Each request can have a perfectly unique operation identity while the combined result is invalid.

Under the proposed conditional transition, the first accepted transaction reduces available quantity by 1 − 1 = 0. The competing transaction cannot satisfy its quantity condition against that committed state. Its rejection creates no reservation. Accepted quantity is one and remaining quantity is zero, preserving 1 + 0 = 1 total unit in this simplified model.

This calculation assumes no replenishment, expiry or cancellation during the two decisions. Those actions must enter the same invariant argument. A release must correspond to an existing reservation and must not add the unit repeatedly when its own delivery is retried. Conservation is a state-transition property, not just an arithmetic check on the happy path.

Row locking can serialize competing changes to the selected item. Optimistic version checks can reject a transition whose expected version no longer matches. Serializable execution can reject transactions whose combined behavior cannot match an allowed serial ordering. These mechanisms differ in blocking, retry and operational behavior; none removes the need to state the business predicate.

Consider an invariant spanning several rows, such as a limit on all active reservations in a tenant. Locking just one existing reservation does not necessarily protect the set, including new rows. The design might use a tenant authority row, an appropriate constraint or serializable transactions with whole-transaction retries. Explain the actual mechanism instead of extending a single-row proof to every possible predicate.

Hypothetical scenario. Northwind permits at most one active reservation for a tenant. Initially no reservation is active. Transactions A and B take snapshots in which the active count is zero. Each decides to insert one active reservation with a different identifier. Their row identities do not conflict. If the chosen isolation permits both decisions to commit, the resulting count is 0 + 1 + 1 = 2, exceeding the allowed one by 2 − 1 = 1.

This is a predicate-level write-skew problem: each decision relies on the absence of a competing active row, while the transactions write distinct rows. Neither a unique operation key nor locking one existing reservation covers the absent future row. A plain read of zero followed by an insert is not an atomic claim on the tenant’s remaining right.

One repair serializes every relevant transition through the same tenant authority row, locks it before evaluating the active count and holds that lock through commit. Under a statement-snapshot design, the count must be read after acquiring the lock; reusing an older snapshot can defeat the intended reasoning. Every insertion, activation, cancellation or transfer affecting the invariant must participate. This trades a deliberate coordination point for a simple authority argument.

Layer 3 · Internals

A waiting room reduces the number of buyers reaching the reservation service; it is not the authority deciding whether a seat is available. The inventory transaction must distinguish an unheld seat, an active hold and a confirmed purchase. An expiring hold uses server-side authority and an atomic condition, not the buyer's browser timer.

Payment completion can race hold expiry. Before releasing a seat, reconcile the payment operation and its stable identity under a declared transition policy. A cleanup worker holding an old expiry observation must not release a newer hold for the same seat. Include the hold ID or version in every conditional transition. The public availability view can be cached and approximate if the interface makes final acceptance explicit. The reserve operation, however, must enforce the single-owner invariant. Recovery should be able to reconstruct occupied and pending inventory from durable records without assuming that the queue's in-memory state survived.

Trade-offs and limits

ApproachProvidesRequires
Per-seat guarded holdExpresses exclusivity directly at the inventory record.Popular events create contention at a scarce authority.
Inventory partition by eventSeparates independent events and limits blast propagation.A single extremely popular event still needs its own admission policy.

Recovery decision

Hypothetical scenario: Hold expiry and payment success race. A guarded transition must decide whether to confirm, refund/reconcile or reject; clocks at independent workers must not allocate the same seat twice.

No. A map helps discovery. A conditional authoritative allocation enforces uniqueness when multiple callers act on the same apparent availability.

Write your design before revealing the review

Can caching a seat map prevent double booking?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

No. A map helps discovery. A conditional authoritative allocation enforces uniqueness when multiple callers act on the same apparent availability.

Hold expiry and payment success race. A guarded transition must decide whether to confirm, refund/reconcile or reject; clocks at independent workers must not allocate the same seat twice.

Check your understanding

Can caching a seat map prevent double booking?

No. A map helps discovery. A conditional authoritative allocation enforces uniqueness when multiple callers act on the same apparent availability.

How would you recover from this failure: Hold expiry and payment success race. A guarded transition must decide whether to confirm, refund/reconcile or reject; clocks at independent workers must not allocate the same seat twice.

Start with the exact boundary that failed. Admit bounded contenders. Conditionally change an available seat to a specific hold. Confirm from payment evidence or expire under a race-safe state transition. Then recover evidence through the observation path: Read seat availability as advisory discovery. Resolve the caller’s own hold identity. Expose confirmed/expired/pending states without inventing availability. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

Hypothetical sale has 10,000 seats and 100,000 contenders. Admitting 1,000 requests/s takes at least 100 seconds to admit everyone, but cannot create more than 10,000 distinct seat confirmations. A 2-minute hold at 100 newly held seats/s would request 12,000 simultaneous holds before accounting for confirmations/expiry. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Allocate scarce seats under concurrent requests and expiring holds. A waiting room shapes demand; it is not the authority granting the seat. Payment must reconcile with hold expiry.

Which component in this topology could be removed from a smaller first deployment?

Waiting room, Seat authority, Hold record, Payment flow name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Admit bounded contenders.

What evidence must a caller have before relying on the observation path?

Read seat availability as advisory discovery. Resolve the caller’s own hold identity. Expose confirmed/expired/pending states without inventing availability. No. A map helps discovery. A conditional authoritative allocation enforces uniqueness when multiple callers act on the same apparent availability.

45-minute interview rubric

  1. 00–05: scope hold and seat inventory.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw seat inventory, numbered writes and reads.
  4. 28–40: challenge recovery: Commit a hold under inventory authority and reconcile payment before release.
  5. 40–45: defend event_id placement, observations and remaining assumptions.

Go deeper

Decision log

Commit a hold under inventory authority and reconcile payment before release.

Preserve hold identity and seat inventory ownership.

Revisit changed workload, observations or recovery objectives.