"Design a hotel reservation system" looks like a CRUD exercise: hotels, rooms, bookings. It is really a question about selling the same scarce thing to many people at once without ever selling more than you have.
The interviewer is watching for one move above all: do you recognize that checking availability and then booking is a race? A hotel has 20 rooms of one type left and 40 people press Book at the same moment. What stops the 21st booking? After that comes the part that separates answers: the guest takes two minutes to pay, so what happens to the room in the meantime, and why might the hotel sell more rooms than it has on purpose?
This question is distinct from its marketplace neighbors. Searching listings against calendars is Design Airbnb, a single listing that is one unit. A hotel sells room types with many identical units, which makes the problem one of counters instead of single rows. Fast-moving seat contention is Design Ticketmaster. The background is in distributed transactions and idempotency.
Clarify the requirements
Functional requirements:
- Search hotels by destination, dates and guests, and see room types with prices and availability.
- Book a room type for a date range.
- Cancel or modify a booking.
- A hotel manager sets room counts, prices and blocks rooms for maintenance.
- The guest receives a confirmation.
Out of scope, said aloud: assigning a physical room number (usually done at check-in), loyalty programs, reviews, channel managers for other travel sites, payment-processor details.
Non-functional requirements: these decide the design.
- Never sell more than the allowed inventory. The allowed number may exceed physical rooms (overbooking), but it must be a number the hotel chose, not an accident.
- Booking is a transaction across several nights. A three-night stay needs all three nights or none.
- Search is eventually consistent, booking is not. A count a few seconds stale in a result list is fine.
- Retries are safe. A guest on a bad connection who taps Book twice gets one reservation.
Estimate the scale
Assume 5,000 hotels, each with 10 room types, and 4 million daily active users. Assume 100 searches for each booking, a typical look-to-book ratio for travel.
Bookings: 400,000 a day ÷ 86,400 ≈ 4.6 per second, perhaps 15 per second at peak.
Searches: 100 × 4.6 ≈ 460 per second, or 40 million a day (4M users × 10 searches), with a peak near 1,400.
Inventory rows: one row per room type per night. For a year ahead: 5,000 × 10 × 365 = 18.25 million rows. At 100 bytes each that is about 1.8 GB, tiny.
Booking records: 400,000 × 1 KB = 400 MB a day, about 730 GB over five years.
"Booking volume is under 20 a second, so throughput is not the issue. The inventory table is under 2 GB. The hard part is correctness under contention: all the traffic for one popular hotel and room type lands on the same few rows."
Adjust assumptions in the capacity estimator.
API and data model
GET /v1/hotels/search?place=&checkIn=&checkOut=&guests= -> hotels[], room types, prices
POST /v1/reservations { reservationId, hotelId, roomTypeId, checkIn, checkOut, guests }
(client-generated reservationId is the idempotency key)
POST /v1/reservations/{id}/confirm { paymentToken }
DELETE /v1/reservations/{id}room_inventory (hotel_id, room_type_id, night) PK
total_rooms, reserved, version
reservations (id PK, hotel_id, room_type_id, check_in, check_out, status, expires_at)
status: held | confirmed | canceled | expiredThe non-obvious choice is the counter table. Inventory is not "this room is taken on this night" but "of total_rooms, reserved are sold". The reservationId is created by the client, and it is the primary key, so a duplicate request fails on a unique constraint and returns the original.
High-level design
The slice worth running is the booking path: a load balancer, a stateless booking API, a cache that serves availability to search, and the inventory database that is the only place a booking is decided.
- Clients reach the booking API through a load balancer.
- Searches read a cached availability count, while bookings go to the inventory store's primary.
Describe this diagram
Components
- clients (Client)
- lb (Load balancer)
- booking api (Service)
- availability cache (Redis)
- inventory store (PostgreSQL)
Connections
- clients sends to lb
- lb sends to booking api
- booking api sends to availability cache
- booking api sends to inventory store
Run it, then try adding load and compare reads that hit the cache with writes that must reach the primary.
The search path: the API reads cached availability per hotel and room type for the date range, with a short TTL such as 30 seconds. A slightly stale count is acceptable, because the booking will check the truth.
The booking path: the API generates or accepts the reservation id, opens a transaction against the inventory primary, increments reserved on every night of the stay under a condition, writes the reservation and commits. The cache is invalidated or left to expire.
The interesting problem: not selling the last room twice
Forty guests want the last two rooms of a type for the same night. Three approaches, in the order most candidates arrive at them.
Approach A: read, check, then write
Read total_rooms and reserved, and if reserved < total_rooms, write a reservation and add one.
Good: obvious, and it works in a test with one user.
Bad: between the read and the write, another request reads the same numbers. Both see one room left, both book, and the hotel is oversold by a number nobody chose. This check-then-act race is the same as the one in the rate limiting lesson.
Approach B: pessimistic locking
SELECT ... FOR UPDATE on the inventory rows of the stay, then check and update inside the same transaction. Other bookings for those rows wait.
Good: correct and easy to explain. No two transactions can modify the same rows at once.
Bad: a lock is held across a round trip from your application to the database and back, and for a hot room type the waiters queue. If your code calls a payment service while holding the lock, a slow payment stalls everyone. Rows must be locked in a fixed order (by date) or two overlapping stays can deadlock.
Approach C: a conditional atomic update
Fold the check into the write so the database decides in one statement per night:
UPDATE room_inventory
SET reserved = reserved + 1, version = version + 1
WHERE hotel_id = ? AND room_type_id = ? AND night = ?
AND reserved < total_rooms + overbook_limit;
-- run once per night, in ascending date order, inside one transaction;
-- if any statement changes 0 rows, roll back the whole stayGood: no read before the write, no application-level lock and only a short transaction, since the database takes the row locks it needs for the duration of the statement. Each statement reports whether its night had space, and the transaction commits only if every night did.
Bad: a multi-night stay touches several rows, so two overlapping stays can still deadlock unless each updates in date order, and the code must handle "zero rows changed" as a normal result, not an error.
The recommended answer is C, with rows updated in a fixed order and a retry on a deadlock error. The principle to state: let the database make the decision in one atomic statement, and keep the transaction short. A unique reservation id gives you idempotency for free: a retry hits the primary key and returns the existing reservation.
Diagram, as text
- Reserve request with id leads to Begin transaction
- Begin transaction leads to Conditional update on each night, in date order
- Conditional update on each night, in date order leads to Insert reservation: held (every night changed)
- Conditional update on each night, in date order leads to Roll back: sold out (a night changed 0 rows)
- Insert reservation: held leads to Commit
The second decision: holds, payment and overbooking
The guest needs a minute or two to enter payment details. In that time the room must not disappear, and it must not stay locked if the guest walks away.
Hold, then confirm. The first step creates the reservation in held state, increments reserved and sets expires_at a few minutes ahead. Payment happens after, outside any database transaction. On success, a second conditional update moves it to confirmed. On failure or timeout, the reservation goes to expired or canceled and a compensating update decrements reserved. This is a small saga: each step has an undo.
An expiry sweeper finds held reservations past expires_at and releases them, in a periodic job. Make the release idempotent, so a crash mid-sweep is safe to rerun. Do not rely on the guest's browser to cancel.
Charge exactly once. Send the payment processor an idempotency key derived from the reservation id. If the confirm request times out, the retry reuses the key, and the guest is not charged twice. The mechanics are in Design a Payment System.
Overbooking is a policy, not a bug. Some guests cancel or do not arrive, so a hotel may choose to sell slightly more than its physical rooms. In the schema, that is the overbook_limit in the condition, set per hotel from its historical cancellation rate and the cost of walking a guest to another hotel. The system's job is to enforce the chosen number exactly. Say that the policy belongs to the business and the code only enforces it, and that you would show hotels the cancellation data to tune it.
Bottlenecks and failures
Hot rows. A popular hotel on a holiday weekend sends all bookings for a room type to a few rows, and updates on one row serialize. At 15 bookings a second that is fine, because each transaction takes a few milliseconds. If it ever grew, split a room type's counter into several shards and sum them, but only when you can show you need it.
Deadlocks. Two overlapping stays that update nights in different orders can wait on each other. Always update in ascending date order, and retry once on a deadlock error.
Stale search. The cache says 2 rooms left, and the booking says sold out. That is a normal outcome. Show a clear message and offer the next-best room type, and keep the cache TTL short for nearly sold-out inventory.
Payment service down. Holds expire while payments fail. Extend the hold once when the payment provider is unavailable, with a limit, and tell the guest. Never confirm a reservation without a successful payment.
Cancellations and modifications. A cancel decrements reserved in a conditional update on the same nights. A modification is a cancel and a new reservation in one transaction, never an edit in place.
What if the primary fails? Fail over to a replica with synchronous replication for the inventory, or accept a short outage for bookings. Do not let a stale replica accept bookings, because it can sell rooms the primary already sold.
Trade-offs to name aloud
- Conditional update over pessimistic locks: short transactions and no lock held during payment, in exchange for handling "zero rows changed" as a normal result.
- Holds with expiry: a room is reserved while the guest pays, in exchange for needing a sweeper and some inventory briefly unavailable to others.
- Overbooking: higher occupancy, at the cost of occasionally relocating a guest, so it must be an explicit, bounded policy.
- A stale cache for search: cheap reads, in exchange for occasional "sold out" at booking time.
What interviewers listen for
- A working answer: an inventory table per room type and night, a transaction that checks and updates it, and a reservation table.
- A strong answer: names the check-then-act race, fixes it with a conditional update or row lock, uses a client-generated reservation id for idempotency, and separates cached search from authoritative booking.
- A standout answer: designs the hold with expiry as a saga, orders updates to avoid deadlocks, treats overbooking as an enforced business policy, and sends the payment processor an idempotency key.
Check your understanding
Common mistakes
Read-then-write on the count. It passes every single-user test and fails the first busy weekend.
Holding a lock while calling the payment service. One slow response stalls every booking on that room type.
Modeling every physical room as a row. Guests book a room type and the room number is assigned later. Counters are smaller and avoid hot individual rows.
No expiry on holds. Abandoned checkouts then lock inventory forever. Every hold needs an expires_at and a sweeper.
Treating overbooking as a defect. It is a deliberate, bounded policy. The defect is overbooking by an unplanned amount.
Editing a booking in place. A date change is a cancel plus a new reservation in one transaction, so the inventory counters stay consistent.
Practice
A promotion sends 5,000 people to book the same 40 rooms of one type in the same minute. What happens in your design, and what would you add?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Estimate the per-second rate on the hot rows before reaching for sharding.
Show a strong answer
Do the arithmetic. 5,000 requests in 60 seconds is about 83 a second, and all land on the same few rows. Each conditional update takes a few milliseconds, so one row can handle hundreds of updates a second. The design holds.
Expect most to lose. 40 succeed and about 4,960 see "sold out". That is correct behavior, but make it cheap: return the failure fast, and show alternatives such as another room type or dates.
Protect the database. Put a rate limit per user and an admission queue in front of the booking API so the primary sees a steady stream, not a spike. If the same row becomes a real bottleneck, split its counter into several rows and sum them.
The pattern worth keeping: compute the rate on the contended row first, because a few milliseconds per update serves hundreds a second, and add machinery only when the numbers demand it.
Finance finds that 30 confirmed reservations last month had inventory counters that never went back down after the guest canceled. How could that happen, and how do you detect and fix it?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about the cancel path as a saga with two writes, and what happens if one of them fails.
Show a strong answer
Likely causes. The cancel updated the reservation's status but a crash or error stopped the decrement of reserved, because the two writes were not in one transaction. Or a retry applied the decrement twice, then a second fix applied it once more, in the wrong direction.
Fix the write. Do the status change and the counter decrement in one transaction, guarded by the reservation's current status (WHERE status = 'confirmed'), so repeated cancels change nothing the second time.
Detect drift. Run a reconciliation job that, for each room type and night, compares reserved with the count of active reservations covering that night, and reports mismatches. Correct them with an explicit audit entry, not a silent update.
The pattern worth keeping: a counter derived from rows can drift, so keep it transactionally tied to those rows and reconcile them on a schedule.
Key takeaways
- Selling a scarce thing concurrently is the problem, and read-then-write is the bug.
- Model inventory as counters per room type and night, not a row per physical room.
- Make the database decide in one conditional update, and keep transactions short.
- Hold, pay outside the transaction, then confirm or release, with expiry and a sweeper.
- Overbooking is a bounded business policy that the code enforces exactly.
- Use a client-generated reservation id so retries return the same reservation, and reconcile counters against reservations.
Further reading
- PostgreSQL documentation, "Explicit Locking" and "Transaction Isolation": row-level locks,
SELECT FOR UPDATEand isolation behavior. - Martin Kleppmann, "Designing Data-Intensive Applications" (O'Reilly, 2017), chapter on transactions: write skew, phantoms and materializing conflicts.
- Pat Helland, "Life beyond Distributed Transactions: an Apostate's Opinion", CIDR (2007): activities, idempotent messages and compensation.