Design Hotel Booking

How a hotel booking system searches availability, claims several nights in one transaction, holds rooms during payment and handles overbooking.

Case study27 minLesson 7 of 10
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A hotel booking site lets guests search for places to stay by location, dates and number of guests, look at a listing, and book one or more rooms for a range of nights. It is hard to design for two reasons. A stay covers several nights, so one booking has to claim several inventory rows at once without ever selling a night twice. And guests search and browse far more often than they book, so most of the load comes from reading availability that keeps changing.

The steps below follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a site where people book hotels and holiday homes.

You

Do we have both hotels, which have many rooms of the same type, and homes, which are a single unit? And does a guest book instantly, or does the host have to approve?

Interviewer

Both kinds of property, and instant booking only.

You

How many properties and bookings a day should I plan for, and how much do guests browse before they book?

Interviewer

About a million properties and 500,000 bookings a day. Assume 100 searches and 200 listing views for every booking.

You

So reads outnumber bookings by about 300 to 1. We must never confirm two guests for the last room, but search can be a few seconds behind. So search can use slightly stale data, and the booking transaction is what decides whether a night is really available.

  • Functional: search by place, dates and number of guests; view a listing with photos, prices and a calendar; book one or more rooms of a type for a range of nights; pay; cancel.
  • Non-functional: no night is ever sold beyond its limit, so inventory needs strong consistency; search responds within 300 ms and may lag behind bookings by a few seconds; listing pages respond within 200 ms; a hold lasts 15 minutes; a confirmed booking is never lost.
  • Out of scope: reviews, host payouts, messaging, price setting and loyalty programmes.

Estimate the scale

A day has 86,400 seconds, and we assume the busiest hour runs at 5 times the average rate.

  • Bookings: 500,000 ÷ 86,400 is about 6 a second, and about 30 a second at peak. One database primary can handle this.
  • Searches: 500,000 × 100 = 50 million a day, which is about 600 a second and 3,000 a second at peak.
  • Listing views: 500,000 × 200 = 100 million a day, which is about 1,200 a second and 6,000 a second at peak.
Estimate: Inventory rows for a year ahead

Inventory is stored as one row per room type per night, for the next 365 nights. How much space do those rows take?

You know
  • 1 million properties
  • 2 room types per property on average (a home is one room type with one unit)
  • 365 nights ahead
  • About 50 bytes per row

Show the working
  1. 1,000,000 × 2 = 2 million room types
  2. 2,000,000 × 365 = 730 million rows
  3. 730 × 106 × 50 B ≈ 36.5 × 109 B, about 37 GB

Estimate 37 GB (anything from 10 GB to 150 GB is a good answer)

This fits on one machine, so the size of the data is not a reason to partition it.

Your turn: Define the API

Write the endpoints for search, a listing page and booking. How do you write the dates of a stay, and what does booking return when one of the nights has just sold out?

Compare with a model answer

Search and listings are GET requests. Booking is a POST that creates a held reservation, and a second call pays for it. A stay is written as a check-in date and an exclusive check-out date in the property's local calendar, and a night that has just sold out returns 409 Conflict.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
GET  /search?near=38.72,-9.14&check_in=2027-06-12&check_out=2027-06-15&guests=2&cursor=...
  200 { "results": [ { "property_id": 501, "room_type_id": 42,
                       "total_cents": 39000, "photo": "..." }, ... ],
        "next_cursor": "..." }
 
GET  /properties/{id}                        static content, cacheable for minutes
GET  /properties/{id}/availability?from=2027-06-01&to=2027-08-01
  200 { "room_types": [ { "id": 42, "nights": [ { "date": "2027-06-12",
          "free": 3, "price_cents": 13000 }, ... ] } ] }
 
POST /reservations          Idempotency-Key: 7f3c...
  body: { "property_id": 501, "room_type_id": 42,
          "check_in": "2027-06-12", "check_out": "2027-06-15",
          "rooms": 1, "guests": 2 }
  201 { "reservation_id": 88001, "status": "held",
        "held_until": "...", "total_cents": 39000 }
  409 Conflict      not enough rooms on 2027-06-14; body lists similar options
  400 Bad Request   check_out not after check_in, or more than 365 days ahead
 
POST /reservations/{id}/pay
  200 { "status": "confirmed" }
  402 Payment Required   declined; the hold stays until it expires
  410 Gone               the hold expired
 
POST /reservations/{id}/cancel

The API decision worth explaining is how to write the dates. A stay is two plain dates in the property's own calendar, with no time zone, and it covers the nights from check-in up to but not including check-out, so a stay from 12 June to 15 June uses the nights of the 12th, 13th and 14th.

Your turn: Model the data

Sketch the tables for room types, inventory and reservations. How does a booking for three nights claim all three nights at once?

Compare with a model answer

Inventory has one row for each room type and night, with a total and a reserved count. One transaction adds to the reserved count on every night that still has room, and it commits only if every night was changed.

Model the data

Room types, nightly inventory, reservations
room_types
  property_id    BIGINT
  room_type_id   BIGINT
  name           VARCHAR(100)   -- "Double room, sea view"
  max_guests     SMALLINT
  total_units    SMALLINT       -- 1 for a home
  PRIMARY KEY (property_id, room_type_id)
 
inventory                        -- one row per room type per night
  property_id    BIGINT
  room_type_id   BIGINT
  night          DATE           -- local date at the property
  total_units    SMALLINT
  overbook_limit SMALLINT       -- extra units the hotel allows; 0 for homes
  reserved       SMALLINT       -- held + confirmed
  price_cents    INT
  PRIMARY KEY (property_id, room_type_id, night)
 
reservations
  reservation_id BIGINT
  property_id    BIGINT
  room_type_id   BIGINT
  user_id        BIGINT
  check_in       DATE
  check_out      DATE           -- exclusive
  rooms          SMALLINT
  status         VARCHAR(10)    -- held | paying | confirmed | expired | cancelled
  held_until     TIMESTAMP
  total_cents    INT
  idem_key       VARCHAR(64) UNIQUE
  PRIMARY KEY (property_id, reservation_id)

A hotel sells a room type, not a specific room such as room 214, because the front desk assigns the actual room at check-in. Inventory is therefore a count for each room type and night. A home is a room type with total_units = 1.

A booking changes several rows of one property, and all of those changes must succeed or none of them, so the data belongs in a relational database with transactions. Every key starts with property_id, so partitioning by property later never splits one booking.

Your turn: High-level design

Sketch search, listings and booking. Where does search get its availability data, and how does it learn about new bookings?

Compare with a model answer

A search index holds each listing together with its sold-out nights, and it is updated from the inventory change stream. Listing pages are mostly served from a CDN. A booking service is the only writer of inventory, and it calls the payment processor.

High-level design

Search and listing pages read copies that lag by a few seconds, while only the booking service writes to the inventory primary, which checks every booking.Guest's browser to CDN (pages, photos); Guest's browser to API gateway; CDN to Search and listings (on a miss); API gateway to Search and listings (search, calendar); API gateway to Booking service (book, pay); Search and listings to Search index (query); Search and listings to Inventory replica (recheck); Booking service to Inventory primary (reserve nights); Booking service to Payment processor (authorize); Inventory primary to Inventory replica (replication), asynchronous; Inventory replica to Search index (change stream), asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryPaymentprocessorpages, photoson a misssearch, calendarbook, payqueryrecheckreserve nightsauthorizereplicationchange stream

request and replyasynchronous message

Search and listing pages read copies that lag by a few seconds, while only the booking service writes to the inventory primary, which checks every booking.
Search, book three nights, lose a race, expire a holdUse the arrows or ← → keys
  1. Search, book three nights, lose a race, expire a hold, step 1Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch index412 matchesInventoryreplicaInventoryprimaryPaymentprocessor
    nights
    12, 13, 14

    1Ana searches near Lisbon for 12 to 15 June. The index filters by distance, guests and sold-out nights, and the 25 results shown are rechecked on the replica.

  2. Search, book three nights, lose a race, expire a hold, step 2Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryPaymentprocessor
    room type 42 free
    1, 2, 1

    2She opens a hotel. The page and photos come from the CDN, and only the calendar reads about 60 rows from the replica.

  3. Search, book three nights, lose a race, expire a hold, step 3Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimary3 of 3 rowsPaymentprocessor
    room type 42 free
    0, 1, 0
    reservation 88001
    held

    3She books one room of type 42. One transaction adds 1 to the reserved count on each night that has room. All 3 rows change, so it commits and the reservation is held for 15 minutes.

  4. Search, book three nights, lose a race, expire a hold, step 4Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimary1 of 2: rollbackPaymentprocessor
    room type 42 free
    0, 1, 0
    Ben
    409 on night 14

    4Ben tries type 42 for 14 to 16 June from an older search result. Night 14 is full, so only 1 of 2 rows changes, and the transaction rolls back with a 409.

  5. Search, book three nights, lose a race, expire a hold, step 5Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryPaymentprocessorkey 88001
    reservation 88001
    paying

    5Ana pays. The reservation moves to paying, its hold is extended, and the card is authorized with idempotency key 88001.

  6. Search, book three nights, lose a race, expire a hold, step 6Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryPaymentprocessor
    reservation 88001
    confirmed

    6The reservation becomes confirmed. Inventory does not change, because the hold already counted the nights.

  7. Search, book three nights, lose a race, expire a hold, step 7Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexlag about 2 sInventoryreplicaInventoryprimaryPaymentprocessor
    sold out
    12, 14

    7Nights 12 and 14 now have no free rooms, so the change stream marks them sold out in the index about 2 seconds later. Until then, the booking transaction catches any stale result.

  8. Search, book three nights, lose a race, expire a hold, step 8Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browsergoneCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryhold expiredPaymentprocessor
    reservation 88002
    held, expired

    8Carl holds type 7 for two nights and closes his laptop. The hold expires, but the reserved count still includes it.

  9. Search, book three nights, lose a race, expire a hold, step 9Guest's browser to CDN; Guest's browser to API gateway; CDN to Search and listings; API gateway to Search and listings; API gateway to Booking service; Search and listings to Search index; Search and listings to Inventory replica; Booking service to Inventory primary; Booking service to Payment processor; Inventory primary to Inventory replica, asynchronous; Inventory replica to Search index, asynchronous.Guest's browserCDNAPI gatewaySearch andlistingsBooking serviceSearch indexInventoryreplicaInventoryprimaryPaymentprocessor
    reservation 88002
    expired
    type 7 free
    +1, +1

    9A sweeper runs every minute. In one transaction it sets reservation 88002 to expired and subtracts 1 from both nights.

1 / 9

Deep dives

Reserving several nights at once

A stay of three nights needs three inventory rows to each have room, and the three claims must succeed or fail together, or a guest could end up with a booking that has a gap in it. There are two ways to do this.

Nightly counts with a conditional update. Each night has a row with a limit and a reserved count. One UPDATE statement adds to the reserved count on every night in the range that still has room, and the application checks how many rows changed. If the number equals the number of nights, the transaction commits. If it is smaller, at least one night was full, and the transaction rolls back. This works for hotels with many rooms and for homes with one.

Date ranges with an overlap constraint. Each booking is stored as a range of dates, and the database rejects a new range that overlaps an existing one for the same room. No nightly rows are needed, but the constraint only says yes or no for one unit. It cannot count 30 rooms of a type, so it fits only a product made of single-unit homes.

Ways to claim a range of nights
OptionGood atBad atPick it when
Nightly counts, conditional update Usual defaultOne statement claims every night that has room, and the changed row count shows whether all did. It works for one unit or many.The nightly rows have to be created ahead of time, and expired holds need a sweeper to release them.Use it when room types have counts, which covers every hotel and also homes.
Date ranges with an overlap constraintEach booking is one row, and the database rejects overlaps without nightly rows.It only answers yes or no, so it works for single units and cannot count rooms.Use it only when the product contains nothing but one-unit homes.
Claim one room of type 42 for 12 to 15 June
BEGIN;
UPDATE inventory
   SET reserved = reserved + 1
 WHERE property_id = 501 AND room_type_id = 42
   AND night >= '2027-06-12' AND night < '2027-06-15'
   AND reserved + 1 <= total_units + overbook_limit;
-- The statement must change 3 rows (the nights 12, 13 and 14).
-- If it changes fewer, run ROLLBACK and return 409.
INSERT INTO reservations (..., status, held_until)
     VALUES (..., 'held', now() + interval '15 minutes');
COMMIT;

This is safe because an updated row stays locked until its transaction commits, so a second transaction that wants the same row waits. In PostgreSQL at the default read committed level, the waiting update then re-checks its WHERE condition, finds the night full, and skips that row, so the row count comes back short and the application rolls back. At stricter isolation levels the database raises a serialization error instead, which also becomes a 409 (see transactions and isolation). Two overlapping stays can lock the same rows in different orders and deadlock, so the application retries a transaction that the database aborts for that reason.

Searching by availability

A search combines a location, a number of guests and the availability of every night in the stay, at about 3,000 searches a second at peak. The question is where the availability part comes from. There are three options.

Query the inventory database directly. The answer is always exact, but each search scans many listing-nights on the database that handles bookings, so it only suits a small site.

Search without availability, then check each result. The index holds only static data such as location and capacity, and availability is checked afterwards. In a busy week most top results are full and must be discarded.

Keep sold-out nights in the index and recheck the page. Each room type's document in the search index lists the nights on which it is sold out. A room type matches if none of the stay's nights is in that list, which is one "must not match" filter next to the geographic filter (see Design Proximity Search). The change stream updates the index only when a night's free count reaches zero or leaves zero, so most bookings do not touch it, and it applies changes in log order.

The sold-out list does not say how many rooms are free, so a family that needs three rooms may be shown a hotel with one left. Search therefore rechecks the 25 results it is about to show with one batched read from the replica, which is 25 room types × 3 nights = 75 rows, and drops any that fail.

Holds, payment and expiry

The booking must reserve the nights before it charges the card, so that a guest never pays for nights that cannot be claimed. The flow is the same as in ticket booking: the reservation is held for 15 minutes, it moves to a paying status that the sweeper leaves alone, and the charge uses an idempotency key (Design a Payment System covers payments whose result is unknown). The difference for hotels is how an expired hold is released.

Releasing an expired hold needs a writer. In ticket booking each seat row carries its own expiry time, so an expired hold simply reads as free. Here the inventory row holds only a count, which cannot say which holds are stale, so a sweeper job releases them. It runs UPDATE reservations SET status = 'expired' WHERE reservation_id = 88002 AND status = 'held' AND held_until < now(), and only if that changed one row does it subtract from the reserved count of each night, in the same transaction.

Overbooking on purpose and by accident

Some guests never arrive, so hotels sell slightly more rooms than they have, for example 105 rooms for a 100-room hotel. The overbook_limit column lets each hotel set its own margin for each room type, with 0 for homes, and the same conditional update enforces it exactly.

Accidental overbooking is the larger risk. Hotels often sell the same rooms on several sites, and no transaction on our side stops two sites from selling the last room in the same minute. The system should push bookings to other channels within seconds.

Bottlenecks and failures

At ten times the load, search reaches 30,000 requests a second, and the search index is the first thing to scale. Shard it by region, because every query names a place, and add replicas. The 30,000 rechecks a second then need more inventory replicas. Bookings at 300 a second still fit on one primary. Partitioning by property_id gives more headroom.

When this failsWhat happensWhat you do
The change stream consumerThe index becomes stale, so more bookings return 409.No room is sold twice, because the booking transaction does the final check. Alert on the lag, and let the consumer resume from its saved position.
The inventory primaryBookings stop until a replica takes over, and search keeps working from its copies.Replicate synchronously to a standby, so that a booking the guest was told about survives the failover.
The payment processorGuests cannot pay, and holds approach their expiry.Extend the holds, and retry with the same idempotency key.
The booking service, in the middle of a paymentThe card is authorized but the reservation is stuck in paying, which the sweeper skips.A reconciler looks up paying reservations older than a few minutes at the processor by idempotency key, and then confirms or releases each one.
The sweeperExpired holds keep rooms hidden, which loses sales but never double-sells a room.Restart it, and alert on the age of the oldest expired hold.

What a strong answer sounds like

LevelWhat the answer does
JuniorUses one database for both search and booking, and checks whether the room is free before inserting the booking, adding a transaction only when prompted.
Mid-levelModels nightly inventory, claims the whole stay in one transaction, and adds holds and idempotent payment.
SeniorRecognizes that reads are the scale problem, separates a stale search copy from the exact check at booking, releases counted holds safely, and treats overbooking across sites as a business process as well as a technical one.
Availability in searchStrong answer
Interviewer

How does search know which hotels are free?

You

The index stores each room type's sold-out nights, updated from the change stream within a few seconds, and it excludes anything that is sold out during the stay. I recheck the 25 results I show against a replica. The booking transaction checks again, so a stale result costs the guest a retry and never causes a double booking.

Follow-up questions

Prices change per night. How do you show the total?

Add up the nightly prices for the stay and copy the total onto the reservation when the hold is created. A later price change then does not alter what the guest agreed to pay.

A hotel takes 5 rooms out for repairs. What happens?

Lower total_units on those nights in one transaction. If reserved is now higher than the limit on some night, do not cancel anyone automatically. Send those bookings to the relocation process instead, because cancelling a confirmed guest is a business decision.

Why not lock the night rows with SELECT FOR UPDATE, or use a version column?

Both work, but they cost more. With SELECT ... FOR UPDATE the application reads the nights, checks the counts and then writes, so the locks are held across a round trip to the application, and popular nights become a queue. With a version column the update fails whenever another booking touched the row since it was read, so a popular night causes many retries. The single conditional update checks and changes the rows in one statement, which keeps the locks as short as possible.

The guest double-clicks, or the client retries after a timeout. How do you avoid two reservations?

The client sends an idempotency key, and the reservations table has a unique constraint on it. The claim and the insert run in one transaction, so a duplicate request fails on the constraint and rolls back its claim. The service then returns the reservation that already exists for that key.

How does cancellation work?

In one transaction the service changes the status from held or confirmed to cancelled and subtracts the rooms from the reserved count of every night in the stay. It does this only if the status change affected a row, so a repeated cancel does nothing. The refund follows the property's cancellation policy.

Self-review: hotel booking0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure