Room-Level Hotel Booking Without Overlapping Stays
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a global room-level hotel booking platform where travelers browse available rooms at a property for a chosen check-in and check-out window and reserve an exact physical room (for instance, Room 804 rather than a generic room tier). Every multi-night reservation must succeed or fail as a single atomic unit, and two guests must never acquire overlapping stays on the same physical room—even when thousands of requests race simultaneously.
Your design should serve two sharply asymmetric workloads under the following operational constraints:
- Read workload (
100,000+queries/sec): Shoppers filter properties and inspect open rooms across date ranges. Search responses may reflect eventual consistency (lagging behind live bookings by roughly a second), and the search path must remain fast and available even when the booking or payment path slows down. - Write workload (
~1,000bookings/sec): Checkout operations require strict consistency so conflicting date ranges on the same room are impossible, while safely recovering inventory whenever downstream card payments decline or time out.
Scope & Expectations
- APIs & checkout flow: Define REST endpoints and request/response contracts for browsing room availability and completing an idempotent room reservation.
- Schema & date-interval representation: Model properties, physical rooms, and stay intervals so overlapping date ranges are detected efficiently and accurately.
- Concurrency & payment failure recovery: Explain how concurrent booking attempts on the same room are serialized or rejected without holding locks across slow external payment calls, and how failed or abandoned checkouts release inventory.
- Read scaling & fault isolation: Show how the architecture serves
100,000+searches per second and insulates search latency from booking database or payment gateway degradation.
Step-by-step walkthrough
Clarify requirements and scope
A room-level hotel reservation system has two completely different workloads: a search path that handles massive read traffic (
100,000+ req/s) and tolerates a second or two of staleness, and a booking path that handles moderate writes (1,000 req/s) where double-booking the same physical room is strictly forbidden. Separating those two paths from the start keeps search blazingly fast even if checkout slows down, while letting the database enforce rock-solid transactional guarantees on bookings.Functional requirements
- Search availability: Query available hotels and specific rooms (for example, Room
804, Queen Harbor View) for a date range and guest count. - Room-level reservation: Reserve a specific physical room—not just a generic room category—for
[check_in, check_out). - Atomic multi-night booking: A reservation is atomic (all-or-nothing): the guest gets every requested night for that room, or none of them.
- Checkout and cancellation: Hold a room briefly during payment, confirm once payment succeeds, or release/cancel cleanly.
Non-functional requirements
- Zero double-booking (strong consistency): Under any concurrency, network retry, or service crash, two active reservations for the same
room_idmay never share a night (strong consistency means every booking write sees and enforces the exact latest committed state). - High-throughput search (eventual consistency): Serve
100,000+ searches/sat< 100 msp95; eventual consistency (search views lagging bookings by ~1 second) is acceptable because the booking step re-verifies availability authoritatively. - Fault isolation: Search must stay fast and available even if the reservation service or payment gateway experiences high latency or an outage.
Explicit assumptions
- Inventory size: 100,000 hotels × ~100 rooms each = 10,000,000 physical rooms worldwide.
- Booking window: Up to 365 days in advance; max 30 nights per stay; zero intentional overbooking.
- Half-open date intervals: Stays use
[check_in, check_out)—checking in Oct 12 and checking out Oct 15 occupies the nights of Oct 12, 13, and 14, so another guest can check in on Oct 15 without conflict. - External payment gateway: Supports idempotency keys (unique tokens ensuring retries never charge twice) and separate authorization (freezing funds) vs. capture (settling funds).
- Search availability: Query available hotels and specific rooms (for example, Room
Back-of-the-envelope numbers
1. Global inventory footprint - Physical rooms: 100,000 hotels x 100 rooms = 10,000,000 rooms - Rolling calendar bitmap: 512 bits (8 x 64-bit integers = 64 bytes) per room - Entire world's availability: 10,000,000 x 64 B = 640 MB! -> Fits completely in RAM on EVERY search server! 2. Booking write load - Peak booking rate: 1,000 holds/s (assume ~100/s daily average -> ~2.3M confirmed stays/day) - Transitions per booking: HELD -> PAYMENT_PENDING -> CONFIRMED/RELEASED (~3 writes/booking) - Peak database writes: ~3,000 small ACID transactions/s total - Sharded across 16 DB shards (by hotel_id): 3,000 / 16 ≈ 190 write tx/s per shard (very light!) - Storage growth: ~8.6M hold rows/day x 300 B ≈ 2.6 GB/day (~0.95 TB/year before archiving) 3. Search read load - Peak search rate: 100,000 searches/s (100:1 read-to-write ratio) - Candidate rooms per query: ~50 hotels x 100 rooms = 5,000 rooms checked via bitwise AND - Fleet sizing: At ~4,000 searches/s per 8-core node -> ~25-30 stateless search nodes - Live availability updates: ~3,000 state changes/s streamed to each search node (< 1% CPU)Key architectural conclusions from the math: - Search must never query the booking database. Sending 100,000 range queries/s to transactional shards would melt them; meanwhile, 640 MB of room bitmaps fits inside every search node's memory with zero network hops. - Shard bookings by
hotel_id. Every room reservation (and even a multi-room booking within one hotel) lands on a single PostgreSQL shard at a calm ~190 writes/s.API design
1. Search & Room-Picker APIs (served by Search Fleet; never touches Booking DB) GET /v1/search?area=tokyo-bay&check_in=2026-10-12&check_out=2026-10-15&guests=2&cursor=... -> 200 { "as_of": "2026-09-20T14:00:01Z", "hotels": [ { "hotel_id": 410, "name": "...", "min_total_cents": 48000, "available_rooms_hint": 6 } ] } GET /v1/hotels/{hotel_id}/availability?check_in=2026-10-12&check_out=2026-10-15&guests=2 -> 200 { "as_of": "...", "rooms": [ { "room_id": 804, "room_number": "804", "type": "QUEEN_HARBOR", "total_cents": 48000, "quote_id": "q_52c..." } ] } 2. Two-Phase Booking APIs (served by Reservation Service) POST /v1/holds Headers: Authorization, Idempotency-Key: <client-uuid> Body: { "hotel_id": 410, "room_id": 804, "check_in": "2026-10-12", "check_out": "2026-10-15", "quote_id": "q_52c..." } -> 201 { "reservation_id": "res_7b...", "status": "HELD", "hold_expires_at": "2026-09-20T14:10:02Z", "total_cents": 48000 } -> 409 { "error": "ROOM_UNAVAILABLE", "alternatives": [809, 912] } -> 422 Invalid date range (check_out <= check_in, past date, or > 30 nights) POST /v1/reservations/{reservation_id}/confirm Headers: Authorization, Idempotency-Key: <client-uuid> Body: { "payment_method_token": "pm_tok_..." } -> 200 { "status": "CONFIRMED", "confirmation_code": "HTL-4M8P" } -> 202 { "status": "PAYMENT_PENDING" } // Gateway timed out; client polls GET -> 402 { "error": "PAYMENT_DECLINED" } // Card declined; room hold released immediately -> 410 { "error": "HOLD_EXPIRED" } // User waited > 10 minutes before clicking Pay DELETE /v1/holds/{reservation_id} // User leaves checkout early -> releases room POST /v1/reservations/{reservation_id}/cancel GET /v1/reservations/{reservation_id}Why this two-step contract works so well: - Hold first, pay second: Locking the room in milliseconds via
POST /v1/holdsgives the guest a guaranteed 10-minute TTL (Time-To-Live countdown) to type card details without keeping a database lock open during slow external payment calls. - Helpful409responses: Because search is ~1 second eventually consistent, two users can occasionally click Room804together; returning freealternativesturns a race loss into a one-click recovery. - Explicit202 PAYMENT_PENDING: Never guess whether a timed-out card call succeeded or failed.Data model and half-open intervals
Why model stays as half-open intervals
[check_in, check_out)? Because hotel guests occupy nights, and changeover happens on the morning between stays:Guest A: check_in = Oct 12, check_out = Oct 15 -> [12, 15) occupies nights of Oct 12, 13, 14 Guest B: check_in = Oct 15, check_out = Oct 17 -> [15, 17) occupies nights of Oct 15, 16 Timeline: Oct 12 Oct 13 Oct 14 Oct 15 Oct 16 Oct 17 [========== Guest A (3 nights) =========)[=== Guest B (2 nights) ===) ^ Zero overlap on Oct 15! Two half-open ranges [a1, a2) and [b1, b2) overlap if and only if: a1 < b2 AND b1 < a2.If you stored closed intervals
[Oct 12, Oct 15], Oct 15 would collide with[Oct 15, Oct 17]and block every back-to-back booking!Each of the 16 PostgreSQL reservation shards stores hotels hashed/mapped to that shard:
CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE rooms ( hotel_id bigint NOT NULL, room_id bigint NOT NULL, room_number text NOT NULL, room_type text NOT NULL, in_service bool NOT NULL DEFAULT true, version bigint NOT NULL DEFAULT 1, -- available if using optimistic locking PRIMARY KEY (hotel_id, room_id) ); CREATE TABLE reservations ( reservation_id uuid PRIMARY KEY, hotel_id bigint NOT NULL, room_id bigint NOT NULL, stay daterange NOT NULL, -- stored natively by Postgres as [check_in, check_out) status text NOT NULL, -- HELD, PAYMENT_PENDING, CONFIRMED, BLOCKED, -- EXPIRED, RELEASED, CANCELLED hold_expires_at timestamptz, guest_id bigint NOT NULL, total_cents bigint NOT NULL, currency char(3) NOT NULL, idempotency_key text NOT NULL UNIQUE, payment_ref text, version int NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), -- Ensures room_id actually belongs to hotel_id on this shard: FOREIGN KEY (hotel_id, room_id) REFERENCES rooms (hotel_id, room_id), -- Database-enforced no-overlap rule across all active reservation states: CONSTRAINT no_double_booking EXCLUDE USING gist ( room_id WITH =, stay WITH && ) WHERE (status IN ('HELD', 'PAYMENT_PENDING', 'CONFIRMED', 'BLOCKED')) ); CREATE INDEX idx_holds_expiry ON reservations (hold_expires_at) WHERE status = 'HELD';What is
EXCLUDE USING gist? A GiST (Generalized Search Tree) index is a balanced spatial/range tree inside PostgreSQL (the on-disk cousin of an interval tree) that indexes date intervals and tests the overlap operator&&inO(log N)time. The partialEXCLUDEconstraint declares that no two active rows may have the sameroom_id(=) AND overlappingstay(&&). As soon as a hold flips toEXPIRED,RELEASED, orCANCELLED, it drops out of the partial index and frees those nights instantly.Portable alternative (for MySQL, DynamoDB, or CockroachDB): Create a
room_nights (room_id, night, reservation_id, PRIMARY KEY (room_id, night))table and insert 1 row per night in ascending date order inside the hold transaction (3rows for a 3-night stay), deleting them on release/expiry. Any overlap triggers a standard primary-key violation!High-level architecture
Web / Mobile Clients & Partner APIs | [ CDN + Edge API Gateway ] /v1/search | | /v1/holds, /confirm, /cancel (bulkhead A)| | (bulkhead B + per-room rate limit) v v +-------------------------------+ +-------------------------------+ | Stateless Search Fleet (~30x) | | Reservation Service |---> [Payment Gateway] | In RAM on EVERY node: | | (stateless, routes hotel_id) | ^ | - Hotel & room catalog | +---------------+---------------+ | | - 10M x 64B room bitmaps | | | | - Rate & quote cache | v | +-------------------------------+ +-------------------------------+ +-------+--------+ ^ | Reservations DB (16 Shards) | | Payment | | | Postgres Primary + Sync |<---| Resolver & | | | Standby per shard (AZ 1 + 2) | | Hold Sweeper | | +---------------+---------------+ +----------------+ | | CDC (logical WAL stream) | v +-------------------- [ Kafka: room-availability-events ] (partitioned by key = room_id) | v [ Hotel PMS Sync & Notifications ]Notice the strict CQRS (Command Query Responsibility Segregation—splitting read storage from write storage) boundary: - Reads never touch the database: Search nodes answer 100% from local RAM. - Writes never depend on search: Sharded PostgreSQL enforces room-level exclusivity directly. - CDC (Change Data Capture) reads committed database WAL (Write-Ahead Log) records and streams availability changes through Kafka (
key = room_id) so every search node updates its in-memory bitmap within ~1 second.Deep dive 1: Preventing double booking under concurrency
Why does naive application code double-book? Under PostgreSQL's default
READ COMMITTEDisolation, if Maya and Liam both runSELECT COUNT(*) FROM reservations WHERE room_id = 804 AND stay && '[2026-10-12, 2026-10-15)'at the same millisecond, neither transaction has committed yet—both queries return0, and bothINSERTs succeed!Let's compare the four standard concurrency controls:
Strategy How it works Trade-off 1. Pessimistic row lock ( SELECT FOR UPDATE)Lock parent row SELECT in_service FROM rooms WHERE hotel_id = :h AND room_id = :r FOR UPDATE, check overlap, thenINSERTSimple and works in every SQL DB, but serializes non-overlapping bookings on Room 804 (Oct 12 blocks a May booking) and fails if any code path forgets FOR UPDATE2. Optimistic locking ( versioncolumn)Read rooms.version = v, check overlap,INSERT, thenUPDATE rooms SET version = v + 1 WHERE room_id = :r AND version = :v(0 rows -> rollback)Zero lock wait when conflicts are rare, but non-overlapping dates on the same room still conflict on rooms.version, and requires discipline across all writers3. GiST exclusion constraint (Chosen) INSERTdirectly; Postgres GiST index locks and rejects only overlapping active date ranges onroom_idEnforced inside the schema for every service/script; non-overlapping dates run in parallel; PostgreSQL-specific 4. room_nightsPK tableINSERTone(room_id, night)row per night sorted by dateEnforced in schema on any SQL DB; writes/deletes ~3x more rows per stay Our exact Hold transaction:
BEGIN; -- 1. Verify the room exists at this hotel and is currently in service (shared read check). SELECT in_service FROM rooms WHERE hotel_id = :hotel_id AND room_id = :room_id; -- (If missing or in_service = false -> ROLLBACK and return 409 ROOM_UNAVAILABLE) -- 2. Lazily expire any stale HELD row overlapping these dates so we never depend on the sweeper! UPDATE reservations SET status = 'EXPIRED', version = version + 1, updated_at = now() WHERE room_id = :room_id AND stay && daterange(:check_in, :check_out, '[)') AND status = 'HELD' AND hold_expires_at <= now(); -- 3. Insert the 10-minute hold; no_double_booking constraint blocks any concurrent overlap. INSERT INTO reservations (reservation_id, hotel_id, room_id, stay, status, hold_expires_at, guest_id, total_cents, currency, idempotency_key) VALUES (:res_id, :hotel_id, :room_id, daterange(:check_in, :check_out, '[)'), 'HELD', now() + interval '10 minutes', :guest_id, :total_cents, :currency, :idem_key); COMMIT;Let's trace a simultaneous collision on Room
804(t = 14:00:02.100):Time (ms) Maya: [Oct 12, Oct 15) Liam: [Oct 14, Oct 16) (overlaps Oct 14!) --------- ----------------------------------------- ----------------------------------------- .100 BEGIN; checks room 804; no stale holds BEGIN; checks room 804; no stale holds .101 INSERT [12, 15) -> acquires GiST index INSERT [14, 16) -> sees uncommitted overlap lock on Room 804's [12, 15) entry in GiST index -> BLOCKS waiting on Maya! .103 COMMIT succeeds -> returns 201 HELD Unblocks -> sees committed overlap -> Postgres raises SQLSTATE 23P01! .104 Catches 23P01 -> returns 409 + alternativesNotice that Maya holds the lock for ~2–3 milliseconds (zero external network calls inside
BEGIN ... COMMIT!). If Maya instead loses her mobile signal and retries with the sameIdempotency-Key, Postgres raisesSQLSTATE 23505onidempotency_key, and our service returns her existing201 HELDresponse.Deep dive 2: Two-phase hold, payment failures, and recovery
What happens if the guest clicks "Pay", the card network hangs for 15 seconds, and their 10-minute hold expires right in the middle of charging the card? If another guest grabs the room during that gap, you have double-sold or charged someone for nothing!
We close that race with an explicit intermediate state—
PAYMENT_PENDING—before calling the payment provider:[HELD (10m TTL)] ---confirm()---> [PAYMENT_PENDING (30m cap)] ---auth OK---> [CONFIRMED] | | |--TTL <= now()--> [EXPIRED] |--card declined-------------> [RELEASED] |--DELETE /holds-> [RELEASED] |--timeout -> Resolver checks: found auth -> [CONFIRMED] 30m cap hit -> void auth -> [RELEASED]Step-by-step confirmation workflow: 1. Freeze the hold in Postgres (< 3 ms):
sql UPDATE reservations SET status = 'PAYMENT_PENDING', hold_expires_at = now() + interval '30 minutes', version = version + 1, updated_at = now() WHERE reservation_id = :res_id AND status = 'HELD' AND hold_expires_at > now() RETURNING total_cents, currency;- If0rows update: check currentstatus. IfEXPIRED, return410 HOLD_EXPIREDwithout ever touching the guest's card. If alreadyPAYMENT_PENDINGorCONFIRMED(a client retry!), return current status. - Oncestatus = 'PAYMENT_PENDING', the hold sweeper never touches this row; the room is safely locked while we talk to the bank. 2. Authorize payment outside the DB transaction: Call the payment gateway withIdempotency-Key: <reservation_id>. We authorize (freeze funds) first and capture according to cancellation policy, because voiding an uncaptured authorization on error is instant and fee-free. 3. Record the result: - Authorized:UPDATE reservations SET status = 'CONFIRMED', payment_ref = :ref WHERE reservation_id = :res_id AND status = 'PAYMENT_PENDING'->200 OK. - Card declined:UPDATE ... SET status = 'RELEASED'->402 PAYMENT_DECLINED(room immediately bookable again!). - Network timeout /5xx/ service crash: Leave row inPAYMENT_PENDINGand return202 Acceptedso the client pollsGET /v1/reservations/{id}.Background recovery jobs: - Payment Resolver (runs every 30s on
PAYMENT_PENDINGrows older than 60s): Queries the payment gateway byIdempotency-Key = reservation_id. If authorized ->CONFIRMED; if declined ->RELEASED; if unknown -> retries with the exact samereservation_idkey. If the gateway stays unreachable past the 30-minute cap, the resolver sends an idempotent void forreservation_idand transitions the row toRELEASED. - Hold Sweeper (runs every 30s to clean abandoned tabs for search):sql UPDATE reservations SET status = 'EXPIRED', version = version + 1, updated_at = now() WHERE status = 'HELD' AND hold_expires_at <= now() AND reservation_id IN ( SELECT reservation_id FROM reservations WHERE status = 'HELD' AND hold_expires_at <= now() LIMIT 1000 FOR UPDATE SKIP LOCKED );Repeatingstatus = 'HELD'in the outerWHEREis critical: underREAD COMMITTED, if a concurrentconfirmjust flipped a row toPAYMENT_PENDING, PostgreSQL re-evaluates only the outerWHEREclause!Deep dive 3: Serving 100k+ searches/s and isolating failures
1. Fixed-epoch circular bitmaps in RAM. Shifting 10,000,000 bitmaps every midnight UTC is messy because hotels span 24 time zones and midnight shifts race with live Kafka updates. Instead, we map every calendar
dateto a deterministic bit slot0..511relative to a fixed epoch (2026-01-01) modulo512(comfortably covering a 365-day future horizon plus recent past days):from datetime import date EPOCH = date(2026, 1, 1) RING_BITS = 512 # Stored in production as eight 64-bit unsigned integers (64 bytes/room) def stay_mask(check_in: date, check_out: date) -> int: """Build a 512-bit mask with 1s on each night in [check_in, check_out).""" nights = (check_out - check_in).days start_bit = (check_in - EPOCH).days % RING_BITS # Contiguous stay when it does not wrap around slot 511 -> 0: if start_bit + nights <= RING_BITS: return ((1 << nights) - 1) << start_bit # Wrap-around across the 512-day boundary splits into high bits + low bits: first_leg = RING_BITS - start_bit second_leg = nights - first_leg return (((1 << first_leg) - 1) << start_bit) | ((1 << second_leg) - 1) def is_room_free(room_bitmap: int, mask: int) -> bool: """Return True in O(1) CPU instructions if zero nights in mask are occupied.""" return (room_bitmap & mask) == 02. Ordered, idempotent CDC updates. Each database shard streams committed
reservationsrow changes (before_status,after_status,room_id,stay,lsn) to Kafka partitioned byroom_id. Because all events for Room804land in the same Kafka partition in WAL commit order: - Transition into{HELD, PAYMENT_PENDING, CONFIRMED, BLOCKED}-> bitwise OR (bitmap |= mask). - Transition out to{EXPIRED, RELEASED, CANCELLED}-> bitwise clear (bitmap &= ~mask), which is completely safe because our DB exclusion constraint guarantees no other active reservation shares those bits, and any subsequent hold arrives later in the same partition! - Booting a new search node loads a periodic S3 bitmap snapshot (written every 5 minutes alongside its Kafka partition offsets) and replays a few minutes of Kafka events before joining the load balancer.3. High-availability fault isolation: - Zero synchronous coupling:
/v1/searchnever calls the Reservation Service, Payment Gateway, or Postgres shards. If all 16 booking shards freeze, search still answers in< 20 msfrom RAM. - Bulkheads (isolated resource pools—like watertight ship compartments): Separate Kubernetes deployments, thread pools, and API gateway rate limiters ensure backed-up/v1/confirmconnections cannot starve/v1/searchworkers. - Circuit breakers on/v1/holdsand/v1/confirm: If one shard degrades, the gateway trips open for only that shard's hotels (503 Try again shortly) while the other 15/16 of hotels book normally and 100% of search stays up.Scaling, bottlenecks, and trade-off summary
- Hot-hotel flash sales: A celebrity concert or New Year's Eve deal can hurl 20,000
/v1/holdsattempts/s at one hotel's room. The API gateway enforces per-hotel and per-room token-bucket rate limits, shedding excess duplicate clicks with fast409s + alternative rooms before they touch the shard. - Keeping the GiST index compact: Do not partition
reservationsby month—PostgreSQL exclusion constraints cannot enforce&&range overlap across separate table partitions! Instead, run a nightly archiver moving reservations withupper(stay) < current_date - 90intoreservations_archive; past dates can never overlap future bookings, keeping the active GiST index tiny and RAM-resident. - Shard failover & disaster recovery: Each shard replicates synchronously to a standby in a second Availability Zone (RPO = 0, zero lost holds, ~30s failover) and asynchronously to a second region.
Summary of core trade-offs - Postgres GiST exclusion constraint vs. application row/version locks: Couples the write store to PostgreSQL (or a
room_nightsPK table) in exchange for making double-booking mathematically impossible across all services and scripts while allowing non-overlapping dates on the same room to commit in parallel. - Two-phase Hold +PAYMENT_PENDINGvs. single-call checkout: Adds a state machine, TTL sweeper, and payment resolver in exchange for millisecond database lock times and zero risk of charging a card for an expired room. - Replicated 640 MB in-memory bitmaps vs. querying the booking DB: Accepts ~1 second of search staleness and a CDC pipeline in exchange for100,000+ searches/sand total immunity from reservation database slowdowns.- Hot-hotel flash sales: A celebrity concert or New Year's Eve deal can hurl 20,000
Intuition & how it works
Picture a busy hotel chain with two completely separate boards: out in the public lobby hangs a giant illuminated wall calendar (our in-memory Search Fleet) where 100,000 travelers per second glance up simultaneously to see which specific rooms look free, while behind the front desk sits a locked ledger book (our sharded PostgreSQL booking database) where the clerk records actual room assignments. When a guest picks Room 804 for Oct 12–15, the clerk checks and pencils their name across the boxes for the nights of Oct 12, 13, and 14 in one atomic pen stroke with a 10-minute timer (temporary hold), freezes that timer once the guest hands over their credit card (PAYMENT_PENDING), writes it in ink once the bank approves (CONFIRMED), and sends a runner (CDC—Change Data Capture) to flip those three lights on the lobby wall calendar a second later.
A straightforward single-database design fails immediately for three reasons. First, letting 100,000+ search requests per second run date-overlap SQL queries against the booking database crushes the database and brings both search and checkout down together. Second, checking availability (SELECT) and inserting a reservation (INSERT) in two separate application steps allows two simultaneous shoppers to both read "Room 804 is free" and double-book the exact same bed. Third, charging a credit card inside a database transaction holds locks for 2–5 seconds per call—stalling concurrent bookings—whereas charging outside a transaction without freezing the hold lets a 10-minute timer expire mid-charge and sell the room to someone else!
Concrete walkthrough of a concurrent booking race on Room 804 ([2026-10-12, 2026-10-15)):
1. Fast in-memory search (t = 0.0s): Maya and Liam both search Tokyo Bay for check-in Oct 12, check-out Oct 15 (a half-open interval [12, 15) covering the 3 nights of Oct 12, 13, and 14). Any search server checks Room 804's 64-byte bitmap (a compact array of 0/1 bits, one bit per calendar night) in a single CPU AND instruction and shows Room 804 available to both users.
2. Simultaneous hold (t = 1.2s): Both click "Book Room 804" (POST /v1/holds with client idempotency keys—unique tokens so retries never create duplicate holds). Maya's INSERT arrives 1 ms earlier on Property 410's PostgreSQL shard and acquires the GiST exclusion constraint lock for (room_id = 804, stay = [12, 15)), committing in 2 ms (201 HELD, expires in 10 minutes). Liam's overlapping INSERT immediately hits SQLSTATE 23P01 (exclusion violation) and returns 409 ROOM_UNAVAILABLE with nearby free rooms 809 and 912.
3. Async search update (t = 2.0s): PostgreSQL's commit log streams 804 -> HELD [12, 15) through Kafka (key = 804) to every search server, setting those three night bits to 1 so future searchers no longer see Room 804.
4. Safe payment confirmation (t = 180s): Maya submits her card (POST /confirm). First, a 2 ms SQL update flips her row from HELD to PAYMENT_PENDING (30-minute safety cap so the hold sweeper cannot expire it mid-payment). Second, the service authorizes her card outside the database using reservation_id as the payment idempotency key. Third, it marks the row CONFIRMED.
Key trade-offs
- Database exclusion constraint (
EXCLUDE USING gist) vs.SELECT FOR UPDATEvs. optimisticversionlocking. Locking the parentroomsrow (SELECT ... FOR UPDATE) or bumpingrooms.version(optimistic concurrency—checking at commit time that a version counter did not change) works on any SQL database, but causes an October booking on Room804to conflict with an unrelated May booking on Room804, and breaks if any new script forgets to lockrooms. A PostgreSQL GiST exclusion constraint (or a portableroom_nights(room_id, night)primary-key table) enforces non-overlap inside the schema itself and allows non-overlapping stays on the same room to commit in parallel, at the cost of either tying the write store to PostgreSQL or writing one row per night. - Two-phase Hold + Confirm vs. single-step reserve-and-pay. A single endpoint feels simpler on a whiteboard, but forces you either to hold database locks during multi-second bank calls or to authorize cards before knowing whether the room is free. Splitting into a 10-minute
HELDphase, aPAYMENT_PENDINGfreeze, andCONFIRMEDkeeps database transactions under 3 ms and gives guests calm checkout time, at the cost of operating a hold sweeper and a background payment resolver. - 10-minute hold TTL length. A longer hold (15–20 minutes) helps slow typists finish payment, but lets window-shoppers lock up popular harbor-view suites during peak hours; a shorter hold (3–5 minutes) recycles abandoned rooms fast but frustrates legitimate guests fetching a credit card. Ten minutes for typing plus a 30-minute cap only after card submission balances conversion against inventory availability.
- Replicated 640 MB bitmaps on every search node vs. querying read replicas. Read replicas of the booking database still pay B-tree/GiST range-scan costs across thousands of rooms per query and share replication resources with the write store. Keeping a 512-day circular bitmap per room (64 bytes × 10M rooms = 640 MB) in RAM on all ~30 search nodes answers
100,000+ searches/swith zero fan-out and total fault isolation, in exchange for ~1 second of eventual consistency lag and maintaining a CDC stream. - Bitmaps vs. in-memory interval trees. An interval tree (a binary search tree storing
[start, end)intervals for fast overlap queries) handles arbitrary millisecond timestamps or multi-year horizons well, whereas hotel stays use discrete whole nights over a bounded 1-year window—making a 64-byte bitmap faster (O(1)bitwise AND regardless of booking count) and far smaller in memory. - Sharding by
hotel_idvs.room_idorguest_id. Sharding byhotel_idkeeps single-room and multi-room bookings at one hotel inside one local shard transaction; a multi-hotel vacation package requires an application saga (a sequence of single-hotel holds with compensating releases if one leg fails).
Common mistakes
- Storing closed intervals
[check_in, check_out]instead of half-open[check_in, check_out): Treatingcheck_outas an occupied day makes a guest checking out Oct 15 collide with the next guest checking in Oct 15. - Application-level "SELECT count of overlaps, then INSERT" without a lock or constraint: Under
READ COMMITTEDisolation, two concurrent transactions do not see each other's uncommittedINSERT, guaranteeing double-bookings under load. - Trusting the search cache during booking: Treating the in-memory bitmap as authoritative rather than a display hint double-books rooms during the 1-second CDC propagation window.
- Calling the payment gateway inside
BEGIN ... COMMIT: Holding database locks across slow external HTTP calls exhausts connection pools and stalls shard throughput during bank slowdowns. - Allowing holds to expire while payment is in flight: Without atomically flipping
HELD -> PAYMENT_PENDINGbefore charging the card (and repeatingWHERE status = 'HELD'in the outer clause of the hold sweeper), a 10-minute hold can expire mid-charge and sell the room to a second guest. - Retrying timed-out payment calls with a brand-new idempotency key: Turns a harmless network timeout into charging the guest's credit card twice.
- Publishing CDC room events without partitioning Kafka by
room_id: Out-of-order delivery (Hold Bprocessed beforeExpire Afor the same nights) clearsHold B's bits in search memory and advertises a booked room as free. - Partitioning the live
reservationstable by date: PostgreSQL exclusion constraints cannot check&&date-range overlap across multiple table partitions; keep active stays in one table per shard and archive stays ended> 90days ago instead.
Follow-up questions
- What changes are needed to let a corporate organizer atomically reserve a block of 50 rooms in a single request? Because we shard by
hotel_id, all 50 rooms at one hotel live on the same PostgreSQL shard and can be held atomically in one local transaction. Crucially, the transaction must insert holds in strictly ascendingroom_idorder so two concurrent group bookings wanting overlapping room sets wait cleanly instead of deadlocking. Because any single constraint error aborts a PostgreSQL transaction unless caught, we wrap each room'sINSERTin a SQLSAVEPOINT: if Room804was just grabbed (SQLSTATE 23P01), weROLLBACK TO SAVEPOINT, substitute a spare candidate room of the same type from the search snapshot, and continue—rolling back the entire transaction only if fewer than 50 rooms exist. Finally, real hotel group sales often hold a contract block first (for example,"50 generic Queen Harbor rooms") with a multi-day TTL and assign room numbers closer to check-in, which we support by adding a(hotel_id, room_type, night)allotment counter alongside the room-level constraint. - Suppose peak search traffic overwhelms the storage tier—how would you structure caching and keep cached availability fresh as rooms get booked or released? In our architecture, search already does zero queries against the booking database because the 640 MB per-room circular bitmaps in each search node's RAM act as an event-invalidated replica updated within ~1 second via Kafka CDC (
key = room_id). To cut search CPU further during mega-events when millions search the exact same city and dates, we layer two short-lived caches in front: (1) a per-hotel availability cache keyed by(hotel_id, hotel_version, check_in, check_out, guests)wherehotel_versionincrements in local memory every time a CDC event arrives for that hotel—giving instant, race-free invalidation without delete storms—and (2) a CDN/edge result cache for popular(area, check_in, check_out, guests)first pages with a 15–30 second TTL, while static hotel photos and descriptions live on the CDN with immutable versioned URLs. BecausePOST /v1/holdsalways validates against PostgreSQL, a briefly cached search page never causes a double-booking. - How would you synchronize and reconcile state with each property's on-site front-desk system over a flaky hotel internet connection? Model the link between our cloud booking shard and the hotel's on-premise PMS (Property Management System—the front-desk software managing keycards, walk-ins, and room repairs) as two persisted, sequence-numbered event streams plus daily checksum reconciliation. Outbound cloud reservation changes write to a transactional outbox with a per-hotel monotonic
seq; our PMS connector delivers events in order and advances its cursor only after the PMS acknowledges (reservation_idmakes duplicate replays idempotent, and during a hotel internet outage the front desk operates from its local synced database). Inbound PMS events (walk-in guests, extended stays, plumbing repairs) insertstatus = 'BLOCKED'rows through our exact sameno_double_bookingexclusion constraint—and if an offline hotel walk-in took Room804during a network partition at the same time an online guest booked Room804, reconnecting hitsSQLSTATE 23P01and automatically opens a high-priority front-desk relocation task to move one guest to an equal or upgraded room before arrival, backed by a nightly 30-day per-room occupancy checksum diff to catch any silent drift.
Follow-up questions
- What changes are needed to let a corporate organizer atomically reserve a block of 50 rooms in a single request?
- Suppose peak search traffic overwhelms the storage tier—how would you structure caching and keep cached availability fresh as rooms get booked or released?
- How would you synchronize and reconcile state with each property's on-site front-desk system over a flaky hotel internet connection?
Similar questions
- Distributed Hotel Room Search and Booking Architecture
- Balancing PM Deadlines and AI Code Safety in Financial Systems
- Versioned Key-Value Store with Snapshots
- Time-Series Stock Quote Store
- Mutable Ticker Price Ledger
- Dynamic Interval Calendar with Overlap and Page Queries
More Lead Bank interview questions
- Time-Series Stock Quote Store Medium
- Dynamic Interval Calendar with Overlap and Page Queries Medium
- Mutable Ticker Price Ledger Medium Pro
- Distributed Hotel Room Search and Booking Architecture Medium Pro
- Balancing PM Deadlines and AI Code Safety in Financial Systems Medium Pro
- Versioned Key-Value Store with Snapshots Medium Pro
- Timestamped Key-Value Store and Mutual-Friend Recommendations Medium Pro