Systemsfor Aravinda
0 / 78 core
Week 11 · Case studies

Design hotel reservation

1.5 hours · core path

Read first: Transactions and isolation, Choosing a database

In one sitting

Hotel inventory is a row you update under a predicate, or a physical room you mark held, plus a hold that expires. Snapshot isolation still lets two guests insert two bookings when the only check was a count of other rows. Confirm the hold before you trust a payment, and key the confirm so a double click is one stay.

Two guests want the last king room on the same night. The rest of the product is a catalog with photos. The design is the invariant: that night ends with at most as many confirmed stays as there are rooms, and a guest who walks away does not pin the room until the front desk notices.

Requirements

The user is a guest booking a room type for a set of nights at one hotel. A second user is the hotelier who needs the inventory to match the keys behind the desk.

Functional requirements:

  • Search availability by place, dates, and party size.
  • Place a short hold while the guest pays.
  • Confirm a stay exactly once per attempt, and release the hold if they do not.
  • Show a guest their own reservation after a refresh.

Non-goals:

  • A ranking of hotels, ads, or a loyalty program. Search can be a filter over availability.
  • Prices that move while the guest is on the page. Quote a price, store it on the hold, and treat a later price change as a different product.
  • A channel manager that syncs three outside travel sites. One inventory, owned here. If you add a channel later, it has to take the same conditional update. It does not get its own counter.
  • Cross-hotel trips. One booking touches one hotel, so one partition can own the transaction.

Choosing a database is easy to overthink here. You want row updates with a predicate, a unique key on the reservation, and a primary you can read your own write from. A document of “current availability” rewritten by each app server is how the last room gets sold twice.

Estimation

Assumptions, stated as assumptions:

  • 25,000 hotels.
  • 80 bookable rooms per hotel on average, so 2,000,000 rooms.
  • On a typical day, 10 percent of rooms take a new booking: 200,000 bookings.
  • A completed booking is preceded by 30 availability searches.
  • A stored booking is 500 bytes.
  • You keep bookings for 3 years, three copies.
bookings / day     2,000,000 * 0.10 = 200,000
per second         200,000 / 86,400 ≈ 2.3
shortcut           200,000 / 100,000 = 2 per second

searches / day     200,000 * 30 = 6,000,000
per second         6,000,000 / 86,400 ≈ 70
Sunday peak, 10×   about 700 searches/s   (10× is an assumption)

bytes / day        200,000 * 500 = 1e8 ≈ 100 MB
one year           about 37 GB
three years        about 110 GB
three copies       about 330 GB

A day is 86,400 seconds. The 100,000-second shortcut says about 2 bookings a second, and the real divisor says about 2.3. Search at a few hundred per second at peak is a small read load. Disk for a few years of stays fits on one machine. Say that out loud. Interviewers who hear “hotel” sometimes draw a global sharding scheme before they have a load that needs it.

The load that matters is narrower. Assumption: 2,000 guests try to book one hotel on one holiday night, spread over 5 minutes. That is 2,000 / 300 ≈ 7 attempts a second, all aimed at one inventory row or a handful of room rows. Aggregate QPS is a distraction. Lock waits on that row are the system.

High-level design

Search reads a replica or a short-lived cache. Booking does not. A hold, a release, and a confirm go to the primary that owns that hotel. Payment is a call you make after the hold has committed, never while a database transaction sits open. A sweeper, or the next update’s predicate, returns expired holds to the free pool.

flowchart LR
  guest[Guest]
  search[Search service]
  replica[Availability replica]
  book[Booking service]
  primary[Inventory primary]
  pay[Payment call]
  sweep[Expiry sweeper]
  guest --> search
  search --> replica
  guest --> book
  book --> primary
  book --> pay
  sweep --> primary

Shard the primary by hotel id. Every night for one hotel lives together, so a multi-night stay is one local transaction. A famous hotel is then a hot partition. More shards do not split a single inventory row. If that row’s lock wait exceeds the guest’s budget, put a small queue in front of that hotel’s booking path and keep the invariant on the row.

Deep dive

Inventory is a row you can conflict on

There are two honest shapes.

One row per physical room per night. The row is free, held, or sold. A hold is an update that matches only a free row and sets the hold id and the expiry. Two guests who target the same room conflict on that row. Two guests who target different rooms do not, and they should not. The scarce thing and the locked thing are the same row.

One counter per room type per night. remaining = 4 for kings on 3 March. The update is a single statement: decrement remaining where remaining is at least the number of rooms requested. The database locks that row, checks the predicate, and writes. Zero rows changed means the guest does not get the room. You tell them it is gone. You do not retry in a loop against a sold-out night.

Both shapes work because the write lands on a specific row that represents the scarce unit. What does not work is reading a count, deciding in the app, and inserting a new booking row as the only write.

What snapshot isolation still gets wrong

Transactions get you atomicity and a menu of isolation levels. Snapshot isolation stops dirty reads, non-repeatable reads, and phantoms. Write skew still gets through. This booking is the textbook case.

Capacity is 5. Four booking rows already exist. Guest A and guest B both start a transaction and both count booking rows. Each count returns 4, because each snapshot was true when it was taken. Each inserts a new booking row. The inserts do not touch a row the other transaction wrote, so snapshot isolation has no write-write conflict to abort. Both commit. The night now has 6 bookings. Each statement was locally honest. The invariant lived across rows, and nothing enforced it.

Step Guest A Guest B
Count bookings 4, capacity 5 4, capacity 5
Decide in the app one left one left
Write insert booking A insert booking B
Result under snapshot isolation both commit both commit

A second, quieter bug sits at read committed if you use the counter shape badly. Both guests read remaining = 1. Both write remaining = 0. Both commit. That is a lost update: the second write was computed from a stale read, and it did not conflict if you expressed it as a blind write of a constant. The fix is the same statement either way. Decrement in the database, with the predicate on the update, so the lock and the check are one operation.

UPDATE inventory
SET remaining = remaining - 1
WHERE hotel_id = ?
  AND room_type = ?
  AND night = ?
  AND remaining >= 1

If the statement changes one row, the guest has the room. If it changes zero, they do not. You do not need a serializable mode to get this particular invariant right. You need the scarce unit to be a row your update can miss.

The room-row shape has the same discipline. Update the room from free to held where the id matches and the status is still free. Include the hold id in that write. A confirm that only says “sell room 14” can sell someone else’s later hold. A confirm that says “sell room 14 if the hold id is still H” cannot.

The hold and the clock

A hold exists so the guest can pay without the room vanishing, and so a guest who closes the laptop does not keep it. Assumption: the hold lasts 10 minutes, stored as an expiry on the row.

Use the database clock in the predicate. Application machines disagree by more than a web form should care about, and a sweeper that uses its own wristwatch will fight a confirm that used a different one.

The confirm matches the hold id, the room, and an expiry still in the future according to the database. The sweeper matches the hold id and an expiry already in the past. Those predicates are disjoint for a given hold. One of them changes the row. The other changes zero rows and stops.

Search can be stale. A cache of a few seconds, or a replica that lags, may show a room that a hold just took. That is acceptable. The guest is disappointed on submit, not double-booked. Booking reads and writes the primary. A guest who just confirmed must see the stay on refresh, so that read is the primary or a session that is known to include the write.

Payment is not inside the database transaction

A payment call leaves your process and comes back when it comes back. Hold a row lock across that call and every other guest for that room waits on a company you do not control. Commit the hold. Then pay. Then confirm.

The dangerous order is the reverse: charge the card, then discover the hold expired and another guest took the room. You now owe a refund to someone who has no stay. Extend the hold first, with a conditional update that matches the hold id and adds a few minutes (assumption: one extension of 5 minutes, once). If that update matches zero rows, do not charge.

Give the confirm a client-generated idempotency key. A double click and a timeout retry must return the same stay, not decrement remaining twice and not charge twice. Store the key with the outcome. If the process dies after the charge is accepted and before the row flips to sold, a recovery scan sees the key and finishes the flip. Record that you are about to charge, then charge, then record that you did. A retry continues from that point. A local database transaction can roll back. A captured charge cannot.

Do not invent a long distributed transaction across the bank. One hotel’s rows are one database. Keep them that way.

Tradeoffs

Choice What you gain What you spend
One row per physical room Two guests only conflict if they picked the same room More rows, and a search that has to skip held and sold rooms
One counter per room type and night A simple “how many left” and one lock per type Every king-room buyer for that night serializes on one row
Conditional update on that row The last room goes to one guest The loser must be handled in the product, not retried blindly
Snapshot isolation plus inserts from a count Familiar read-then-write application code Write skew, two confirmed stays, one room
Hold of 10 minutes Time to pay, then the room returns A popular night looks full while holds sit unpaid
Search on a replica The primary stays free for holds A guest can see a room disappear on submit
Extend the hold, then charge You do not capture money for a room you lost A few extra minutes of inventory pinned during payment

Failure modes

Dependency down. The payment service times out. The hold is still a hold. You do not flip it to sold. The guest sees a retryable error and the same idempotency key. If they never return, the sweeper releases the room at expiry. If the primary is down, search can keep showing a stale catalog, and booking stops. Selling from the replica would oversell. Availability of the brochure is not availability of inventory.

Retry storm. The client retries confirm because the response was lost. Without the idempotency key, each retry decrements the counter or inserts another stay. With the key, the second call returns the stored stay. Bound the retries. A sold-out night is not a reason to hammer the predicate in a loop: zero rows is an answer.

Hot partition. One hotel, one holiday, one counter row. The attempts are only about 7 per second in the assumption above, and they queue on a lock. That is correct behavior, and it is still a bad guest experience if each attempt holds the lock across anything slow. Keep the update to the single predicate statement. If a larger spike shows up (a festival, a bad client), queue in front of that hotel id. Do not split the counter across two databases and try to add the halves. The split is how the count invariant becomes write skew again.

Consistency. The failure you are here to name is write skew: two inserts, snapshot isolation, six bookings for five rooms. The related failure is a confirm that ignores the hold id and finalizes a room that has already been released and re-held. Stale search is a consistency choice you are allowed to make. Stale confirm is not.

Durability. A confirmed stay has to survive a crash. Commit it on the primary and replicate synchronously enough that a failover does not resurrect the room as free. A hold may be lost in a crash; the guest retries and takes a new one. A sold stay may not. If you replicate bookings asynchronously and promote a lagging replica, you can sell a room whose sale was on the dead primary. Fence the old primary and fail over only to a replica that has the commit. That is the same fencing story as any other primary.

In the interview

First five minutes: one hotel, one night, the last room. Non-goals are ranking and channel sync. The number is about 2 bookings a second average and a hot row at a handful of attempts a second, so this is a correctness problem. The bottleneck is the inventory row, not the search fleet. The tradeoff is a stale search against a strict confirm.

Draw search on a replica, the conditional update on the primary, the hold expiry, and the payment call outside the transaction. Skip the photo pipeline and the tax engine.

The question that usually follows is “walk two guests through snapshot isolation.” Tell the insert story, then the predicate update, and say which rows each one touches. The question after that is the expired hold racing the charge. Extend, then charge, then flip, under the hold id, with an idempotency key.

Check yourself

Two guests each count four bookings, the capacity is five, and each inserts a new booking row under snapshot isolation. What is stored, and why did isolation allow it?

Six bookings. Each snapshot honestly saw four rows. Each insert wrote a new row, so there was no write-write conflict on a shared row. Snapshot isolation does not check an invariant that lives only in the combination of the rows. Both transactions commit.

What does a conditional decrement change about that race?

The scarce unit is one inventory row. The update subtracts one only while remaining is at least one, in a single statement. One guest’s update changes the row. The other changes zero rows and does not book. You no longer decide eligibility from a count you read earlier in the application.

The sweeper and the confirm run at the same moment. How do you keep them from both succeeding?

Both statements name the hold id and use the database clock. Confirm requires the expiry to still be in the future. The sweeper requires it to be in the past. At most one predicate matches. The loser sees zero rows. A confirm that names only the room can sell a later guest’s hold.

Why is a five-second stale search acceptable when a stale confirm is not?

Search is allowed to show a room that was just held. The guest finds out at submit, and the primary rechecks. Confirm is the write that creates a stay. If it runs from a stale read or a lagging replica, two guests can hold one room, or a failover can forget a sale. Read-your-writes for the guest’s own stay comes from the primary or a session that includes the commit.

You charged the card and then learned the hold had expired. What was the wrong order, and what do you store so a retry is safe?

The charge ran before a conditional extend of the hold, so you captured money for inventory you no longer had. Extend the hold while the hold id still matches, then charge, then mark the room sold. Store an idempotency key and the point you had reached, so a crash after the charge finishes the flip instead of charging again.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes; Brandur Leach on idempotency recovery points.