Transactions and concurrency
Keep the invariant true when requests overlap.
The idea
Two clients can both observe one seat available. A read followed by an unguarded write can oversell. Move the invariant into an atomic database operation or choose an isolation and locking strategy that protects it. A local transaction cannot atomically include an arbitrary external payment service.
Follow the flow
Make it concrete
This excerpt isolates the concept. Connect it to the booking API as you work through the exercise.
UPDATE seats
SET remaining = remaining - 1
WHERE event_id = $1 AND remaining > 0
RETURNING event_id;
-- No returned row means the reservation did not succeed.Decisions that matter
- Database constraints are the final defense for data invariants.
- Long transactions hold locks and can reduce concurrency.
- Retries need a bounded policy and must not duplicate committed side effects.
Your turn
Run two simultaneous reservations against the final seat. What result and final state must hold?
Reveal a worked answer
Exactly one reservation succeeds, remaining becomes zero, and the other caller receives a documented unavailable or conflict result. Use separate database connections in the test and assert committed state, not just returned values.