Design a Booking and Reservation System
Prevent double-booking under concurrency with 10-minute holds, comparing pessimistic locks, optimistic CAS, and Redis leases plus DB constraints.
In this lesson (4 bite-sized sections)
Why booking is a concurrency puzzle
Concert seats, hotel rooms, and restaurant time slots all share one strict invariant: never double-book the same inventory, even when hundreds of users click Reserve in the exact same millisecond. Unlike a social timeline where brief staleness is harmless, selling seat 12A twice forces manual cancellations and refunds.
The first instinct many candidates reach for is wrapping the entire checkout flow (select seat, call Stripe, mark booked) inside one database transaction.
The two-phase 10-minute temporary hold
Solve long checkout latency by splitting reservation into two short transactions connected by an explicit state machine: AVAILABLE -> HELD -> CONFIRMED.
- Acquire hold (few milliseconds): atomically transition the slot from
AVAILABLEtoHELD, stamping a uniquehold_tokenandhold_expires_at = now() + 10 minutes. Commit immediately and release the DB connection. - Checkout (minutes, zero DB lock held): the user completes payment while the UI displays a countdown timer.
- Confirm (few milliseconds): once payment authorizes, transition
HELD -> CONFIRMEDonly ifhold_tokenmatches and the hold is still active.
If a buyer abandons checkout, a periodic sweeper resets expired rows to AVAILABLE. Better yet, treat any row with status = 'HELD' AND hold_expires_at < now() as claimable immediately during hold acquisition so inventory never waits on sweeper lag.
- Browse seatscached read map, slight staleness acceptable
- Atomic Holdshort write sets HELD + hold_token + 10m TTL
- Payment Checkoutno DB lock held while buyer enters card
- Conditional Confirmverifies hold_token and active TTL, marks CONFIRMED
- Expiry Reapunpaid holds return to AVAILABLE automatically
Three ways to stop double-booking
When two buyers race for the same slot during the hold step, pick the concurrency guard that matches your contention profile:
| Mechanism | Best Contention Profile | Tradeoff | Final Safety Net |
|---|---|---|---|
| Pessimistic lock (FOR UPDATE) | High (front-row concert seats) | Zero wasted retries; blocks concurrent readers of that row | Database row lock |
| Optimistic CAS (version column) | Low to medium (hotel dates) | Lock-free reads; retry storms on hot seats | Conditional UPDATE rows_affected = 1 |
| Redis hold (SET NX EX) + DB guard | Extreme burst traffic | Fast in-memory TTL holds; Redis alone is unsafe on failover | DB UNIQUE constraint on confirmed slot |
For general restaurant tables or unassigned rooms, SELECT ... FOR UPDATE SKIP LOCKED lets concurrent transactions grab different open rows without waiting on each other. For huge flash-sale spikes, placing a temporary hold in Redis (SET seat:12A token NX EX 600) protects the primary database from overload during checkout spikes, while the database enforces a partial unique index on confirmed bookings so no race can ever finalize twice. Meanwhile, keep interactive seat-map browsing fast by serving read-only availability from a short-TTL cache (1-2 seconds stale is fine for browsing), and enforce strict consistency only when a buyer actually clicks Reserve.
Payment races and idempotent confirmation
The classic edge case strikes at minute 9:59: Buyer A submits payment right before expiry, the payment provider captures the card at 10:02, and Buyer B has already claimed the expired seat. Prevent split-brain between money and seats with two safeguards. First, attach the reservation_id as an idempotency key to the payment API so retries never double-charge. Second, issue the confirmation update conditionally on WHERE id = ? AND hold_token = ? AND status = 'HELD' AND hold_expires_at > now(); if zero rows update after payment authorization (or if you authorize-then-capture only after confirming), immediately void or refund the charge and notify Buyer A cleanly.
Sources: PostgreSQL explicit locking · Redis SET NX expiration pattern · Stripe idempotent requests
HOLD_TTL_SEC = 600 # 10-minute checkout hold
class SeatInventory:
def __init__(self, seat_id: str) -> None:
self.seat_id = seat_id
self.state = "AVAILABLE"
self.holder: str | None = None
self.expires_at = 0
def try_hold(self, buyer: str, now: int) -> bool:
if self.state == "HELD" and now >= self.expires_at:
self.state, self.holder = "AVAILABLE", None
if self.state != "AVAILABLE":
return False
self.state, self.holder, self.expires_at = "HELD", buyer, now + HOLD_TTL_SEC
return True
def confirm(self, buyer: str, now: int) -> bool:
if self.state == "HELD" and self.holder == buyer and now < self.expires_at:
self.state = "BOOKED"
return True
return False
seat = SeatInventory("A12")
print("t=0s Buyer 1 hold:", seat.try_hold("buyer-1", now=0), seat.state)
print("t=0s Buyer 2 hold:", seat.try_hold("buyer-2", now=0), "(blocked by active hold)")
print("t=601s Buyer 1 confirm:", seat.confirm("buyer-1", now=601), "(hold expired)")
print("t=601s Buyer 2 hold:", seat.try_hold("buyer-2", now=601), seat.state, f"holder={seat.holder}")
print("t=620s Buyer 2 confirm:", seat.confirm("buyer-2", now=620), seat.state)Apply
Your turn
The task this lesson builds to.
Architect a reservation system for a 20,000-seat concert venue that supports interactive seat maps, 10-minute checkout holds, and zero double-bookings during on-sale spikes.
Think about
- Why must holding a seat and charging a credit card happen in two separate short transactions?
- When do pessimistic row locks beat optimistic version CAS, and why is Redis alone unsafe?
- How do you resolve a payment that succeeds seconds after the 10-minute hold expires?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Outline the data model and locking strategy for a multi-night hotel booking platform where guests reserve date ranges across room types (50 identical Standard Queens) rather than individually numbered seats.
Think about
- Why does modeling per-(room_type, date) inventory counts beat locking 50 individual room rows?
- How do you prevent deadlocks when two transactions lock overlapping multi-night date ranges?
- How does intentional hotel overbooking (e.g., 105% capacity) fit into the constraint?
Draft your design answer here Save your draft, compare against the model answer, and track progress.