System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

Hotel Booking System

The guest is charged for the last room, then the booking worker crashes before confirmation.

● HardSystem 217 min1 prerequisite
My progress
Topic tools

Layout updated

Explore the design, then rehearse the decisions without looking.

Problem statement

Design a hotel booking service. Guests can search by location and dates, see a price, hold a room for the whole stay, pay, and receive or cancel a reservation.

Functional requirements

  • Search hotels and room types by location, dates, guests and filters.
  • Quote price and policy, hold all requested nights, take payment and return booking status.
  • Cancel reservations and track any refund separately.
  • Ingest hotel inventory updates and obtain partner confirmation for shared stock.

Non-functional requirements

  • Prevent overbooking of owned stock. For shared stock, require confirmation from the hotel's authority.
  • Target discovery under 300 ms and owned hold under 250 ms in the home region. Measure provider time separately.
  • Acknowledge inventory writes after synchronous multi- durability. Keep discovery available during booking outages and fail closed if ownership is uncertain.
  • Protect guest data and payments with authorization, tokenized payment details, signed callbacks and an audit trail.
  • Bound hold age, checkout extensions and retry load. Track unresolved payments, partner drift and recovery time.

Back-of-the-envelope estimates

Illustrative estimate
Assume 100,000 hotels, 5 room types per hotel and 365 days on sale. That is 182.5 million daily inventory rows if all stock is modeled locally.
10 million searches/day is about 116/s average and 1,160/s at 10× peak. Use OpenSearch and cached availability for discovery.
200,000 hold attempts/day is about 2.3/s average and 23/s at 10× peak. A hot hotel can concentrate those writes on a few date rows.
At 3 nights per stay, 200,000 successful holds would touch 600,000 inventory rows/day at creation. Confirmation or release adds up to 600,000 more row changes before cancellation and retries.
At 128 bytes of base data per daily row, 182.5 million rows are roughly 23 GB before indexes, , replicas and bloat. Measure actual storage and use rolling date partitions.

Entities

Entity / logical owner
Hotel + room type → catalog and inventory authority
Daily inventory → (hotel_id, room_type_id, stay_date)
Reservation + reservation_night → stay allocation and lifecycle
Quote → amount, currency, rules and validity
Request , provider operations, inbox and → recovery
Partner availability + feed cursor → advisory discovery stock

API design

Operation / inputResponse and retry contract
GET/v1/hotels?location&checkIn&checkOut&guests&cursor200 with paginated hotel/room-type results and availability as of a timestamp. Recheck at checkout.
POST/v1/quotes {hotelId, roomTypeId, checkIn, checkOut, guests, quantity}201 with quoteId, amount in minor units, currency, policy and validUntil. A quote does not allocate inventory.
POST/v1/holds {quoteId} + Idempotency-Key201 with reservationId and expiresAt for owned stock. For shared stock, 202 while partner hold or booking is pending. Return 409 for stale quote, sold-out dates or key reuse with a different request.
POST/v1/reservations/{id}/checkout {paymentMethodToken} + Idempotency-Key202 with current state. Verify ownership and quote, record one logical payment operation and dispatch it durably.
GET/v1/reservations/{id}200 with booking and payment states, deadline and confirmation reference when committed. Authorize access by customer.
POST/v1/reservations/{id}/cancel + Idempotency-Key202 when cancellation or compensation is pending. Return current state on retry. Enforce the stored cancellation policy.
POST/v1/webhooks/{provider}2xx after signed event validation and durable . Process callbacks asynchronously and reconcile missing or out-of-order events.

High-level design

How to draw this design

  1. Discover hotelsGuest, gateway, search index, and availability cache
  2. Hold room nightsReservation service and PostgreSQL inventory transactions
  3. Pay and confirmPayment orchestrator, provider, , and confirmation
  4. Reconcile and recoverExpiry workers, partner adapter, and hotel channel manager

Search approximate availability, hold every requested night atomically, then reconcile payment and confirm the stay.

State ownership
PostgreSQL owns the platform's inventory holds. The hotel confirms partner-controlled inventory.
Scale
Keep search traffic away from the transactions that contend on popular room nights.
Correctness
Hold all nights in one transaction. Confirm only if the exact hold remains eligible.
Failure and recovery
If payment succeeds after expiry, reconcile and compensate without reclaiming rooms sold elsewhere.
Hotel Booking & Reservation System · Discovery, booking and recovery
G guest->api 1. Search or book api->search 2. Discover hotels search->index 3. Filter catalog search->cache 4. Read stock hint api->booking 5. Hold / checkout / status booking->inventory 6. Allocate every night inventory->db 7. Lock dates + commit hold booking->db 8. Persist checkout intent db->relay 9. Read committed outbox relay->queue 10. Publish work / events queue->workers 11. Dispatch by provider workers->payment 12. Charge / reconcile payment->psp 13. Capture / query / refund psp->payment 14. Signed result / webhook payment->db 15. Confirm or compensate workers->partner 16. Reserve or reconcile partner->pms 17. Hold / book / look up pms->partner 18. Versioned stock updates partner->db 19. Record stock / confirmation workers->db 20. Expire / reclaim safely workers->cache 21. Refresh stock projection workers->index 22. Refresh searchable data queue->notify 23. Send confirmation guest Guest · Web / Mobile edge api Booking API Gateway edge search Hotel Search compute index OpenSearch Hotel Index state · durable cache Redis Availability Cache state · memory booking Reservation Service compute inventory Inventory Transactions compute db PostgreSQL · Booking Authority state · durable relay Outbox Relay compute queue → Kafka · Booking Work and Events messaging workers Expiry and Recovery Workers compute payment Payment Orchestrator compute psp External Payment Provider compute partner Hotel Partner Adapter compute pms Hotel PMS / Channel Manager compute notify Confirmation Delivery compute
  • Edge
  • Compute
  • State
  • Messaging

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.

Read the 23 flow steps

High-level design component walkthrough

Client / user

Guest · Web / Mobile

Search, hold, pay and check status.

Why, tradeoff and connected operations

Separate pending and confirmed outcomes in the UI.

Tradeoff: A client timeout can hide a successful commit.

Connected operations: Search or book

Gateway / routing

Booking API Gateway

Authorize guests and apply route-specific limits.

Why, tradeoff and connected operations

Use different budgets for discovery and scarce inventory.

Tradeoff: Admit fewer checkouts when hot dates are saturated.

Connected operations: Search or book; Discover hotels; Hold / checkout / status

Distributed database

OpenSearch Hotel Index

Index catalog, geography and searchable filters.

Why, tradeoff and connected operations

OpenSearch supports hotel-name, location and amenity filters. It serves discovery without scanning or locking room inventory. A search index suits browsing; PostgreSQL remains the booking authority.

Tradeoff: Index lag is normal.

Connected operations: Filter catalog; Refresh searchable data

Cache / in-memory index

Redis Availability Cache

Cache derived room-type/date availability and observation time.

Why, tradeoff and connected operations

Redis caches approximate availability by room type and date. It absorbs repeated browsing queries. Cached availability cannot authorize a booking; the transaction must verify every requested room night.

Tradeoff: Never authorize a hold from Redis.

Connected operations: Read stock hint; Refresh stock projection

Backend service

Reservation Service

Validate quotes, accept scoped keys and expose booking state.

Why, tradeoff and connected operations

One place to enforce lifecycle and response semantics.

Tradeoff: An unresolved external result is returned as pending.

Connected operations: Hold / checkout / status; Allocate every night; Persist checkout intent

Backend service

Inventory Transactions

Allocate, confirm or release a full stay on its hotel .

Why, tradeoff and connected operations

Short row locks protect the exact inventory being sold.

Tradeoff: A hot property may need a tighter admission budget.

Connected operations: Allocate every night; Lock dates + commit hold

Relational database

PostgreSQL · Booking Authority

Own room nights, holds, payment and partner operation identities, and the .

Why, tradeoff and connected operations

PostgreSQL atomically holds all room nights for a stay and stores checkout intent. Constraints and conditional updates stop conflicting reservations. fits multi-row booking correctness; search and caches remain derived views.

Tradeoff: Single-writer ownership limits where reservations can commit.

Connected operations: Lock dates + commit hold; Persist checkout intent; Read committed ; Confirm or compensate; Record stock / confirmation; Expire / reclaim safely

Backend service

Outbox Relay

Publish committed work and events to Kafka.

Why, tradeoff and connected operations

Recover the gap between database commit and broker publication.

Tradeoff: Publication can repeat if a relay crashes.

Connected operations: Read committed ; Publish work / events

Queue / event stream

Kafka · Booking Work and Events

Buffer checkout work and committed lifecycle events.

Why, tradeoff and connected operations

Rate-limit provider-specific workers and isolate notifications.

Tradeoff: Consumer delivery can repeat.

Connected operations: Publish work / events; Dispatch by provider; Send confirmation

Backend service

Expiry and Recovery Workers

Claim work, recover pending provider operations, expire holds and refresh projections.

Why, tradeoff and connected operations

Use durable database state to resume work after process or queue failures.

Tradeoff: Claims and generations fence local writes only.

Connected operations: Dispatch by provider; Charge / reconcile; Reserve or reconcile; Expire / reclaim safely; Refresh stock projection; Refresh searchable data

Backend service

Payment Orchestrator

Charge, reconcile and compensate using stable operation keys.

Why, tradeoff and connected operations

Persist identity before invoking external effects.

Tradeoff: An uncertain result may need delayed or manual recovery.

Connected operations: Charge / reconcile; Capture / query / refund; Signed result / webhook; Confirm or compensate

External dependency

External Payment Provider

Own capture, authorization, void and refund outcomes.

Why, tradeoff and connected operations

Resolve uncertain outcomes using provider evidence.

Tradeoff: and lookup capabilities depend on the provider contract.

Connected operations: Capture / query / refund; Signed result / webhook

Backend service

Hotel Partner Adapter

Sync inventory, confirm shared stock and reconcile ambiguous partner calls.

Why, tradeoff and connected operations

Normalize revision, availability and booking semantics per contract.

Tradeoff: A live partner outage can block checkout.

Connected operations: Reserve or reconcile; Hold / book / look up; Versioned stock updates; Record stock / confirmation

External dependency

Hotel PMS / Channel Manager

Own inventory sold across channels where no exclusive allotment exists.

Why, tradeoff and connected operations

Only the partner can confirm shared stock.

Tradeoff: A feed update is not booking confirmation.

Connected operations: Hold / book / look up; Versioned stock updates

Backend service

Confirmation Delivery

Notify guests from committed booking events.

Why, tradeoff and connected operations

Keep message delivery out of the booking transaction.

Tradeoff: Late email does not invalidate a reservation.

Connected operations: Send confirmation

Deep dives — decisions, failures and recovery

Open a deep dive to follow the steps, try an example and see how recovery works.

Deep dive 1

Allocate all nights in one transaction

Partition by hotel. In one PostgreSQL transaction, lock each room-type/date row in order, check the whole stay and create the hold with the client key.

Read the explanation and worked example
How it works

Use the property's civil dates and the half-open interval [check-in, check-out). Lock all DailyInventory rows in date order. Require every row and enough free units on every night. In one commit persist the scoped client key, reservation, exact night allocations, held counts and the record. No network call runs under these locks.

Walk through an example

A and B both see one deluxe room for December 10–13. A commits holds for December 10, 11 and 12. B waits, then sees zero on at least one row and returns unavailable without holding any night.

Failure and recovery

If the commit response is lost, retry the same request key and hash on the writer. If a transaction deadlocks, retry the whole local transaction with the same key and . The nightly capacity constraint catches inconsistent writers.

Why this helps

The stay is the unit of sale. A stale read and a per-night partial update can each leave a guest with a promise the system cannot honor.

What you give up

Popular hotel dates serialize on a few rows. Keep the critical section short and prefer admission control before splitting inventory into independently sellable pools.

Deep dive 2

Make hold expiry a state transition

Lock the reservation before its inventory rows. Confirmation, expiry and cancellation each verify the prior state and mutate its allocations in the same commit.

Read the explanation and worked example
How it works

A checkout transition creates the payment operation and optionally extends the hold once, up to a fixed final deadline. Both confirm and expiry lock the reservation and its allocation rows before evaluating the deadline with the database clock. Update counters and state in the same commit.

Walk through an example

At 10:05, the cleanup worker and a capture webhook arrive together. If verified payment gets the lock and passes the deadline guard first, the allocation becomes confirmed. Otherwise the hold expires and the payment saga handles any late capture.

Failure and recovery

Scan indexed due rows in bounded batches. A retried release finds the terminal state and does nothing. Monitor the oldest overdue hold. Conservatively count an expired but unprocessed hold against capacity until the release is committed.

Why this helps

A timer tells you when to try a release. Only the state transition determines who is allowed to change the counters.

What you give up

A long hold improves checkout completion but blocks other guests. A short hold releases inventory quickly and increases the chance that a late capture needs compensation.

Deep dive 3

Persist each payment operation before calling the provider

Use a durable saga with separate logical keys for charge, void and refund. Reconcile an ambiguous provider result before creating another logical operation.

Read the explanation and worked example
How it works

Record the payment key, amount, currency and dispatch entry before the first provider call. A verified webhook or status lookup can advance the operation, but cannot skip the booking's state guard. checks the same key and stores durable evidence. Compensations have their own stable keys.

Walk through an example

The provider captures P1 at 10:04 and the payment worker crashes. The replacement queries P1. With a valid hold it commits confirmation. With released inventory it leaves the booking expired and creates one refund operation against P1.

Failure and recovery

Treat timeout as unknown. Keep the unresolved operation after inventory expires. If the provider cannot deduplicate or look up the original operation, stop automatic retries and escalate. Use webhook signature verification, event and monotonic state updates.

Why this helps

The provider decides whether money moved. PostgreSQL decides whether the booking can be confirmed. Recovery joins those two facts using durable identity.

What you give up

A local transaction cannot include the payment provider. A guest may temporarily see a charge on an expired booking while a refund is verified.

Deep dive 4

Respect the hotel's inventory authority

Allocate owned allotments in PostgreSQL and confirm shared stock through the hotel partner. Cache availability only for discovery.

Read the explanation and worked example
How it works

Fetch partner snapshots and receive webhooks through adapters. Normalize hotel, room type, property-local dates and occupancy. Persist feed cursors and accept only newer comparable revisions. Shared stock lives in a separate discovery projection. Exclusive quotas are amended under local inventory locks.

Walk through an example

A hotel sold the last deluxe room on another channel. Our cached search still shows it. The partner rejects the live reservation, so the platform never marks it confirmed.

Failure and recovery

Recover feed gaps from a full and replay later revisions. When the booking times out, query the original operation or replay only under partner . If the partner confirmed but payment failed, track cancellation or escalate if cancellation is forbidden.

Why this helps

Hotels may sell the same room type on other channels. Local locking cannot reserve units that another system owns.

What you give up

Live confirmation adds partner latency and can make checkout temporarily unavailable. Exclusive allotments support fast checkout at the cost of reserving capacity with the hotel.

Deep dive 5

Protect the hot hotel without weakening the invariant

Scale discovery separately with OpenSearch and Redis. Bound checkout traffic per hotel and keep owned inventory transactions local to one .

Read the explanation and worked example
How it works

Publish committed inventory deltas through the to refresh cached availability. cache misses, keep stale results labeled and rate-limit hold attempts by customer and hot property. Apply short transaction timeouts, bounded retry budgets and cleanup priority for scarce dates.

Walk through an example

A flash sale sends thousands of guests to one property. Discovery stays fast, while admission control sends only a bounded number of contenders to the three hot inventory rows.

Failure and recovery

During cache loss, use bounded reads or hide availability estimates. During broker loss, keep the durable and throttle when age or backlog exceeds budget. Track per-property contention, expiry lag and cache freshness.

Why this helps

The average write rate hides the contention that determines and safety.

What you give up

Sharding by hotel isolates properties but cannot split one hot row. Independent quota buckets can spread writes, with stranded capacity and added .

Deep dive 6

Fence the booking owner before failover

Use a single fenced writer per hotel . Acknowledge commits with synchronous multi- durability and define a separate regional recovery policy.

Read the explanation and worked example
How it works

Routing can cache the current owner, but the protected database must enforce leadership. Within the durability domain, promote only a replica with the required committed history and fence the old primary. For regional takeover, establish a higher generation through a -backed and ensure the previous writer cannot commit. Workers also conditionally persist results against their claim generation. Provider covers calls that were already in flight.

Walk through an example

West stops responding after taking the last room. East can keep serving discovery. It must not allocate another unit until it can fence West and establish which holds, confirmations and operation identities survived.

Failure and recovery

Resume from known commit positions and compare provider evidence with durable booking state. With asynchronous regional replication, identify the recovery gap, close affected inventory and reconcile. For zero acknowledged booking loss across regional failure, require a cross-region commit . Exercise the recovery plan against explicit and targets.

Why this helps

Single writer, durable history and external-effect identity are separate conditions for safe recovery.

What you give up

Synchronous regional durability adds latency and may stop writes during partitions. Async DR improves local performance but cannot safely reopen inventory on the basis of alone.

Additional technical detail

Follow a three-night stay

A guest searches for a deluxe room from December 10 to 13. Check-out on the 13th consumes no inventory. Dates are local to the property, while hold deadlines are stored as absolute timestamps. The search result may say a room is available even after another guest starts checkout. The hold request is where we check availability and quote validity together.

NightSellableHeldConfirmedFree before request
December 10121101
December 11120111
December 1212291

The winning transaction adds one hold to each row. When payment is verified and the hold is still eligible, one transaction subtracts one held unit and adds one confirmed unit on each night. Free inventory stays at zero. The front desk can assign a physical room later. If the product guarantees a specific room or an uninterrupted stay in that exact room, room-type totals alone cannot enforce it.

PostgreSQL schema and constraints

Relation and keyFieldsWhat it protects
hotel, room_typeHotel ID, timezone, authority mode and owner . Room type key is hotel ID plus room type ID. Store occupancy and booking rules.One inventory authority per property or explicit allotment. Search projections copy descriptive fields.
daily_inventory PK (hotel_id, room_type_id, stay_date)Sellable quantity, held quantity, confirmed quantity, row version and sales-closed flag.Check that all counts are nonnegative and held + confirmed ≤ sellable. To cut supply below commitments, close sales and resolve the shortfall explicitly.
quote PK (quote_id)Property, room type, dates, occupancy, amount in minor units, currency, policy version and valid-until time.Bind checkout to exact terms. Persist the accepted amount and cancellation terms with the reservation.
reservation PK (reservation_id)Customer, hotel, authority mode, state, version, quote , hold deadline, final payment deadline and partner confirmation reference.One durable state machine. Index eligible hold states by deadline for bounded expiration scans.
reservation_night PK (reservation_id, stay_date)Hotel, room type, date and quantity. Reference the owned daily row for local allotment bookings.Record the exact allocation needed for confirmation, expiry and cancellation. Materialize one record per night.
request_idempotency PK (customer_id, operation, client_key)Canonical request hash, reservation ID and durable outcome or in-progress marker.Repeat requests return the same logical result. Reject key reuse with a different payload. Keep the identity through the supported retry horizon.
payment_operation and partner_operationUnique logical operation key, reservation ID, operation type, amount where applicable, external reference, status, attempt generation and next check time.Persist identity before calling a provider. Charge, void, refund, partner reserve and partner cancel have separate identities and retry lifecycles.
partner_availability PK (partner, hotel, room_type, stay_date)Absolute availability, source revision and observation time. Keep feed cursor and generation per partner scope.Search projection for partner-owned stock. A delayed sync cannot authorize a booking or overwrite owned allocations.
inbox and outboxInbox unique (source, event_id). unique event ID, aggregate version, payload and delivery state.Commit accepted incoming evidence and outgoing workflow work with local state. Relays and consumers can retry independently.

The allocation transaction

Keep one stay on one hotel . Acquire the record first, then the existing reservation row if the operation has one, and then daily inventory rows in ascending date order. Use the same lock order for confirm, cancel and expiry. Retry a deadlock or serialization failure using the same client key.

BEGIN
  claim (customer_id, "create_hold", client_key)
  if claim already exists:
    verify the request hash
    return the recorded result

  lock inventory rows for hotel, room type and [check_in, check_out)
    in ascending stay_date order, using SELECT ... FOR UPDATE
  verify every requested date exists and is open for sale
  verify sellable - held - confirmed >= quantity on every row
  validate occupancy and the server-side quote

  insert reservation in HELD and insert its reservation_night rows
  increment held by quantity on every night
  record reservation ID against the client key and insert the outbox event
COMMIT

Rollback the entire allocation if any night cannot be held. A check constraint is a backstop. The decisive operation is the locked validation and mutation of the complete date set. Missing dates mean no inventory. Do not derive a booking decision from an unlocked counter read or a Redis lock.

Reservation lifecycle and payment evidence

From → toGuard and durable changeWhat the guest sees
Request → HELDAll nights allocated in the same transaction, with a quote and short deadline.Hold ID, amount and expiration time.
HELD → PAYMENT_PENDINGLock reservation, check its deadline, record a stable payment operation and enqueue work. Allow at most one bounded checkout extension.Payment processing.
PAYMENT_PENDING → RECONCILIATION_REQUIREDExternal result is uncertain. Retain operation identity and deadline. Reconcile even if inventory later expires.Payment pending. A status refresh reuses the same booking.
PAYMENT_PENDING or RECONCILIATION_REQUIRED → CONFIRMEDRequire verified capture for the correct amount and currency, plus an eligible hold and current owner. Convert all held nights to confirmed and commit the confirmation event atomically.Confirmation number after the booking commit.
Active hold → FAILED or EXPIREDOn definite payment failure or a passed deadline, release all held nights exactly once. Unknown payment operations remain separately reconcilable.Booking failed or hold expired. Show payment status separately.
Expired hold with a late capture → refund pendingReservation stays expired. Record the verified capture and create one durable refund operation. If merely authorized, void instead. Reconcile ambiguous compensation and escalate aged cases.Booking expired. Refund pending, then refunded once verified.
CONFIRMED → CANCELLEDValidate policy, lock the reservation and its nights, decrement confirmed inventory once and create any refund intent in the same transaction.Cancellation confirmed, with refund tracked separately.
Partner request → PENDING_CONFIRMATIONFor partner-owned stock, persist a partner operation before submitting. Require partner confirmation and verified payment before showing a completed booking.Awaiting hotel confirmation or payment. Poll the same booking ID.

Expiry boundary. Both confirmation and expiry lock the reservation before changing inventory, then evaluate the current database clock and stored deadline while holding the relevant locks. A payment callback that arrives after expiry cannot reclaim a room. If cleanup falls behind, the counters conservatively withhold those units until the release transaction commits. Alert on the oldest overdue hold and prioritize cleanup for hot dates.

Payment boundary. The reference flow captures against a live hold and reconciles the gap before local confirmation. An authorization-first flow can reduce refunds, but capture can still fail after authorization. Keep that step visible in the state machine and reserve enough time to finish it. Never hold row locks while making external requests.

Two partner contracts

ContractAuthority and confirmation ruleSync and recovery
Exclusive platform allotmentThe hotel guarantees a separate quota. Platform PostgreSQL owns allocation within that quota. The hotel imports confirmed reservations through the feed.Apply versioned quota changes under the same inventory locks. Close sales and escalate cuts below current commitments. Never merge a stale partner into local held or confirmed counters.
Shared, partner-owned inventoryThe partner PMS can sell on other channels. Our feed is advisory. Require a partner reservation or firm hold before promising inventory. If the partner has no hold , authorize payment where supported, then book at the partner and capture.Authenticate and deduplicate changes, apply only a newer comparable revision, and reconcile gaps using a full plus subsequent events. After a booking timeout, look up the original partner reference. If outcome cannot be established, keep the booking pending and escalate before issuing a second create.

Do not use wall-clock ordering across unrelated partner systems. For unversioned feeds, serialize imports per property and reconcile snapshots under the partner's documented contract. Mark stale stock and suppress immediate checkout if live confirmation is unavailable. If partner booking succeeds but payment definitively fails, submit a tracked partner cancellation if permitted, or escalate the exception. If the platform charged but the partner definitively rejected, compensate the payment.

Failure timeline to rehearse aloud

  1. At 10:00, A holds the last room for three nights. The hold expires at 10:05. B reads an older search result but cannot acquire those nights.
  2. At 10:04, a worker records payment operation P1, then the provider captures the charge. The worker crashes before recording the result.
  3. Before 10:05, can verify P1 and convert A's hold to confirmed in one commit. After 10:05, confirmation fails the deadline check. The expiry worker releases A's allocation once, and B can hold it.
  4. When the late capture is discovered, queue a refund with its own stable key. Retrying the charge or the booking with a fresh identity would create a second effect. The confirmation email is sent only from the committed confirmation event.

Tradeoffs and alternatives

DecisionTradeoff / alternative and recovery implication
Allocate all nights in one transactionPopular hotel dates serialize on a few rows. Keep the critical section short and prefer admission control before splitting inventory into independently sellable pools.
Make hold expiry a state transitionA long hold improves checkout completion but blocks other guests. A short hold releases inventory quickly and increases the chance that a late capture needs compensation.
Persist each payment operation before calling the providerA local transaction cannot include the payment provider. A guest may temporarily see a charge on an expired booking while a refund is verified.
Respect the hotel's inventory authorityLive confirmation adds partner latency and can make checkout temporarily unavailable. Exclusive allotments support fast checkout at the cost of reserving capacity with the hotel.
Protect the hot hotel without weakening the invariantSharding by hotel isolates properties but cannot split one hot row. Independent quota buckets can spread writes, with stranded capacity and added .
Fence the booking owner before failoverSynchronous regional durability adds latency and may stop writes during partitions. Async DR improves local performance but cannot safely reopen inventory on the basis of alone.

Production scars & failure modes

Failure investigation

The guest is charged for the last room, then the booking worker crashes before confirmation.

Look for: Find the reservation, its deadline, the persisted payment operation and the provider's verified outcome. Check who owns the inventory before retrying.

Recovery and invariant: Confirm only if the same hold is still eligible. If inventory was released, preserve the expired booking and track a refund. Recover the original operation identity before making another provider call.

Component / failureRequired behavior / recoveryOperational implication
Two bookings contend for the last roomLock all nights in order and recheck inside the transaction. One hold wins. The other rolls back and receives an unavailable response.Verify no negative count and no partial stay. Watch lock waits by hotel/date.
Provider captured payment, then worker crashedLoad the persisted payment key and query the provider. Confirm under the same valid hold, or persist a refund if inventory has been released.Track aged captures without bookings and the refund backlog.
Hold expires during paymentLock and recheck reservation state and the database deadline in both paths. Release only once. Late success requires compensation or a new explicit allocation.A callback is payment evidence. It cannot reopen the expired reservation.
Provider timeout or missing webhookKeep the payment pending and reconcile by stable provider identity. Retry only within the provider's contract. Keep tracking payment after hold expiry.Alert on ambiguous operations by age. Escalate if evidence cannot establish the outcome.
Client loses the hold or checkout responseLook up the scoped client key and request hash. Return the existing reservation or operation and its current state.A fresh request ID represents a fresh operation. Retain keys for the promised retry period.
PostgreSQL primary fails during commitFail over to a fenced synchronous replica within the durability domain. Resolve the request key on the new primary before retrying an uncertain commit.A read replica with lag cannot tell you that an acknowledged booking did not exist.
The owning region is unavailableKeep discovery online. Pause new holds for that until the former writer is fenced, durable state is recovered and uncertain provider operations are reconciled.Asynchronous DR can lose acknowledged allocation state. Keep sales closed when recovery evidence is incomplete.
Hotel booking times outStay in PENDING_CONFIRMATION and query by original partner request ID. Replay only with supported or verified absence.A missing response does not prove that the partner has no reservation.
Partner feed is delayed or out of orderDeduplicate, enforce revisions and reconcile gaps from a . Mark the search projection stale or hide immediate checkout.Protect local commitments from stale quota updates. Never infer a partner confirmation from the feed.
, broker or notification is delayedResume publishing committed events and deduplicate at the consumer. Retry confirmation messages independently.The reservation is valid once committed. Email is a delivery channel.

90-second interview summary

I separate global discovery from booking authority. OpenSearch and Redis return fast but potentially stale results. PostgreSQL owns exclusively allocated inventory by hotel, room type and local night.

A hold is an transaction across every night. Lock the date rows in order, check capacity, store the reservation and request identity, and write an record. Confirmation and expiry take the same reservation lock and change counters with state.

Payment runs outside . Persist a stable operation before calling the provider, reconcile timeouts, and confirm only against an eligible hold. A late charge on released inventory becomes a tracked refund. For partner-owned stock, require the partner's own confirmation and reconcile ambiguous calls using the original reference.

Keep one fenced writer per hotel. Discovery can continue during an outage, but booking pauses when authority or commit history is unclear. The tradeoff is accepting pending status and temporary unavailability to protect the reservation and prevent duplicate effects.

Practice questions and answers

Illustrative exercises. Predict the outcome before revealing the explanation.

Only the middle night is sold out. Should the system hold the first and last nights?

No. The booking unit is the entire stay. Reject and roll back all nights unless the guest explicitly chooses separate stays.

The payment provider returns a timeout after capture might have happened. Can the client start a new checkout?

Return the existing reservation and operation status. Reconcile the stable payment identity. A different key could charge the guest again.

East acquired a new shard generation, but its asynchronous replica is missing the last few writes. Can it reopen sales?

A newer generation fences old writes. It does not restore missing holds or charges. Keep affected sales closed until inventory and external operations are reconciled, or use a durability design that prevents that loss.

Explain it without looking

Explain allocate all nights in one transaction

Reveal answer

Partition by hotel. In one PostgreSQL transaction, lock each room-type/date row in order, check the whole stay and create the hold with the client key.

The stay is the unit of sale. A stale read and a per-night partial update can each leave a guest with a promise the system cannot honor.

Popular hotel dates serialize on a few rows. Keep the critical section short and prefer admission control before splitting inventory into independently sellable pools.

Explain make hold expiry a state transition

Reveal answer

Lock the reservation before its inventory rows. Confirmation, expiry and cancellation each verify the prior state and mutate its allocations in the same commit.

A timer tells you when to try a release. Only the state transition determines who is allowed to change the counters.

A long hold improves checkout completion but blocks other guests. A short hold releases inventory quickly and increases the chance that a late capture needs compensation.

Explain persist each payment operation before calling the provider

Reveal answer

Use a durable saga with separate logical keys for charge, void and refund. Reconcile an ambiguous provider result before creating another logical operation.

The provider decides whether money moved. PostgreSQL decides whether the booking can be confirmed. Recovery joins those two facts using durable identity.

A local transaction cannot include the payment provider. A guest may temporarily see a charge on an expired booking while a refund is verified.

Explain respect the hotel's inventory authority

Reveal answer

Allocate owned allotments in PostgreSQL and confirm shared stock through the hotel partner. Cache availability only for discovery.

Hotels may sell the same room type on other channels. Local locking cannot reserve units that another system owns.

Live confirmation adds partner latency and can make checkout temporarily unavailable. Exclusive allotments support fast checkout at the cost of reserving capacity with the hotel.

Explain protect the hot hotel without weakening the invariant

Reveal answer

Scale discovery separately with OpenSearch and Redis. Bound checkout traffic per hotel and keep owned inventory transactions local to one .

The average write rate hides the contention that determines and safety.

Sharding by hotel isolates properties but cannot split one hot row. Independent quota buckets can spread writes, with stranded capacity and added .

Explain fence the booking owner before failover

Reveal answer

Use a single fenced writer per hotel . Acknowledge commits with synchronous multi- durability and define a separate regional recovery policy.

Single writer, durable history and external-effect identity are separate conditions for safe recovery.

Synchronous regional durability adds latency and may stop writes during partitions. Async DR improves local performance but cannot safely reopen inventory on the basis of alone.

Revision checklist

Revision checklist

  • Reconstruct allocate all nights in one transaction: Partition by hotel. In one PostgreSQL transaction, lock each room-type/date row in order, check the whole stay and create the hold with the client key.
  • Reconstruct make hold expiry a state transition: Lock the reservation before its inventory rows. Confirmation, expiry and cancellation each verify the prior state and mutate its allocations in the same commit.
  • Reconstruct persist each payment operation before calling the provider: Use a durable saga with separate logical keys for charge, void and refund. Reconcile an ambiguous provider result before creating another logical operation.
  • Reconstruct respect the hotel's inventory authority: Allocate owned allotments in PostgreSQL and confirm shared stock through the hotel partner. Cache availability only for discovery.
  • Reconstruct protect the hot hotel without weakening the invariant: Scale discovery separately with OpenSearch and Redis. Bound checkout traffic per hotel and keep owned inventory transactions local to one .
  • Reconstruct fence the booking owner before failover: Use a single fenced writer per hotel . Acknowledge commits with synchronous multi- durability and define a separate regional recovery policy.
  • Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
  • Explain one alternative and exactly which guarantee you would relax.
  • Redraw the request and recovery paths without looking; mark what required a hint.

60-minute interview outline

60-minute interview walkthrough

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope search, holds, checkout, and cancellation. Estimate busy hotel contention and distinguish owned from partner inventory.
15–30 minHigh-level designDraw search and a booking transaction for multiple room nights, then trace payment and confirmation.
30–45 minDeep divesExplain why all nights are held atomically and how payment success is reconciled when a hold expires.
45–55 minFailure and recoveryWalk through a database failover or an uncertain partner confirmation. State when booking pauses and when compensation applies.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.
On this page
  1. Problem statement
  2. Functional requirements
  3. Non-functional requirements
  4. Back-of-the-envelope estimates
  5. Entities
  6. API design
  7. High-level design
  8. High-level design component walkthrough
  9. Deep dives — decisions, failures and recovery
  10. Tradeoffs and alternatives
  11. Production scars & failure modes
  12. 90-second interview summary
  13. Practice questions and answers
  14. Explain it without looking
  15. Revision checklist
  16. 60-minute interview walkthrough

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram