Hotel Reservation: Scaling It
You named the gap first, so at minute twenty that is where the interviewer starts: two guests, one room, the same millisecond, and which of them gets it. Next, one guest clicks twice, and the same request arrives at two servers. Then they point at a hundred searches for every booking, all reading the tables that bookings write. Last they ask you to cut the data up, and the real test is whether you can say what for.
The Last Room
"Both guests press Book at once, and one room is left. Show me the step where one of them loses." The design has no such step, so it gets a row they both must touch. Each hotel, room type and night gets one count row, with the number left in it. A booking inserts the reservation, then lowers the count for each night, earliest night first, with a conditional write that applies only where a room remains, all in one transaction. If any night's write changes no row, the whole transaction rolls back, and the guest is refused.
-- room_counts.free has CHECK (free >= 0)
BEGIN;
INSERT INTO reservations (id, hotel, request_id, guest, room_type, nights, state)
VALUES ('h4217-r88321', 'h4217', '0195e2c4-...', 'g902', 'deluxe', ..., 'confirmed');
-- once per night, earliest first; no row changed: ROLLBACK and refuse
UPDATE room_counts SET free = free - 1
WHERE hotel = 'h4217' AND room_type = 'deluxe'
AND night = '2027-03-10' AND free > 0;
UPDATE room_counts SET free = free - 1
WHERE hotel = 'h4217' AND room_type = 'deluxe'
AND night = '2027-03-11' AND free > 0;
COMMIT;
That block is the insert, then one update per night, earliest first, all committed together. The insert goes first so that a repeat on the last room, the next push, hits the request ID's constraint and not a zero. The price is small: a guest who loses writes one row and rolls it back. A check constraint also says that no count may fall below zero. That is the last line, because it also stops the next code path, not only this one. The race on one row, and why reading and then writing loses it, is Backend Deep Dive's lesson on the oversell. What is new here is the run: all nights or none, and one order, so overlapping stays cannot deadlock. This runs at read committed, where a waiting update re-reads the row once the first commits. At PostgreSQL's repeatable read the waiter aborts instead, so the store still decides, at the price of a retry.
Now answer the question they asked: "Both guests now have to lower the same row, and the second finds zero and changes nothing, so the store decides who got it."
A count row has to exist before it can be lowered. A small daily job adds the night that has just come within 365 days, which is 32,000 rows, and drops the night that has passed. A booking for a night not yet on sale changes no row, and is refused.
What it costs: derived data that must stay in step, and a wait on each row. In step means a cancel raises the same counts, earliest first, in one transaction. Its first write moves the reservation from confirmed to cancelled, and applies only if it was still confirmed, so a second DELETE changes no row and raises nothing.
As for the wait, assume a transaction keeps a count row locked for about 5 milliseconds. One row passes about 200 bookings a second, against one every 1,000 seconds at a hotel at peak. Only a sale comes near that, and the curveballs take it up.
The Double Click
"The guest's finger bounces, and two identical requests land on two servers. Who notices?" Right now nobody does, and both book. So the page carries a request ID, a 16-byte UUID made when the page renders. The reservation stores it, under a unique constraint on hotel and request ID, inside the booking transaction.
A repeat hits the constraint, and its transaction rolls back, so no count moves. The server then reads the first reservation and returns it. If the first is still in flight, the repeat's insert waits for it and then fails the same way. It does not matter which server took which request, because the check lives with the effect.
A check in a cache would be a second step with a gap in front of it, the argument in Chapter 6's Delivery Semantics at Scale. The constraint names the hotel so that it still works on one partition after the split, the last push of this lesson. One service's version of this key is Backend Deep Dive's lesson on idempotency keys. No outside party is involved here, and that case is Chapter 24's.
The ID arrives from a client, so the server does not trust it. A repeat has to match the stored guest, type and dates. Anything else is refused, and never answered with somebody else's booking.
What it costs: one ID per real intent, so a second room needs a fresh page. And the app has to keep the ID until it has an answer, or a reload books again.
Searches at a Hundred to One
"Eight hundred searches a second, 200 checks each, on the tables your bookings write. Where should all of that go?" Away from the booking store. Search reads a copy of availability, keyed by hotel, type and night, and the booking path never reads it. The store stays exact, and the copy is allowed to fall behind.
An outbox keeps it current, the pattern in Chapter 5's Transactions Across Partitions. The booking transaction also writes one outbox row, with the new counts and the reservation. A relay reads those rows in order, updates the copy and marks them sent. Each message carries the new count, not the change, and a sequence number, so a repeat or a late message cannot overwrite anything newer.
Memory does not size the copy, which is 1.2 gigabytes against a cache node's 100. The rate does. A hundred and sixty thousand simple reads a second, at about 100,000 a node, is two nodes, and four at half their limit, each with all of it. A search sends its 200 checks to one node as a batch. That saves round trips and not the node's work, so 160,000 is still the number to divide. The list of hotels in each city barely changes, and sits on the same nodes.
Assume a lag of up to 5 seconds. If the relay stops, the lag grows, so you alert on it. Guests then see rooms that have gone or miss rooms that came back, and no booking is harmed, because none reads the copy. A new or emptied node loads the 12 million counts from the store before it takes a search, while the relay's messages wait for it.
What it costs: a guest can see a room that has gone, and the booking refuses them truthfully. And there is a relay to run. So the change has a trigger. While searches are few, a read replica does this with nothing new to run, as in Chapter 2's Read Replicas and Lag. Move to the copy when a measured replica falls behind them.
What the Split Is For
"Thousands of hotels, four types, a year of nights. That sounds like a lot of data. How would you cut it up, and why?" Partition by hotel ID, with type and night as the sort key, the choice in Chapter 3's Picking the Partition Key. A booking's counts, reservation and outbox row then commit in one local transaction, and a cancel finds its partition from the hotel at the start of the reservation's ID.
Now work the three signals of Chapter 3's When One Machine Is Not Enough out loud. Bytes first: 730 gigabytes of reservations and 1.2 gigabytes of counts fit a 2-terabyte node. Then writes. A booking writes a reservation, 2 counts and an outbox row, and the relay's mark on that row is a fifth write. Five writes times 8 bookings is about 40 a second at peak, far under a partition's 1,000. And the reads have gone to the copy. No signal passes one machine.
So the split buys a smaller failure. With one primary, a failover stops booking at all 8,000 hotels, and a sale at one hotel queues on the machine serving the rest. Assume the product accepts a failover pausing one hotel in twenty. That is 20 partitions of 400 hotels, with about 37 gigabytes of reservations each.
Each partition is a primary and two replicas, and a commit waits for a replica in another zone, so a confirmed reservation survives the loss of any machine. When a primary dies, a consensus group elects its successor, as in Chapter 5's Leader Election and Consensus. That partition refuses bookings until the old primary is fenced, cut off so that it can confirm nothing, and search keeps answering from the copy.
The trigger runs the other way too, and it pays to say so: "Nothing here forces a split. The bytes fit and the writes are tiny. I'd split by hotel only to shrink what one failover stops, and if you'll accept a pause across the chain, I'd keep one primary with the key already chosen."
What it costs: 20 partitions at three machines each is 60 machines, where three could store the bytes, though each can be small. Your reservations now name a guest and cross partitions, so that list gets a table keyed by guest, fed from the outbox, with the same 5 seconds of lag. The confirmation reads the reservation by ID from its partition, so only the list lags. Chain-wide reports scatter and gather.
The Full Design
A search goes from the load balancer to the app servers, then to the availability copy on four cache nodes. A booking goes to the inventory store, split by hotel, with counts, reservations and an outbox together on each of 20 partitions. A relay on each partition carries the changes to the copy and the guest table. Reservations remain the record of who has what, and the count rows are derived from them. A nightly job recomputes each count from the live reservations and pages on any difference, and the reservations win. The figure marks the new parts.
- Reaching for a distributed lock when the store has both rows and can settle it in one write.
- Letting the booking read the copy to save a query, which brings the double sale back.
- Announcing a shard by hotel for scale when no node is full. The interviewer asks which limit you passed.
- The count row justified by the race, not by speed.
- The copy's staleness given as a number, along with who feels it.
- The split said to be for failure size, with the arithmetic that rules out bytes and writes.
Knowledge Check
The count row settles the last-room race. What have you taken on by adding it?
- A second database that needs its own replicas and failover
- A lock on the entire hotel for the length of each booking
- Derived data that each booking and cancel must keep in step
- A retry loop for each booking that loses a version check
The availability copy lags by up to 5 seconds. What can a guest see because of that?
- A room that has gone, which the booking then truthfully refuses
- A confirmation for a room that another guest has already got
- A reservation that vanishes once the relay has caught up again
- Two reservations on one room, for up to 5 seconds at a time
Why does the unique constraint on the request ID also name the hotel?
- Two guests at two hotels might generate the very same UUID
- The search copy is keyed by hotel, and it reads this ID as well
- Without it, the index would outgrow a 2 TB node within 5 years
- A store split by hotel can enforce it only within one partition
The interviewer asks which of Chapter 3's signals forces the split by hotel. What is the honest answer?
- The bytes, since 2.2 TB with replicas overflows a 2 TB node
- None passes one machine, and the split buys a smaller failure
- The writes, since 160,000 checks a second outrun a partition
- The reads, since searches run at a hundred times the bookings
You got correct