Hotel Booking Platform: Fast Search, Oversell-Free Reservations
System DesignModel answerLast updated
Design a hotel search and reservation system that serves low-latency search from caches while guaranteeing strict, oversell-free transactional booking across multi-night stays.
Scenario
You are asked to design a worldwide hotel discovery and reservation platform (in the spirit of large online travel sites). Travelers search for lodging by destination and dates, view live price quotes, book rooms with payment, and later look up or cancel their reservations.
Functional Requirements
- Search & discovery: Find hotels by location, check-in/check-out dates, and guest count. Filter by amenities, price range, and star rating.
- Pricing & quotes: Show accurate quotes for the chosen date range, reflecting dynamic nightly rates and taxes.
- Inventory & booking: Reserve a specific room type over a continuous range of nights. No night may ever exceed that room type's capacity (no overselling).
- Lifecycle management: Support reservation lookup, cancellation, and automatic release of inventory.
- Payment & idempotency: Integrate with external payment providers so users are never double-charged and never left with orphaned reservations.
Non-Functional Requirements
- Consistency vs. availability: Search must be highly available and fast (< 200 ms). Booking must be strictly consistent (ACID) with zero overselling.
- Idempotency: Every booking request must be strictly idempotent.
- Privacy & compliance: Payment data (PCI-DSS) and customer PII must be segregated and protected.
Scale Assumptions
- Hotels & rooms: 500,000 hotels, ~100 rooms each (~50M rooms total).
- Search traffic: 50,000 read QPS at peak.
- Booking traffic: 500 booking transactions per second at peak (~100:1 read-to-write).
- Booking window: Reservations allowed up to 365 days ahead.
What Your Design Should Cover
- API design: Core endpoints for search, room holds, booking confirmation, and cancellation.
- Data model: Schema for hotels, room types, daily inventory records, and reservations.
- Inventory management & concurrency: How you serialize concurrent bookings across multi-night stays (e.g., optimistic locking, row-level locks, distributed locks, transactional decrement).
- Reservation lifecycle & state machine: Temporary holds, hold expiration (TTLs), payment settlement, and asynchronous webhooks.
- Search architecture: Caching, tolerating stale search data, and propagating inventory/price changes into the search index.
Hints
Hint 1
Separate the read path from the write path: search can be served from caches and an index, but bookings must hit an ACID store.
Hint 2
Model inventory as one row per (room type, night); then a stay is a bounded range of rows you can atomically check-and-increment.
Hint 3
Make every write idempotent by storing the Idempotency-Key in the same transaction as the state change.
Hint 4
Holds with TTLs plus a sweeper job let you free abandoned inventory without blocking users.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the two halves first
The core insight is that this system has two very different workloads. Search is read-heavy and can tolerate seconds of staleness. Booking is write-critical and must never oversell or double-charge. So I split them: CQRS with an ACID write store and a cached/indexed read store fed by change data capture (CDC).
Back-of-envelope:
- Room types: 500K hotels × ~5 room types ≈ 2.5M room types.
- Inventory rows: 2.5M × 365 ≈ ~900M rows, ~90 GB — comfortably shardable in Postgres/MySQL.
- Bookings: 500 TPS × ~3 nights ≈ 1,500 inventory row updates/s — easy for a sharded relational cluster.
- Search: 50K QPS, < 200 ms, must never touch the transactional store.
Shard key: hotel_id. A single stay never spans hotels, so each booking is a single-shard transaction. That removes cross-shard 2PC entirely.
2. API design
GET /v1/search?lat=&lng=&radius=&checkin=&checkout=&guests=&amenities=&price=&stars=&cursor=
GET /v1/hotels/{id}/quotes?checkin=&checkout=&guests=
POST /v1/holds (Idempotency-Key header)
POST /v1/reservations/{id}/confirm (Idempotency-Key; body: payment_token)
GET /v1/reservations/{id}
POST /v1/reservations/{id}/cancel (Idempotency-Key)
POST /v1/webhooks/payments (gateway-signed)
Two subtleties: quotes are signed and short-lived, and the hold locks in the quoted price so the user doesn't see it jump at payment. Payment uses a gateway token, so raw card numbers never touch our servers (keeps us in PCI SAQ-A scope).
3. Data model
hotels(hotel_id PK, name, geo_point, star_rating, amenities[], timezone)
room_types(room_type_id PK, hotel_id FK, max_occupancy, total_rooms, attributes)
room_inventory(
hotel_id, room_type_id, stay_date,
total_rooms INT, reserved_rooms INT, price_cents INT, version BIGINT,
PRIMARY KEY (hotel_id, room_type_id, stay_date),
CHECK (reserved_rooms <= total_rooms)
)
reservations(reservation_id PK, hotel_id, room_type_id, guest_ref,
checkin, checkout, num_rooms, total_cents, currency, status,
hold_expires_at, payment_intent_id, version)
idempotency_keys(key PK, request_hash, response_blob, status)
payment_events(event_id PK, reservation_id, type, raw, processed_at)
One row per (room_type, night) turns "is this range free?" into a bounded range query over ≤365 rows and a standard transactional decrement. PII lives in a separate encrypted vault service with its own audit trail; card data never enters our systems.
4. Concurrency: transactional conditional decrement
Inside one transaction on the hotel's shard:
BEGIN;
UPDATE room_inventory
SET reserved_rooms = reserved_rooms + :n, version = version + 1
WHERE hotel_id = :h AND room_type_id = :rt
AND stay_date >= :checkin AND stay_date < :checkout
AND reserved_rooms + :n <= total_rooms;
-- if affected_rows != nights -> ROLLBACK (a night is sold out)
INSERT INTO reservations (..., status='HELD', hold_expires_at=now()+interval '15 min');
INSERT INTO idempotency_keys (...) VALUES (...);
COMMIT;
Why it's correct: the WHERE predicate plus row locks make each night's check-and-increment atomic, so no night can exceed capacity. The row-count check enforces all-or-nothing across the range; the CHECK constraint is a backstop. Updating nights in ascending stay_date order avoids deadlocks with overlapping stays.
Why not alternatives? Distributed locks (Redis/ZK) add a new failure mode without fixing correctness. Optimistic locking (read version, compare-and-swap) works but causes retry storms under contention. The conditional decrement is simplest and correct.
Idempotency: the Idempotency-Key row is written in the same transaction as the hold, so a retry returns the stored response. Same key + different request hash → 422.
5. Lifecycle and state machine
HELD ──confirm──> PENDING_PAYMENT ──webhook success──> CONFIRMED ──cancel──> CANCELLED
└──TTL──> EXPIRED └──webhook fail/timeout──> PAYMENT_FAILED (inventory released)
- Hold: decrement inventory, 10–15 min TTL. User sees "room held for 15 minutes."
- Confirm: create an authorize-only PaymentIntent, passing
reservation_idas the gateway idempotency key so a retried call can't create a second charge. Move toPENDING_PAYMENTand extend the hold by a grace window. - Webhook: verify signature, dedupe on
event_id, then guard every transition with compare-and-set on status:UPDATE reservations SET status='CONFIRMED' WHERE id=? AND status='PENDING_PAYMENT'. Duplicate or out-of-order events become no-ops. Then capture. - Expiry sweeper: scan on
(status, hold_expires_at); for expired holds, markEXPIREDand give nights back in one transaction. ForPENDING_PAYMENT, query the gateway first before releasing. - Cancellation: set
CANCELLED, release nights in the same transaction, emit an outbox event. Refunds run asynchronously keyed byreservation_id. - Outbox pattern: all side effects (emails, refunds, index updates) are written to an outbox table inside the transaction; a relay publishes to Kafka, so there are no dual writes.
6. Search architecture
Pipeline: Inventory DB → CDC (Debezium) → Kafka → {Availability Cache, Elasticsearch indexer}.
Elasticsearch holds hotel docs: geo_point, stars, amenities, review score, coarse min_price. It answers geo, filter, and ranking queries but not per-night availability. An availability cache (Redis) keyed by (hotel_id, date) holds remaining counts, refreshed by CDC and by the booking service after each write. Search merges ES filter matches with cached availability to produce from_price and available_room_types.
Handling staleness: accept a small window (seconds) of stale search — worst case a user clicks a sold-out room and gets a clean "no longer available" at the quotes/hold step. Long-tail hotels with little traffic hit a read-through availability service rather than sitting uncached. Kafka decouples churn: a spike of booking writes doesn't stall the indexer because each consumer scales independently and can lag briefly.
7. Key trade-offs and pitfalls
- Correctness lives in the write path. Never let the read path (cache, ES) be authoritative for a booking decision.
- Don't skip the idempotency table inside the write transaction — that's the #1 source of double bookings in interviews.
- Watch the hold sweeper: a naive periodic DELETE can race with an in-flight confirm; always use compare-and-set transitions.
- PCI/PII segregation is a requirement, not a nice-to-have; tokenize and vault.
- Clock skew: derive
hold_expires_atfrom the DB clock, not the app server's.