Hotel Reservation: Deep Dives and Curveballs
Minutes thirty to forty-five open on a question saved for candidates who got the decrement right: why that one, out of three? Then you go back for the card you parked as a box, and for what search may believe about availability. Four curveballs follow, and each one asks you to question the business before you touch the design.
Three Ways to Protect a Run of Nights
Lead with the choice: the conditional decrement with a check constraint, where the store decides in one statement. It fits because the only rule here is a floor. Each of the other two comes in with a requirement this booking path does not have.
A person between the read and the write brings in a version on each row, retried on conflict. That fits a manager changing a room count, because no lock can wait that long. Under contention it wastes work, because a conflict says the row changed, not that the room is gone. With ten rooms left, the loser retries for nothing.
A rule the statement cannot express brings in a lock: take the count rows in night order and decide in code. It fits when the decision needs more than a floor, such as a limit per guest, and it costs a lock kept open while that code runs.
An optimistic retry reads the count and its version, decides, and writes only if the version is unchanged. Use it when a person or a long rule sits between the read and the write.
A conditional decrement lowers the count only if it would stay at or above the floor, in one statement. Use it when the floor is the only rule, because at read committed two bookings that both fit only take turns.
The Hold Across Payment
This is the hold you parked in Scope, and the box you drew in First Design. Committing first and charging next left a window with nothing said about it, and charging inside the transaction keeps row locks open across a call to an outside party. So it becomes three steps, two local ones on one hotel's partition and the charge between them, the saga of Chapter 5's Transactions Across Partitions.
First, in one transaction, insert the reservation as held, with an expiry by the database's own clock, assumed 10 minutes, and lower the counts for every night. Second, when the guest pays, charge the card with the reservation's ID as the processor's key, so a repeat cannot charge twice. Third, a conditional write moves the reservation from held to confirmed. A decline moves it from held to cancelled and raises the counts, earliest first, so the guest starts again from a fresh page.
POST /reservations/h4217-r88321/payment {"card_token": "tok_51Hx"}
200 confirmed, 202 still checking, 402 declined, or 409 expired
-- the card went through
UPDATE reservations SET state = 'confirmed'
WHERE id = 'h4217-r88321' AND state = 'held';
-- the sweep, past the expiry
UPDATE reservations SET state = 'expired'
WHERE id = 'h4217-r88321' AND state = 'held' AND expires_at < now();
-- one row changed: raise each night's count, earliest first, then COMMIT
The page pays with one more call, checked against the signed-in guest as a cancel is, which posts a card token to the reservation and answers confirmed, still checking, declined or expired. An expiry sweep, a small worker on each partition, writes from held to expired and raises the counts in one transaction. Both writes name the state, so exactly one of them wins. That is the lease kept in the database, from Chapter 5's Leases, Locks and Fencing. A DELETE on a hold writes from held to cancelled and raises the counts the same way, and a charge that lands after it is refunded.
The state is also the fence. A server that stalled for twenty minutes and wakes with a success from the processor writes to a row that is no longer held, and changes nothing. A confirmation after the 10 minutes but before the sweep still wins, which is fine, because the room has not gone back. A stopped sweep keeps rooms off sale for longer, and never sells one twice, so it gets an alert and no more.
A payment can still land after expiry. The server then tries to lower the counts again and move the reservation from expired to confirmed, in one transaction. If the room has gone, one transaction moves the reservation from expired to refunded and writes the refund into the outbox. A separate relay calls the processor under a key of its own, made from the reservation's ID, so a slow processor cannot delay the copy, a repeat refunds nothing and a crash loses nothing. A charge after a cancel is refunded the same way. The guest is left with a charge and a refund on the statement. Whether cancelling a confirmed stay refunds is a rate rule, left out in Scope.
The server that charged can also die before it confirms. So the processor's signed report, naming the reservation's ID, drives the same writes, and a charge ends up confirmed or refunded whichever way the news arrives. On a timeout nobody knows whether the card was charged, so the reservation stays held, never cancelled, and the page shows the payment as still being checked and offers no new booking. The report or a repeat under the same key settles it, and if the sweep gets there first, the late path above does. Why that state needs an owner of its own is Chapter 24's unknown outcome.
The length is a choice. Eight bookings a second for 10 minutes is about 4,800 open holds across the chain, which is nothing. The hold adds three writes to each booking, the confirmation, its outbox row and the relay's mark, so 40 writes a second becomes about 64, still far under 1,000. The price falls on the last room, where a dithering guest blocks a paying one for the whole 10 minutes. So shorten it where holds expire unpaid on nights that sell out.
A hold is also free to take, so a script could empty a hotel for 10 minutes at a time. A limit on new holds per guest belongs at the edge, with Chapter 11's rate limiter. It is a rate, not a floor on the count, so the decrement stays.
Say the bound you have just bought: "The room comes off the count before the card is touched, so the worst a slow payer costs is ten minutes of that room."
Two Truths About Availability
With 5 seconds of lag, and a hotel's counts changing every 1,000 seconds at peak, a hotel's copy is out of date about half a percent of the time. That matters only when the change took the last room. So search trusts the copy, and only the booking transaction decides.
One display breaks that bargain. "Only two left" read from the copy is a promise it cannot keep, so it is rounded or read from the store. Overbooking is the same question from the other side: a floor set by the business, not by physics.
Curveballs
"One hotel runs a flash sale: 100 rooms, and 50,000 guests in ten seconds." Ask whether it is one type on one night. Take the worst case, all 100 rooms on one row and every attempt on it. That is 5,000 attempts a second against about 200 through that row. Salting cannot help. Sub-keys would each keep part of the count, and none could say whether the whole had reached its floor, as Chapter 3's Picking the Partition Key warned of this very sale.
But 100 rooms take half a second of row time, so nearly all the load is losers. Once the count reads zero, a loser rolls its insert back and has no commit to wait for, so the row stops queuing. The partition still pays for 5,000 transactions a second, and its other hotels wait behind them. Keep the losers off the store. An admission queue in front of booking lets about 200 attempts a second through, and a sold-out flag from the copy then refuses the rest at the edge. The flag can be 5 seconds late, so about 1,000 more attempts reach the row and change nothing. Rooms back from expired holds clear the flag and reopen the queue. The queue fronts that hotel alone, so if it fails, the sale pauses and no other hotel notices.
Then give the hotel its own partition through a directory, from Chapter 3's Range, Hash and Directory. That is a small map the app servers cache, and the sale no longer queues on a machine serving 399 other hotels. A sale has a date, so the move comes first, and that hotel's bookings pause while it happens.
"Revenue wants to oversell by 5 percent." Hotels do this because some guests never turn up, and when everyone does, a guest gets walked: sent to a room at another hotel, at the hotel's cost. The floor stops being zero. Five percent of a hotel's 100 rooms is 5 rooms a night. A count is per type, so the business spreads them: a floor of minus 1 on three types, and minus 2 on the type easiest to walk a guest from. The floor is a column on the count row. The conditional write and the check constraint compare against it, so the business can change it without a deploy, and the outbox carries it to the copy. Ask who arranges that walk, because the requirement now exists.
"Other booking sites sell the same rooms." Ask how many rooms the business will hand over. Those sites will not join your transaction, so give each an allotment: a block taken out of the count, kept as a row beside the counts, which the site sells from on its own. Take back what is unsold by a release date. These are the blocks of Chapter 5's IDs Without Coordination, applied to rooms. The cost is rooms sitting in a block while your own site refuses guests. A shared pool synced by messages avoids that and sells rooms during the lag, which is overbooking nobody chose.
"A region fails in the middle of a booking." Ask how long the business can refuse bookings. Bookings are few enough to afford a synchronous replica in a second region: about 70 milliseconds across the US on each commit. So a row passes about 14 bookings a second, against one every 1,000 seconds at a hotel. The guest's retry carries the same request ID, and the promoted store either has that reservation or never confirmed it.
Refuse bookings until the old primary is fenced, because two primaries sell the same room. Two regions cannot outvote each other, so a consensus group with a member in a third place makes that call. If the second region is the silent one, commits wait until that group drops it. App servers and four more cache nodes run there too, so search survives. The sale pays as well: its 100 rooms take about seven seconds, which the queue absorbs.
How Each Level Answers
A mid-level answer builds a booking transaction on a sound reservation model. It finds the last-room race when the interviewer describes it, and fixes it with a lock or a count. It moves search to a cache once told the ratio, and treats payment as a step after the booking until asked.
A senior answer asks type or room before drawing, derives bookings from rooms, and raises the race and the double click unprompted. It chooses the decrement and says why a version would retry for nothing. It walks the hold through expiry and late payment. It says the split is not for bytes, and gives the number that shows it.
A staff answer treats never as a number the business owns, and asks who bears a walked guest. It sees the sale as a load of losers and keeps them from the store. It asks where other sites' inventory lives before drawing the store, because allotments or a shared pool change what a count means. And it prices the second region against the real write rate instead of assuming it is unaffordable.
- Answering the flash sale with more shards or a salted key, when one exact count on one row is the whole problem.
- Letting the sweep and the confirmation write without naming the state, so an expired hold is confirmed after its room was resold.
- Treating overbooking as a defect to argue about, instead of a rule to store.
- The write that makes exactly one of the sweep and the confirmation win, shown and not described.
- The sale's losers counted, and the design aimed at them.
- A business question asked at each curveball before the answer.
Knowledge Check
One hotel's sale sends 5,000 attempts a second at a row that passes about 200. What is the best move?
- Salt the count into ten sub-keys and spread them over ten partitions
- Add partitions to the store, so that the row sits on a less busy machine
- Keep the losers off the store with an admission queue and a sold-out flag
- Have each booking decide on the copy, which can absorb far more reads
Revenue wants to oversell by 5 percent. What changes in the design?
- Each count row stores a floor the business sets, and the writes compare to it
- The check constraint is dropped, so a count can fall as far as demand takes it
- A nightly job cancels 5 percent of reservations on any night that is oversold
- The search copy shows 5 percent more rooms, and the booking path stays as it is
Other sites sell the same rooms and will not join your transaction. Why give them allotments over a shared pool?
- A shared pool would need every site to run two-phase commit on each sale
- Blocks sell out faster, because each site competes only for its own guests
- Messages between companies cannot be delivered reliably or in any order
- A block cannot be oversold by lag, though unsold rooms can sit idle in it
A guest's payment lands after the sweep moved the hold to expired. What does the server do?
- Confirm the reservation anyway, since the guest has already paid for it
- Try to lower the counts again, and refund the charge if the room has gone
- Drop the payment quietly, because the reservation no longer counts as held
- Reset the expiry for ten more minutes and ask the guest to pay once more
You got correct