Part 7 of 8 · 2 min read
Trade-offs
What to choose and say.
Trade-offs and what to say
| Choice | Gain | Cost |
|---|---|---|
| Pessimistic lock | Simple, no conflicts | Waits, deadlocks, poor scale |
| Optimistic lock | Fast, no DB locks | Retries under heavy load |
| Database constraint | Easy, last line of defence | Hard to version, user-visible failures |
| Idempotency key | Safe retries | An id to create and store |
| Inventory cache | Low load | Briefly stale, needs sync |
| Shard by hotel | Spreads load | Cross-hotel queries are harder |
Cancellations. A cancel lowers total_reserved for the dates and changes the reservation status. It must be one transaction, and must also be idempotent, so a repeated cancel does not subtract twice.
Payment. The reservation moves from pending to paid when payment succeeds. If payment fails or times out, the pending hold is released. Level 12 covers payment in detail. For now: keep the booking and the payment linked by the reservation id.
Failures between services. The reservation service and payment service are separate, so a crash between them can leave a reservation pending without a payment. A background job that cancels stale pending reservations repairs this, and a saga (Level 7) can coordinate the steps.
Interview angle
Answer in your head first, then open it.
What is the hard part?
Concurrency on few hot rows, not volume.
How do you avoid a double click booking twice?
An idempotency key as the primary key of the reservation.
How do you avoid selling the last room twice?
Optimistic locking or a database constraint, with a transaction.
Why not pessimistic locking?
Long locks, deadlocks and poor scale.
How do you scale?
Shard by hotel, cache reads, keep the database as the source of truth.
One follow-up to try. "A flash sale opens 1,000 rooms at one minute past noon and 50,000 people arrive." A good reply: put the visitors in a waiting queue and let in only as many as the system handles (Level 8, load shedding). Serve availability from the cache. Do the real booking against the database with optimistic locking and a limit on retries. Tell users clearly when the rooms are gone, instead of letting them retry without end.
Check yourself: 1. Why must a cancel be idempotent? 2. What repairs a reservation that was never paid? 3. How does a waiting queue help in a flash sale?
Words you will meet
| Word | Meaning |
|---|---|
| Overbooking | Accepting more bookings than rooms |
| Inventory | The count of rooms of a type on a date |
| Idempotent | Giving the same result however many times it is called |
| Idempotency key | A unique id that marks repeats of one request |
| Pessimistic locking | Locking a row before changing it |
| Optimistic locking | Checking at write time that nothing changed |
| Constraint | A rule the database enforces on its data |
| Source of truth | The store whose value wins in a disagreement |