#67 Holds/State Machines
Reservation System
Reserve a limited resource (a seat, a room, a table) fairly, hold it while the user pays, and never give it to two people.
What is being asked
Design a general reservation system that works for flights, hotels, restaurants or events. The core problem is the same in all of them: limited inventory, many people competing for it, and a gap between "I want this" and "I've paid".
Requirements
Functional
- Check availability, place a hold, confirm with payment, cancel.
- Holds expire automatically if not confirmed.
- Look up a reservation by reference number.
Non-functional
- Never oversell (unless overbooking is a deliberate business rule).
- Handle bursts when popular inventory goes on sale.
- Every state change must be auditable.
Design
A reservation moves through a state machine:
HELD → CONFIRMED → (CANCELLED | COMPLETED) and HELD → EXPIRED
- Hold: in one transaction, decrement available inventory (only if it stays ≥ 0) and insert a reservation in
HELDwith an expiry time, for example 10 minutes. - Confirm: after payment succeeds, move
HELD → CONFIRMED. The update checks the current state, so a late payment on an expired hold is refunded rather than confirmed. - Expire: a worker finds holds past their expiry, marks them
EXPIREDand returns the inventory.
Key decisions and trade-offs
- Conditional updates beat locks.
UPDATE inventory SET available = available - 1 WHERE id = ? AND available > 0lets the database arbitrate without holding row locks during payment. - Hold duration is a product decision: long enough to pay, short enough not to block inventory.
- Reference numbers should be short, unambiguous (no O/0, I/1) and not guessable.
- Event log. Store every state transition, not just the latest state; it answers "what happened to my booking?" disputes.
Follow-up questions
- Payment succeeds one second after the hold expired. What happens?
- How would you support a waiting list?
- How do you shard inventory when one event has 100,000 seats?
- How do you allow 5% deliberate overbooking for no-shows?