Design Hotel Management System
A hotel management system orchestrates the full lifecycle of a guest's stay: searching for rooms, making reservations, checking in, room service, housekeeping, checking out, and billing. The interesting LLD challenge here is room allocation — when a guest checks in, which specific room should they get? The "best fit" strategy minimizes waste and keeps premium rooms available for guests who actually booked them.
Room allocation is the part most candidates talk about. The part interviewers actually probe is the calendar. A room is not "free" or "taken". It's free on some nights and taken on others, and every booking is a date range that must not overlap any other live booking on the same room. Get the overlap test wrong by one day and you either turn away a guest whose stay starts the morning someone else checks out, or you sell the same night twice. Add two receptionists and a website booking the last deluxe room at the same moment, and you have the classic check-then-act race that this page spends a whole section on.
This page walks the full interview route from the LLD interview framework: clarifying questions, entities, a class diagram, the key flows as sequence and state diagrams, the patterns and the alternatives we turned down, then complete, runnable code in Java, Python and TypeScript. After that come the concurrency story, three "the interviewer adds X" extensions shown in code, tests, common mistakes and follow-up questions with answers.
The first version of the code on this page (the "Implementation" section) is kept as it was originally written, because it is a realistic first draft and its bugs are instructive. The two that matter (it can overbook, and it ignores dates when picking a room) are marked with correction notes, and the complete runnable implementation fixes them.
What you should be able to say by the end
"A booking is a half-open date range on one room. Overlap is a.start < b.end && b.start < a.end. The check and the insert happen under the room's lock, so two requests can't both see the room as free. A booking moves through an explicit state machine, holds expire lazily, and pricing is a stack of decorators over a base rate."
Requirements
Functional Requirements
| # | Requirement | Details |
|---|---|---|
| FR-1 | Room management | Add, remove, update rooms with types and amenities |
| FR-2 | Reservation | Create, modify, cancel reservations |
| FR-3 | Check-in | Assign a specific room from the reserved room type |
| FR-4 | Check-out | Generate bill, mark room for cleaning |
| FR-5 | Housekeeping | Track room cleaning status |
| FR-6 | Guest management | Store guest profiles and history |
| FR-7 | Billing | Calculate charges (room + services + taxes) |
| FR-8 | Search | Find available rooms by date range, type, floor |
Non-Functional Requirements
- Single hotel (not a chain)
- No double-booking of rooms
- Rooms cannot be assigned until cleaned after previous checkout
- Support for concurrent reservation requests
Clarifying questions to ask first
The original requirements above are a good list, but in an interview you have to earn them by asking. These are the questions that change the design, with the answers we assume for the rest of the page:
| Question | Why it matters | Assumed answer |
|---|---|---|
| Does the guest book a specific room or a room type? | Decides whether inventory is per room or per type per night | The guest books a type. We pick a concrete room at booking time (see the follow-up on assigning at check-in instead) |
| Is the check-out day a night of the stay? | The off-by-one that causes most overlap bugs | No. A stay is the half-open range [check-in, check-out) |
| Can a booking sit unpaid? For how long? | Introduces a hold state and expiry | Yes, a hold lasts 10 minutes, then lapses unless confirmed |
| Does the price depend on the night? | Decides whether price is per stay or per night | Yes: weekends and seasons change the nightly rate |
| What happens to a guest who never arrives? | Adds a no-show transition | A confirmed booking whose check-in day has passed becomes NO_SHOW |
| Can guests check in before the room is cleaned? | Separates housekeeping state from booking state | No, the room must be CLEAN |
| How many front-desk terminals and booking channels? | Concurrency | Many: the desk, the website and a channel manager all book at once |
| Do we deliberately overbook, the way airlines do? | Changes the core invariant | Not by default. It's discussed as a follow-up |
Additional functional requirements
| # | Requirement | Details |
|---|---|---|
| FR-9 | Holds | A booking starts as a time-limited hold and must be confirmed (paid) before it expires |
| FR-10 | Booking lifecycle | Every status change goes through one transition table, so illegal moves (check out a guest who never checked in) are rejected |
| FR-11 | Per-night pricing | Quote = sum of nightly rates, where weekend and seasonal rules adjust each night |
| FR-12 | No-shows | A daily job marks confirmed bookings whose check-in day has passed as NO_SHOW |
Additional non-functional requirements
- Correctness over throughput. Selling one night twice is a real-world incident (a guest with nowhere to sleep). Turning away a guest because of a stale lock is merely lost revenue. When in doubt, refuse.
- Testable time. Holds expire and no-shows are computed from "now", so the clock is injected.
- Money is exact. Amounts are integer minor units (cents), never floating point.
- Extensible pricing and allocation without editing the booking service.
Out of scope
Payments (we only call confirm once payment succeeds), multi-property chains, loyalty programmes, rate parity across channels, and persistence. The service keeps everything in memory behind small interfaces, and the follow-ups explain how the same invariants map to a database.
Core Entities and Relationships
Underline the nouns in the requirements and you get roughly this list. The important modelling decision is which nouns are entities (they have identity and a lifecycle) and which are value objects (they are defined entirely by their values).
| Entity | Kind | Owns | Notes |
|---|---|---|---|
Room | Entity | its calendar of bookings, its housekeeping status | Identity is the room number. Holds the lock that protects its calendar |
Booking | Entity | guest, room, stay, price, status, extras | The aggregate that moves through the state machine. Called Reservation in the first version |
Guest | Entity | id, name, contact details | Unchanged from the first version |
DateRange | Value object | check-in, check-out | Immutable. Validates checkOut > checkIn. Knows how to test overlap and list its nights |
Invoice | Value object | room total, extras, tax | Built at check-out |
PricingStrategy | Strategy interface | nothing | nightlyRate(room, night). Decorators stack on top of a base rate |
AllocationStrategy | Strategy interface | nothing | Ranks candidate rooms: cheapest first, lowest floor first |
HotelService | Service / facade | rooms, booking registry, strategies, clock | The entry point for every use case |
Three relationships carry the design:
- A room owns its bookings. The calendar lives inside the room, next to the lock that guards it. That puts the data and the invariant ("no two live bookings on this room overlap") in the same object, so it can't be bypassed.
- A booking points to exactly one room. In the first version a reservation had a room type and an optional room, filled in at check-in. That is a legitimate design (see the follow-ups), but it means availability has to be counted per type per night, and the first version didn't do that.
- Status lives on the booking, not the room. A room has no single "reserved" status, because it can be reserved for March and free in April. The only status a room has of its own is its housekeeping state: clean, dirty or out of order.
Room status vs booking status
The first version's RoomStatus enum mixes the two: RESERVED and OCCUPIED describe a booking, while CLEANING and MAINTENANCE describe the physical room. Keeping them separate is what makes date-range search possible. "Is room 201 free on March 21?" is a question about bookings, not about a field on the room.
Date Ranges and Interval Overlap
Every availability question reduces to one test: do two stays overlap? Model a stay as the half-open interval [checkIn, checkOut). The check-in day is the first night, and the check-out day is not a night. A guest arriving on the 20th and leaving on the 23rd sleeps the nights of the 20th, 21st and 22nd.
Two half-open intervals a and b overlap exactly when
The easiest way to convince yourself is to negate it: they don't overlap when one ends on or before the other starts, a.out <= b.in || b.out <= a.in. Here are the cases worth testing, with an existing stay of 20–23 March:
| New stay | Overlaps? | Why |
|---|---|---|
| 23–25 | No | Back to back. The first guest leaves the morning the second arrives |
| 18–20 | No | Back to back on the other side |
| 22–24 | Yes | Shares the night of the 22nd |
| 19–21 | Yes | Shares the night of the 20th |
| 21–22 | Yes | Fully inside |
| 18–26 | Yes | Fully contains it |
| 20–23 | Yes | Identical |
The two classic bugs are using <= (which refuses back-to-back stays and quietly loses a night of revenue on every turnover) and treating the check-out day as a night (which counts one night too many in the price). With half-open ranges, nights = checkOut - checkIn in days, and the boundaries just work.
How expensive is the check?
Each room keeps a list of its bookings, so checking one room is O(k) for k bookings on it, and a search across R rooms is O(R·k). For a single hotel, with a few hundred rooms and a few hundred future bookings each, that's tens of thousands of comparisons, well under a millisecond. If the interviewer pushes on scale, the upgrades in order are:
- Prune dead bookings. Ignore bookings that ended before today, or archive them. Most of k is history.
- Keep each room's bookings sorted by check-in and binary-search for the neighbours of the new range. Only the predecessor and successor can overlap, so the check becomes O(log k).
- An interval tree per room, if bookings can be arbitrary and the list is long.
- A room-night table: one row per (room, night). Availability is a set lookup, and in a database the unique key on
(room_id, night)enforces the invariant for you.
Say the first two out loud and stop. The point is to show you know the check is per room and can be made logarithmic, not to build an interval tree in 45 minutes.
Class Diagram
classDiagram
class Hotel {
-name: string
-rooms: Room[]
-reservations: Reservation[]
+searchAvailableRooms(checkIn, checkOut, type)
+makeReservation(guest, roomType, dates)
+checkIn(reservationId)
+checkOut(reservationId)
}
class Room {
-id: string
-number: string
-floor: number
-type: RoomType
-status: RoomStatus
-pricePerNight: number
-amenities: string[]
}
class Guest {
-id: string
-name: string
-email: string
-phone: string
-idProof: string
}
class Reservation {
-id: string
-guest: Guest
-roomType: RoomType
-assignedRoom: Room
-checkInDate: Date
-checkOutDate: Date
-status: ReservationStatus
-charges: Charge[]
}
class HousekeepingTask {
-id: string
-room: Room
-assignedTo: string
-status: TaskStatus
-createdAt: Date
}
class Charge {
-description: string
-amount: number
-category: ChargeCategory
}
Hotel "1" --> "*" Room
Hotel "1" --> "*" Reservation
Reservation "1" --> "1" Guest
Reservation "1" --> "0..1" Room
Reservation "1" --> "*" Charge
HousekeepingTask "1" --> "1" Room
Revised class diagram
The diagram above is the first version. The revised design below is what the complete runnable implementation builds. The changes: the room owns its calendar, the booking always has a room and a DateRange, status lives on the booking, and pricing and allocation are both strategies.
classDiagram
class HotelService {
-rooms: List~Room~
-bookings: Map~String,Booking~
-pricing: PricingStrategy
-allocation: AllocationStrategy
-clock: Clock
+search(stay, type) List~Room~
+hold(guest, type, stay) Booking
+confirm(bookingId) Booking
+cancel(bookingId)
+checkIn(bookingId, today) Room
+addCharge(bookingId, amount)
+checkOut(bookingId) Invoice
+markNoShows(today) int
}
class Room {
+number: String
+type: RoomType
+floor: int
+baseRate: long
+housekeeping: Housekeeping
-bookings: List~Booking~
+isFree(stay, now, ignore) bool
+tryReserve(booking, now) bool
}
class Booking {
+id: String
+guest: Guest
+room: Room
+stay: DateRange
+price: long
+status: BookingStatus
+holdExpiresAt: Instant
+blocks(now) bool
+moveTo(target)
}
class DateRange {
<<value object>>
+checkIn: LocalDate
+checkOut: LocalDate
+overlaps(other) bool
+nights() List~LocalDate~
}
class Guest {
+id: String
+name: String
}
class Invoice {
<<value object>>
+roomTotal: long
+extrasTotal: long
+tax: long
+total() long
}
class PricingStrategy {
<<interface>>
+nightlyRate(room, night) long
}
class BaseRate
class WeekendSurcharge {
-inner: PricingStrategy
-percent: int
}
class SeasonalRate {
-inner: PricingStrategy
-season: DateRange
-percent: int
}
class AllocationStrategy {
<<interface>>
+rank(rooms) List~Room~
}
class CheapestFirst
class LowestFloorFirst
HotelService "1" *-- "*" Room
HotelService "1" o-- "*" Booking
Room "1" --> "*" Booking : calendar
Booking "*" --> "1" Guest
Booking *-- DateRange
HotelService --> PricingStrategy
HotelService --> AllocationStrategy
HotelService ..> Invoice : creates
BaseRate ..|> PricingStrategy
WeekendSurcharge ..|> PricingStrategy
SeasonalRate ..|> PricingStrategy
WeekendSurcharge o-- PricingStrategy : wraps
SeasonalRate o-- PricingStrategy : wraps
CheapestFirst ..|> AllocationStrategy
LowestFloorFirst ..|> AllocationStrategy
Two things to point at when you draw this. First, Room has both the calendar and tryReserve, so the only way to add a booking to a room is through the method that checks for overlap under the room's lock. Second, WeekendSurcharge both is a PricingStrategy and has one. That's the Decorator shape: you can stack a seasonal rule on a weekend rule on a base rate without any of them knowing about the others.
Key Flows
Search, then hold
Search is read-only and takes no locks. It returns a snapshot that may be stale by the time the guest clicks "Book", so hold doesn't trust it. hold asks the allocation strategy to rank the candidate rooms and then tries each one. A room that turns out to be taken (because another request got there first) is simply skipped.
sequenceDiagram
actor G as Guest
participant H as HotelService
participant A as AllocationStrategy
participant P as PricingStrategy
participant R1 as Room 201
participant R2 as Room 101
G->>H: search(20-23 Mar, DELUXE)
H->>R1: isFree(stay, now)
R1-->>H: true
H->>R2: isFree(stay, now)
R2-->>H: true
H->>P: nightlyRate for each night
P-->>H: 540, 540, 450
H-->>G: two rooms with quotes
G->>H: hold(guest, DELUXE, 20-23 Mar)
H->>A: rank(deluxe rooms)
A-->>H: 201 then 101
H->>R1: tryReserve(booking B1, now)
Note over R1: lock, check overlap, append, unlock
R1-->>H: true
H-->>G: B1 HELD, expires in 10 minutes
Two requests race for the last room
This is the flow the concurrency section is about. Both requests saw the room as free in their search. The room's lock makes the check and the insert one atomic step, so only the first request through the lock gets the room. The second sees the first booking and gets false.
sequenceDiagram
participant A as Request A
participant B as Request B
participant R as Room 901
A->>R: tryReserve(BA)
B->>R: tryReserve(BB)
Note over R: A holds the lock, B waits
R->>R: isFree for BA - yes, append BA
R-->>A: true
Note over R: lock released, B enters
R->>R: isFree for BB - no, BA overlaps
R-->>B: false
B->>B: try the next ranked room, or fail
Confirm before the hold lapses
Payment happens outside the hotel's locks: hold, then charge the card, then confirm. confirm checks the hold's expiry under the room lock, so a confirm and an expiry can't interleave.
sequenceDiagram
actor G as Guest
participant H as HotelService
participant Pay as Payment gateway
participant B as Booking B1
G->>H: hold(...)
H-->>G: B1 HELD until 12:10
G->>Pay: charge card
Pay-->>G: paid
G->>H: confirm(B1)
alt now is before 12:10
H->>B: moveTo(CONFIRMED)
H-->>G: confirmed
else hold already lapsed
H->>B: moveTo(EXPIRED)
H-->>G: error - hold expired, refund
end
Check-in / Check-out Flow
sequenceDiagram
participant G as Guest
participant H as Hotel Service
participant R as Room Allocation
participant HK as Housekeeping
Note over G,HK: Reservation Phase
G->>H: makeReservation(DELUXE, Mar 20-23)
H-->>G: Reservation confirmed (ID: R001)
Note over G,HK: Check-in Phase
G->>H: checkIn(R001)
H->>R: allocate(available rooms, DELUXE)
R-->>H: Room 405
H->>H: Room 405 → OCCUPIED
H-->>G: Checked in to Room 405
Note over G,HK: During Stay
G->>H: addCharge(minibar, $25)
G->>H: addCharge(laundry, $15)
Note over G,HK: Check-out Phase
G->>H: checkOut(R001)
H->>H: Calculate: Room + Services + Tax
H->>HK: createTask(Room 405, "clean")
H-->>G: Bill: $1,547.20
HK->>HK: Clean Room 405
HK->>H: completeTask → Room 405 AVAILABLE
Correction (2026-11-10)
The bill in the diagram above ($1,547.20) doesn't match the billing breakdown below, which works the same stay through to $1,817.20 (a $500 deluxe room for 3 nights is $1,500, plus $25 minibar and $15 laundry is $1,540, plus 18% tax of $277.20). The breakdown is right. Note also that in the first version's code there is no public addCharge on the service, so the two "addCharge" arrows are aspirational. The revised HotelService adds addCharge.
Booking Lifecycle
A booking's status is the most important piece of state in the system, and most hotel bugs are illegal transitions: cancelling a guest who has already checked out, checking in a booking that expired, adding minibar charges to a cancelled stay. The fix is to write the legal transitions down once, as data, and route every change through it.
stateDiagram-v2
[*] --> HELD: hold
HELD --> CONFIRMED: confirm before TTL
HELD --> EXPIRED: TTL passes
HELD --> CANCELLED: guest abandons
CONFIRMED --> CHECKED_IN: check in during stay
CONFIRMED --> CANCELLED: cancel
CONFIRMED --> NO_SHOW: check-in day passed
CHECKED_IN --> CHECKED_OUT: check out
CHECKED_OUT --> [*]
CANCELLED --> [*]
EXPIRED --> [*]
NO_SHOW --> [*]
| From | Allowed to | Blocks the room's nights? |
|---|---|---|
HELD | CONFIRMED, EXPIRED, CANCELLED | Yes, until holdExpiresAt |
CONFIRMED | CHECKED_IN, CANCELLED, NO_SHOW | Yes |
CHECKED_IN | CHECKED_OUT | Yes |
CHECKED_OUT, CANCELLED, EXPIRED, NO_SHOW | nothing (terminal) | No |
The last column is the trick that keeps the code small. We never delete a booking from a room's calendar. Instead, blocks(now) says whether a booking still occupies its nights. Cancelling is just a status change, and an early check-out frees the remaining nights automatically because CHECKED_OUT doesn't block. Keeping the history also gives you an audit trail for free.
Lazy hold expiry
A held booking blocks its nights only while now < holdExpiresAt. Nothing has to run at 12:10 to release the room: the next isFree call simply stops counting the stale hold. The status still reads HELD until something touches it (a late confirm moves it to EXPIRED), and a periodic sweeper can tidy statuses for reporting. But correctness never depends on the sweeper running on time, which is exactly the property you want from a timeout.
The room's own lifecycle
Housekeeping is a separate, much smaller state machine on the room itself:
stateDiagram-v2
[*] --> CLEAN
CLEAN --> DIRTY: guest checks out
DIRTY --> CLEAN: housekeeping done
CLEAN --> OUT_OF_ORDER: maintenance
DIRTY --> OUT_OF_ORDER: maintenance
OUT_OF_ORDER --> DIRTY: repaired, needs cleaning
Check-in requires CLEAN. A dirty room can still be booked for tonight, since it will be cleaned before the guest arrives. An out-of-order room can't be booked at all. Keeping this separate from the booking status is what lets a room be "booked for tonight, currently dirty" without a combinatorial enum like RESERVED_BUT_DIRTY.
Design Patterns Used
| Pattern | Where Used | Why |
|---|---|---|
| Strategy | Room allocation (BestFit, LowestFloor, etc.) | Swap algorithms without modifying Hotel |
| Observer | Reservation status changes | Notify guest via email/SMS |
| Repository | Reservation storage | Abstract persistence |
| Factory | Room creation | Different room types with standard amenities |
TIP
In interviews, discuss how the room allocation strategy could be swapped at runtime — for example, using LowestFloorAllocation for elderly guests and HighestFloorAllocation for guests requesting a view. This demonstrates understanding of the Strategy pattern and its practical value.
Correction (2026-11-10)
In the first version only Strategy is actually implemented. Observer, Repository and Factory are places where those patterns would fit, not code on this page. The revised implementation uses Strategy twice (allocation and pricing), Decorator for stacking price rules, and a table-driven State machine for the booking lifecycle. Observer appears in the follow-ups.
Patterns: Why, and What We Rejected
| Pattern | Where | Why it earns its place | Alternative we rejected, and why |
|---|---|---|---|
| Strategy | AllocationStrategy (which room) | The rule changes by hotel and by guest (accessible rooms on low floors, view rooms high up), while the booking logic doesn't | An if/else on a "mode" flag inside hold. It works for two modes and rots at five, and every new rule edits the most dangerous method in the system |
| Strategy | PricingStrategy (what a night costs) | Revenue managers change pricing weekly. The booking service shouldn't know how a rate is computed | A price field on Room. Fine until the first weekend surcharge, after which the price depends on the night and a field can't express that |
| Decorator | WeekendSurcharge, SeasonalRate, later OccupancySurge | Rules combine. A summer weekend gets both uplifts, and the order is explicit in how you build the stack | One class per combination (SummerWeekendPricing), which grows combinatorially. Or a list of "rule" objects folded in a loop, which is also fine, and an equally good answer if you say why |
| State (table-driven) | TRANSITIONS map plus Booking.moveTo | All legal moves are visible in one place, and illegal ones fail loudly | One class per state (HeldState, ConfirmedState…). That is the textbook State pattern, and it pays off when each state has different behaviour. Here the states differ only in which transitions are allowed, so a table is less code and easier to review. See the vending machine for a case where per-state classes win |
| Value object | DateRange, Invoice | Immutable, validated once in the constructor, so an invalid stay (check-out before check-in) can't exist anywhere in the system | Passing two raw dates around. Every method would re-validate them, or more likely forget to |
| Facade | HotelService | One entry point for the desk UI, the website and tests | Letting callers poke at Room and Booking directly, which would let them bypass the lock and the state machine |
Patterns we deliberately did not use:
- Singleton
HotelService. Tests need a fresh hotel per case, and a chain needs one service per property. Pass the instance in. See Singleton for the long version of this argument. - Observer for every status change. Tempting ("notify housekeeping when a guest checks out"), but in a 45-minute round a direct call is clearer. Add Observer when there is a second listener; the follow-ups show how.
- A
Repositoryinterface for rooms and bookings. Worth one sentence ("this map would be a repository behind an interface in production"), but writing the interface with one in-memory implementation adds code without changing the design.
Implementation
This is the first version of the code, kept as originally written. It is a reasonable whiteboard draft, and worth reading for the shape: enums, entities, an allocation strategy, a housekeeping service and an orchestrating service. It has two real bugs, both marked below with correction notes, and the complete runnable implementation further down fixes them in Java, Python and TypeScript.
Enums
TypeScript:
enum RoomType {
SINGLE = "SINGLE",
DOUBLE = "DOUBLE",
DELUXE = "DELUXE",
SUITE = "SUITE",
PRESIDENTIAL = "PRESIDENTIAL",
}
enum RoomStatus {
AVAILABLE = "AVAILABLE",
OCCUPIED = "OCCUPIED",
CLEANING = "CLEANING",
MAINTENANCE = "MAINTENANCE",
RESERVED = "RESERVED",
}
enum ReservationStatus {
CONFIRMED = "CONFIRMED",
CHECKED_IN = "CHECKED_IN",
CHECKED_OUT = "CHECKED_OUT",
CANCELLED = "CANCELLED",
NO_SHOW = "NO_SHOW",
}
enum ChargeCategory {
ROOM = "ROOM",
FOOD = "FOOD",
LAUNDRY = "LAUNDRY",
MINIBAR = "MINIBAR",
SPA = "SPA",
DAMAGE = "DAMAGE",
TAX = "TAX",
}
enum TaskStatus {
PENDING = "PENDING",
IN_PROGRESS = "IN_PROGRESS",
COMPLETED = "COMPLETED",
}
Python:
from enum import Enum
from dataclasses import dataclass, field
from datetime import date, datetime
from abc import ABC, abstractmethod
import uuid
class RoomType(Enum):
SINGLE = "SINGLE"
DOUBLE = "DOUBLE"
DELUXE = "DELUXE"
SUITE = "SUITE"
PRESIDENTIAL = "PRESIDENTIAL"
class RoomStatus(Enum):
AVAILABLE = "AVAILABLE"
OCCUPIED = "OCCUPIED"
CLEANING = "CLEANING"
MAINTENANCE = "MAINTENANCE"
RESERVED = "RESERVED"
class ReservationStatus(Enum):
CONFIRMED = "CONFIRMED"
CHECKED_IN = "CHECKED_IN"
CHECKED_OUT = "CHECKED_OUT"
CANCELLED = "CANCELLED"
NO_SHOW = "NO_SHOW"
class ChargeCategory(Enum):
ROOM = "ROOM"
FOOD = "FOOD"
LAUNDRY = "LAUNDRY"
MINIBAR = "MINIBAR"
SPA = "SPA"
DAMAGE = "DAMAGE"
TAX = "TAX"
class TaskStatus(Enum):
PENDING = "PENDING"
IN_PROGRESS = "IN_PROGRESS"
COMPLETED = "COMPLETED"
Entity Classes
TypeScript:
class Room {
public status: RoomStatus = RoomStatus.AVAILABLE;
constructor(
public readonly id: string,
public readonly number: string,
public readonly floor: number,
public readonly type: RoomType,
public readonly pricePerNight: number,
public readonly amenities: string[] = []
) {}
}
class Guest {
constructor(
public readonly id: string,
public readonly name: string,
public readonly email: string,
public readonly phone: string,
public readonly idProof: string
) {}
}
class Charge {
constructor(
public readonly description: string,
public readonly amount: number,
public readonly category: ChargeCategory,
public readonly timestamp: Date = new Date()
) {}
}
class Reservation {
public assignedRoom: Room | null = null;
public status: ReservationStatus = ReservationStatus.CONFIRMED;
public charges: Charge[] = [];
public readonly createdAt = new Date();
constructor(
public readonly id: string,
public readonly guest: Guest,
public readonly roomType: RoomType,
public readonly checkInDate: Date,
public readonly checkOutDate: Date
) {}
get nights(): number {
const diff = this.checkOutDate.getTime() - this.checkInDate.getTime();
return Math.ceil(diff / (1000 * 60 * 60 * 24));
}
addCharge(charge: Charge): void {
this.charges.push(charge);
}
getTotalCharges(): number {
return this.charges.reduce((sum, c) => sum + c.amount, 0);
}
}
Python:
@dataclass
class Room:
id: str
number: str
floor: int
type: RoomType
price_per_night: float
amenities: list[str] = field(default_factory=list)
status: RoomStatus = RoomStatus.AVAILABLE
@dataclass
class Guest:
id: str
name: str
email: str
phone: str
id_proof: str
@dataclass
class Charge:
description: str
amount: float
category: ChargeCategory
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class Reservation:
id: str
guest: Guest
room_type: RoomType
check_in_date: date
check_out_date: date
assigned_room: Room | None = None
status: ReservationStatus = ReservationStatus.CONFIRMED
charges: list[Charge] = field(default_factory=list)
@property
def nights(self) -> int:
return (self.check_out_date - self.check_in_date).days
def add_charge(self, charge: Charge) -> None:
self.charges.append(charge)
def total_charges(self) -> float:
return sum(c.amount for c in self.charges)
Correction (2026-11-10)
Two smaller problems in the entities above. First, money is a floating-point number/float, so totals like 0.1 + 0.2 drift. Store amounts as integer minor units (cents), as the revised code does. Second, the TypeScript nights getter divides a millisecond difference by 24 hours and rounds up. Across the autumn daylight-saving change one day is 25 hours long, so a 2-night stay measures 49 hours and Math.ceil reports 3 nights. The Python version ((check_out - check_in).days on date objects) is correct. The revised TypeScript stores calendar days as integers, so there are no hours to miscount.
Room Allocation Strategy
The Strategy pattern allows different room assignment algorithms. The "best fit" strategy assigns the cheapest available room of the requested type, preserving premium rooms for higher-paying guests.
TypeScript:
interface RoomAllocationStrategy {
allocate(
availableRooms: Room[],
roomType: RoomType
): Room | null;
}
class BestFitAllocation implements RoomAllocationStrategy {
allocate(availableRooms: Room[], roomType: RoomType): Room | null {
const candidates = availableRooms
.filter((r) => r.type === roomType && r.status === RoomStatus.AVAILABLE)
.sort((a, b) => a.pricePerNight - b.pricePerNight); // cheapest first
return candidates[0] ?? null;
}
}
class LowestFloorAllocation implements RoomAllocationStrategy {
allocate(availableRooms: Room[], roomType: RoomType): Room | null {
const candidates = availableRooms
.filter((r) => r.type === roomType && r.status === RoomStatus.AVAILABLE)
.sort((a, b) => a.floor - b.floor); // lowest floor first
return candidates[0] ?? null;
}
}
class HighestFloorAllocation implements RoomAllocationStrategy {
allocate(availableRooms: Room[], roomType: RoomType): Room | null {
const candidates = availableRooms
.filter((r) => r.type === roomType && r.status === RoomStatus.AVAILABLE)
.sort((a, b) => b.floor - a.floor); // highest floor first
return candidates[0] ?? null;
}
}
Python:
class RoomAllocationStrategy(ABC):
@abstractmethod
def allocate(self, available_rooms: list[Room],
room_type: RoomType) -> Room | None: ...
class BestFitAllocation(RoomAllocationStrategy):
def allocate(self, available_rooms: list[Room],
room_type: RoomType) -> Room | None:
candidates = sorted(
[r for r in available_rooms
if r.type == room_type and r.status == RoomStatus.AVAILABLE],
key=lambda r: r.price_per_night
)
return candidates[0] if candidates else None
class LowestFloorAllocation(RoomAllocationStrategy):
def allocate(self, available_rooms: list[Room],
room_type: RoomType) -> Room | None:
candidates = sorted(
[r for r in available_rooms
if r.type == room_type and r.status == RoomStatus.AVAILABLE],
key=lambda r: r.floor
)
return candidates[0] if candidates else None
class HighestFloorAllocation(RoomAllocationStrategy):
def allocate(self, available_rooms: list[Room],
room_type: RoomType) -> Room | None:
candidates = sorted(
[r for r in available_rooms
if r.type == room_type and r.status == RoomStatus.AVAILABLE],
key=lambda r: -r.floor
)
return candidates[0] if candidates else None
Correction (2026-11-10)
These strategies filter on room.status === AVAILABLE, which describes the room right now, not on the guest's dates. At check-in that can hand out a room that is free tonight but already promised to another guest for tomorrow night. Allocation must consider the stay's date range. In the revised design the strategy only ranks rooms, and the room's own tryReserve decides whether the dates are free.
Housekeeping Management
TypeScript:
class HousekeepingTask {
public status: TaskStatus = TaskStatus.PENDING;
constructor(
public readonly id: string,
public readonly room: Room,
public assignedTo: string,
public readonly createdAt: Date = new Date()
) {}
}
class HousekeepingService {
private tasks: Map<string, HousekeepingTask> = new Map();
createTask(room: Room, assignedTo: string): HousekeepingTask {
room.status = RoomStatus.CLEANING;
const task = new HousekeepingTask(
crypto.randomUUID(),
room,
assignedTo
);
this.tasks.set(task.id, task);
return task;
}
completeTask(taskId: string): boolean {
const task = this.tasks.get(taskId);
if (!task || task.status === TaskStatus.COMPLETED) return false;
task.status = TaskStatus.COMPLETED;
task.room.status = RoomStatus.AVAILABLE;
return true;
}
getPendingTasks(): HousekeepingTask[] {
return [...this.tasks.values()].filter(
(t) => t.status !== TaskStatus.COMPLETED
);
}
}
Python:
@dataclass
class HousekeepingTask:
id: str
room: Room
assigned_to: str
status: TaskStatus = TaskStatus.PENDING
created_at: datetime = field(default_factory=datetime.now)
class HousekeepingService:
def __init__(self):
self._tasks: dict[str, HousekeepingTask] = {}
def create_task(self, room: Room, assigned_to: str) -> HousekeepingTask:
room.status = RoomStatus.CLEANING
task = HousekeepingTask(
id=str(uuid.uuid4()),
room=room,
assigned_to=assigned_to
)
self._tasks[task.id] = task
return task
def complete_task(self, task_id: str) -> bool:
task = self._tasks.get(task_id)
if not task or task.status == TaskStatus.COMPLETED:
return False
task.status = TaskStatus.COMPLETED
task.room.status = RoomStatus.AVAILABLE
return True
def get_pending_tasks(self) -> list[HousekeepingTask]:
return [t for t in self._tasks.values() if t.status != TaskStatus.COMPLETED]
Hotel Service (Orchestrator)
Correction (2026-11-10): this version overbooks
searchAvailableRooms only excludes rooms whose reservations have an assignedRoom, but a reservation gets its room at check-in. Until then every confirmed reservation is invisible to search, so makeReservation accepts any number of bookings for the same nights. Running the Python version with one deluxe room and three identical requests accepts all three. The second guest then gets None at check-in. There is also a check-then-act race: two concurrent calls can both pass the availability check before either stores its reservation. The fix is either to count reservations per room type per night against the number of rooms of that type, or (as in the revised code) to reserve a concrete room at booking time with the overlap check and the insert done atomically under the room's lock.
TypeScript:
class HotelService {
private rooms: Room[] = [];
private reservations: Map<string, Reservation> = new Map();
private allocationStrategy: RoomAllocationStrategy;
private housekeeping: HousekeepingService;
private taxRate: number;
constructor(
allocationStrategy: RoomAllocationStrategy = new BestFitAllocation(),
taxRate = 0.18
) {
this.allocationStrategy = allocationStrategy;
this.housekeeping = new HousekeepingService();
this.taxRate = taxRate;
}
addRoom(room: Room): void {
this.rooms.push(room);
}
searchAvailableRooms(
checkIn: Date,
checkOut: Date,
roomType?: RoomType
): Room[] {
const occupiedRoomIds = new Set<string>();
for (const [, res] of this.reservations) {
if (
res.status === ReservationStatus.CONFIRMED ||
res.status === ReservationStatus.CHECKED_IN
) {
if (res.checkInDate < checkOut && res.checkOutDate > checkIn) {
if (res.assignedRoom) {
occupiedRoomIds.add(res.assignedRoom.id);
}
}
}
}
return this.rooms.filter((r) => {
if (occupiedRoomIds.has(r.id)) return false;
if (r.status === RoomStatus.MAINTENANCE) return false;
if (roomType && r.type !== roomType) return false;
return true;
});
}
makeReservation(
guest: Guest,
roomType: RoomType,
checkIn: Date,
checkOut: Date
): Reservation | null {
const available = this.searchAvailableRooms(checkIn, checkOut, roomType);
if (available.length === 0) return null;
const reservation = new Reservation(
crypto.randomUUID(),
guest,
roomType,
checkIn,
checkOut
);
this.reservations.set(reservation.id, reservation);
return reservation;
}
checkIn(reservationId: string): Room | null {
const reservation = this.reservations.get(reservationId);
if (!reservation || reservation.status !== ReservationStatus.CONFIRMED) {
return null;
}
const room = this.allocationStrategy.allocate(
this.rooms,
reservation.roomType
);
if (!room) return null;
room.status = RoomStatus.OCCUPIED;
reservation.assignedRoom = room;
reservation.status = ReservationStatus.CHECKED_IN;
// Add room charges
const roomCharge = new Charge(
`Room ${room.number} (${reservation.nights} nights)`,
room.pricePerNight * reservation.nights,
ChargeCategory.ROOM
);
reservation.addCharge(roomCharge);
return room;
}
checkOut(reservationId: string): { total: number; charges: Charge[] } | null {
const reservation = this.reservations.get(reservationId);
if (!reservation || reservation.status !== ReservationStatus.CHECKED_IN) {
return null;
}
// Add tax
const subtotal = reservation.getTotalCharges();
const tax = new Charge(
`Tax (${this.taxRate * 100}%)`,
subtotal * this.taxRate,
ChargeCategory.TAX
);
reservation.addCharge(tax);
// Update statuses
reservation.status = ReservationStatus.CHECKED_OUT;
const room = reservation.assignedRoom!;
// Create housekeeping task
this.housekeeping.createTask(room, "auto-assigned");
return {
total: reservation.getTotalCharges(),
charges: reservation.charges,
};
}
cancelReservation(reservationId: string): boolean {
const reservation = this.reservations.get(reservationId);
if (!reservation || reservation.status !== ReservationStatus.CONFIRMED) {
return false;
}
reservation.status = ReservationStatus.CANCELLED;
if (reservation.assignedRoom) {
reservation.assignedRoom.status = RoomStatus.AVAILABLE;
}
return true;
}
}
Python:
class HotelService:
def __init__(self, allocation_strategy: RoomAllocationStrategy | None = None,
tax_rate: float = 0.18):
self.rooms: list[Room] = []
self._reservations: dict[str, Reservation] = {}
self._strategy = allocation_strategy or BestFitAllocation()
self._housekeeping = HousekeepingService()
self._tax_rate = tax_rate
def add_room(self, room: Room) -> None:
self.rooms.append(room)
def search_available_rooms(self, check_in: date, check_out: date,
room_type: RoomType | None = None) -> list[Room]:
occupied_ids: set[str] = set()
for res in self._reservations.values():
if res.status in (ReservationStatus.CONFIRMED, ReservationStatus.CHECKED_IN):
if res.check_in_date < check_out and res.check_out_date > check_in:
if res.assigned_room:
occupied_ids.add(res.assigned_room.id)
return [
r for r in self.rooms
if r.id not in occupied_ids
and r.status != RoomStatus.MAINTENANCE
and (room_type is None or r.type == room_type)
]
def make_reservation(self, guest: Guest, room_type: RoomType,
check_in: date, check_out: date) -> Reservation | None:
available = self.search_available_rooms(check_in, check_out, room_type)
if not available:
return None
reservation = Reservation(
id=str(uuid.uuid4()), guest=guest, room_type=room_type,
check_in_date=check_in, check_out_date=check_out
)
self._reservations[reservation.id] = reservation
return reservation
def check_in(self, reservation_id: str) -> Room | None:
res = self._reservations.get(reservation_id)
if not res or res.status != ReservationStatus.CONFIRMED:
return None
room = self._strategy.allocate(self.rooms, res.room_type)
if not room:
return None
room.status = RoomStatus.OCCUPIED
res.assigned_room = room
res.status = ReservationStatus.CHECKED_IN
res.add_charge(Charge(
description=f"Room {room.number} ({res.nights} nights)",
amount=room.price_per_night * res.nights,
category=ChargeCategory.ROOM
))
return room
def check_out(self, reservation_id: str) -> dict | None:
res = self._reservations.get(reservation_id)
if not res or res.status != ReservationStatus.CHECKED_IN:
return None
subtotal = res.total_charges()
res.add_charge(Charge(
description=f"Tax ({self._tax_rate * 100}%)",
amount=subtotal * self._tax_rate,
category=ChargeCategory.TAX
))
res.status = ReservationStatus.CHECKED_OUT
self._housekeeping.create_task(res.assigned_room, "auto-assigned")
return {"total": res.total_charges(), "charges": res.charges}
def cancel_reservation(self, reservation_id: str) -> bool:
res = self._reservations.get(reservation_id)
if not res or res.status != ReservationStatus.CONFIRMED:
return False
res.status = ReservationStatus.CANCELLED
if res.assigned_room:
res.assigned_room.status = RoomStatus.AVAILABLE
return True
Billing Breakdown
where = price per night, = number of nights, = additional charges, = tax rate.
Example:
- Deluxe room: nights = $1,500
- Minibar: $25
- Laundry: $15
- Subtotal: $1,540
- Tax (18%): $277.20
- Total: $1,817.20
Money in code
The breakdown above multiplies dollars as decimals, which is fine on paper. In code, keep amounts in integer cents and round the tax once, at the end. The revised implementation computes tax = (room + extras) * taxPercent / 100 in integer arithmetic, so the self-check's stay (1,530.00 of room nights at weekend prices plus a 25.00 minibar charge, taxed at 18%) comes out to exactly 1,834.90 in every language.
Complete Runnable Implementation
Each tab below is one self-contained file with no dependencies beyond the standard library. Each ends with a self-check that exercises the overlap edge cases, weekend pricing, hold expiry, illegal transitions, the invoice, housekeeping, cancellation, and a 50-way race for a single room. Run them as:
- Java 21+:
javac HotelDemo.java && java -ea HotelDemo(the-eaflag turns onassert) - Python 3.10+:
python hotel.py - TypeScript:
tsc --strict --noEmit --target es2022 hotel.ts && npx tsx hotel.ts
The scenario in the self-check: room 101 is a deluxe at 500.00 a night, room 201 a deluxe at 450.00, and weekend nights (Friday and Saturday) carry a 20% surcharge. 20 March 2026 is a Friday, so a 20–23 March stay in room 201 costs 540 + 540 + 450 = 1,530.00.
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
public class HotelDemo {
enum RoomType { SINGLE, DOUBLE, DELUXE, SUITE }
enum Housekeeping { CLEAN, DIRTY, OUT_OF_ORDER }
enum BookingStatus { HELD, CONFIRMED, CHECKED_IN, CHECKED_OUT, CANCELLED, EXPIRED, NO_SHOW }
static final Map<BookingStatus, Set<BookingStatus>> TRANSITIONS = new EnumMap<>(Map.of(
BookingStatus.HELD, EnumSet.of(BookingStatus.CONFIRMED, BookingStatus.EXPIRED, BookingStatus.CANCELLED),
BookingStatus.CONFIRMED, EnumSet.of(BookingStatus.CHECKED_IN, BookingStatus.CANCELLED, BookingStatus.NO_SHOW),
BookingStatus.CHECKED_IN, EnumSet.of(BookingStatus.CHECKED_OUT),
BookingStatus.CHECKED_OUT, EnumSet.noneOf(BookingStatus.class),
BookingStatus.CANCELLED, EnumSet.noneOf(BookingStatus.class),
BookingStatus.EXPIRED, EnumSet.noneOf(BookingStatus.class),
BookingStatus.NO_SHOW, EnumSet.noneOf(BookingStatus.class)));
static class BookingException extends RuntimeException {
BookingException(String msg) { super(msg); }
}
/** Half-open interval [checkIn, checkOut): the check-out day is not a night. */
record DateRange(LocalDate checkIn, LocalDate checkOut) {
DateRange {
if (!checkOut.isAfter(checkIn)) throw new BookingException("check-out must be after check-in");
}
boolean overlaps(DateRange o) {
return checkIn.isBefore(o.checkOut) && o.checkIn.isBefore(checkOut);
}
List<LocalDate> nights() { return checkIn.datesUntil(checkOut).toList(); }
boolean contains(LocalDate day) { return !day.isBefore(checkIn) && day.isBefore(checkOut); }
}
record Guest(String id, String name) {}
static class Room {
final String number; final RoomType type; final int floor; final long baseRate; // cents
Housekeeping housekeeping = Housekeeping.CLEAN; // guarded by this
private final List<Booking> bookings = new ArrayList<>(); // guarded by this
Room(String number, RoomType type, int floor, long baseRate) {
this.number = number; this.type = type; this.floor = floor; this.baseRate = baseRate;
}
synchronized boolean isFree(DateRange stay, Instant now, Booking ignore) {
for (Booking b : bookings)
if (b != ignore && b.blocks(now) && b.stay.overlaps(stay)) return false;
return true;
}
/** Check-and-insert under the room's monitor, so two threads cannot both see "free". */
synchronized boolean tryReserve(Booking booking, Instant now) {
if (housekeeping == Housekeeping.OUT_OF_ORDER || !isFree(booking.stay, now, null)) return false;
bookings.add(booking);
return true;
}
}
static class Booking {
final String id; final Guest guest; final Room room; final Instant holdExpiresAt;
long price; // guarded by room
DateRange stay; // guarded by room
BookingStatus status = BookingStatus.HELD; // guarded by room
final List<Long> extras = new ArrayList<>(); // guarded by room
Booking(String id, Guest guest, Room room, DateRange stay, long price, Instant holdExpiresAt) {
this.id = id; this.guest = guest; this.room = room; this.stay = stay;
this.price = price; this.holdExpiresAt = holdExpiresAt;
}
boolean blocks(Instant now) {
if (status == BookingStatus.HELD) return now.isBefore(holdExpiresAt); // lazy expiry
return status == BookingStatus.CONFIRMED || status == BookingStatus.CHECKED_IN;
}
void moveTo(BookingStatus target) {
if (!TRANSITIONS.get(status).contains(target))
throw new BookingException("illegal transition " + status + " -> " + target);
status = target;
}
}
// ---------- pricing (Strategy + Decorator) ----------
interface PricingStrategy { long nightlyRate(Room room, LocalDate night); }
static class BaseRate implements PricingStrategy {
public long nightlyRate(Room room, LocalDate night) { return room.baseRate; }
}
static class WeekendSurcharge implements PricingStrategy {
private final PricingStrategy inner; private final int percent;
WeekendSurcharge(PricingStrategy inner, int percent) { this.inner = inner; this.percent = percent; }
public long nightlyRate(Room room, LocalDate night) {
long rate = inner.nightlyRate(room, night);
DayOfWeek d = night.getDayOfWeek();
return (d == DayOfWeek.FRIDAY || d == DayOfWeek.SATURDAY) ? rate * (100 + percent) / 100 : rate;
}
}
static class SeasonalRate implements PricingStrategy {
private final PricingStrategy inner; private final DateRange season; private final int percent;
SeasonalRate(PricingStrategy inner, DateRange season, int percent) {
this.inner = inner; this.season = season; this.percent = percent;
}
public long nightlyRate(Room room, LocalDate night) {
long rate = inner.nightlyRate(room, night);
return season.contains(night) ? rate * (100 + percent) / 100 : rate;
}
}
static long quote(PricingStrategy pricing, Room room, DateRange stay) {
long total = 0;
for (LocalDate n : stay.nights()) total += pricing.nightlyRate(room, n);
return total;
}
// ---------- allocation (Strategy) ----------
interface AllocationStrategy { List<Room> rank(List<Room> rooms); }
static class CheapestFirst implements AllocationStrategy {
public List<Room> rank(List<Room> rooms) {
List<Room> out = new ArrayList<>(rooms);
out.sort(Comparator.comparingLong((Room r) -> r.baseRate).thenComparing(r -> r.number));
return out;
}
}
static class LowestFloorFirst implements AllocationStrategy {
public List<Room> rank(List<Room> rooms) {
List<Room> out = new ArrayList<>(rooms);
out.sort(Comparator.comparingInt((Room r) -> r.floor).thenComparing(r -> r.number));
return out;
}
}
record Invoice(long roomTotal, long extrasTotal, long tax) {
long total() { return roomTotal + extrasTotal + tax; }
}
static class HotelService {
static final Duration HOLD_TTL = Duration.ofMinutes(10);
volatile PricingStrategy pricing; // swappable at runtime
final AllocationStrategy allocation;
final Supplier<Instant> clock; final int taxPercent;
final List<Room> rooms = new CopyOnWriteArrayList<>();
final Map<String, Booking> bookings = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
HotelService(PricingStrategy pricing, AllocationStrategy allocation, Supplier<Instant> clock, int taxPercent) {
this.pricing = pricing; this.allocation = allocation; this.clock = clock; this.taxPercent = taxPercent;
}
void addRoom(Room room) { rooms.add(room); }
/** A snapshot. It can be stale by the time the guest clicks Book, so hold() re-checks. */
List<Room> search(DateRange stay, RoomType type) {
Instant now = clock.get();
List<Room> out = new ArrayList<>();
for (Room r : allocation.rank(rooms)) {
boolean usable;
synchronized (r) { usable = r.housekeeping != Housekeeping.OUT_OF_ORDER; }
if ((type == null || r.type == type) && usable && r.isFree(stay, now, null)) out.add(r);
}
return out;
}
Booking hold(Guest guest, RoomType type, DateRange stay) {
Instant now = clock.get();
List<Room> candidates = allocation.rank(rooms.stream().filter(r -> r.type == type).toList());
for (Room room : candidates) {
Booking b = new Booking("B" + ids.incrementAndGet(), guest, room, stay,
quote(pricing, room, stay), now.plus(HOLD_TTL));
if (room.tryReserve(b, now)) { // lost a race? try the next room
bookings.put(b.id, b);
return b;
}
}
throw new BookingException("no " + type + " room free for " + stay);
}
Booking get(String id) {
Booking b = bookings.get(id);
if (b == null) throw new BookingException("unknown booking " + id);
return b;
}
Booking confirm(String id) {
Booking b = get(id);
synchronized (b.room) {
if (b.status == BookingStatus.HELD && !clock.get().isBefore(b.holdExpiresAt)) {
b.moveTo(BookingStatus.EXPIRED);
throw new BookingException("hold expired");
}
b.moveTo(BookingStatus.CONFIRMED);
}
return b;
}
void cancel(String id) {
Booking b = get(id);
synchronized (b.room) { b.moveTo(BookingStatus.CANCELLED); }
}
Room checkIn(String id, LocalDate today) {
Booking b = get(id);
synchronized (b.room) {
if (!b.stay.contains(today)) throw new BookingException("check-in only during the stay");
if (b.room.housekeeping != Housekeeping.CLEAN)
throw new BookingException("room " + b.room.number + " is not ready");
b.moveTo(BookingStatus.CHECKED_IN);
}
return b.room;
}
void addCharge(String id, long amount) {
Booking b = get(id);
synchronized (b.room) {
if (b.status != BookingStatus.CHECKED_IN) throw new BookingException("charges only while checked in");
b.extras.add(amount);
}
}
Invoice checkOut(String id) {
Booking b = get(id);
synchronized (b.room) {
b.moveTo(BookingStatus.CHECKED_OUT);
b.room.housekeeping = Housekeeping.DIRTY;
long extras = b.extras.stream().mapToLong(Long::longValue).sum();
return new Invoice(b.price, extras, (b.price + extras) * taxPercent / 100);
}
}
void markClean(Room room) { synchronized (room) { room.housekeeping = Housekeeping.CLEAN; } }
int markNoShows(LocalDate today) {
int count = 0;
for (Booking b : bookings.values()) {
synchronized (b.room) {
if (b.status == BookingStatus.CONFIRMED && b.stay.checkIn().isBefore(today)) {
b.moveTo(BookingStatus.NO_SHOW);
count++;
}
}
}
return count;
}
}
// ---------- self-check (run with java -ea) ----------
static void expectFail(Runnable r, String why) {
try { r.run(); } catch (BookingException e) { return; }
throw new AssertionError(why);
}
public static void main(String[] args) throws Exception {
Instant[] now = { Instant.parse("2026-03-01T12:00:00Z") };
HotelService hotel = new HotelService(new WeekendSurcharge(new BaseRate(), 20),
new CheapestFirst(), () -> now[0], 18);
Room r101 = new Room("101", RoomType.DELUXE, 1, 500_00);
Room r201 = new Room("201", RoomType.DELUXE, 2, 450_00);
hotel.addRoom(r101); hotel.addRoom(r201);
Guest alice = new Guest("g1", "Alice"), bob = new Guest("g2", "Bob"), carol = new Guest("g3", "Carol");
DateRange mar20to23 = new DateRange(LocalDate.of(2026, 3, 20), LocalDate.of(2026, 3, 23));
assert !mar20to23.overlaps(new DateRange(LocalDate.of(2026, 3, 23), LocalDate.of(2026, 3, 25)));
assert mar20to23.overlaps(new DateRange(LocalDate.of(2026, 3, 22), LocalDate.of(2026, 3, 24)));
Booking a = hotel.hold(alice, RoomType.DELUXE, mar20to23);
assert a.room == r201 && a.price == 540_00 * 2 + 450_00 : a.price;
hotel.confirm(a.id);
Booking b = hotel.hold(bob, RoomType.DELUXE, mar20to23);
assert b.room == r101;
expectFail(() -> hotel.hold(carol, RoomType.DELUXE,
new DateRange(LocalDate.of(2026, 3, 22), LocalDate.of(2026, 3, 24))), "overbooked");
assert hotel.hold(carol, RoomType.DELUXE,
new DateRange(LocalDate.of(2026, 3, 23), LocalDate.of(2026, 3, 25))).room == r201;
now[0] = now[0].plus(Duration.ofMinutes(11));
Booking c = hotel.hold(carol, RoomType.DELUXE, mar20to23);
assert c.room == r101;
expectFail(() -> hotel.confirm(b.id), "expired hold confirmed");
assert b.status == BookingStatus.EXPIRED;
expectFail(() -> hotel.checkOut(a.id), "checked out without checking in");
hotel.checkIn(a.id, LocalDate.of(2026, 3, 20));
hotel.addCharge(a.id, 25_00);
Invoice inv = hotel.checkOut(a.id);
assert inv.roomTotal() == 1530_00 && inv.extrasTotal() == 25_00;
assert inv.tax() == 279_90 && inv.total() == 1834_90 : inv;
assert r201.housekeeping == Housekeeping.DIRTY;
Booking later = hotel.hold(alice, RoomType.DELUXE,
new DateRange(LocalDate.of(2026, 4, 1), LocalDate.of(2026, 4, 2)));
hotel.confirm(later.id);
expectFail(() -> hotel.checkIn(later.id, LocalDate.of(2026, 4, 1)), "checked into a dirty room");
hotel.markClean(later.room);
hotel.checkIn(later.id, LocalDate.of(2026, 4, 1));
hotel.confirm(c.id);
hotel.cancel(c.id);
assert hotel.search(mar20to23, RoomType.DELUXE).contains(r101);
// concurrency: 50 threads race for one suite, exactly one wins
HotelService h2 = new HotelService(new BaseRate(), new CheapestFirst(), () -> now[0], 18);
h2.addRoom(new Room("901", RoomType.SUITE, 9, 900_00));
int n = 50;
CountDownLatch start = new CountDownLatch(1);
ConcurrentLinkedQueue<Booking> wins = new ConcurrentLinkedQueue<>();
try (ExecutorService pool = Executors.newFixedThreadPool(n)) {
for (int i = 0; i < n; i++) {
Guest g = new Guest("t" + i, "T");
pool.submit(() -> {
start.await();
try { wins.add(h2.hold(g, RoomType.SUITE, mar20to23)); } catch (BookingException ignored) {}
return null;
});
}
start.countDown();
}
assert wins.size() == 1 : wins.size();
System.out.println("HotelDemo: all assertions passed");
}
}
from __future__ import annotations
import itertools
import threading
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from enum import Enum
from typing import Callable, Protocol
class RoomType(Enum):
SINGLE = 1
DOUBLE = 2
DELUXE = 3
SUITE = 4
class Housekeeping(Enum):
CLEAN = "CLEAN"
DIRTY = "DIRTY"
OUT_OF_ORDER = "OUT_OF_ORDER"
class BookingStatus(Enum):
HELD = "HELD"
CONFIRMED = "CONFIRMED"
CHECKED_IN = "CHECKED_IN"
CHECKED_OUT = "CHECKED_OUT"
CANCELLED = "CANCELLED"
EXPIRED = "EXPIRED"
NO_SHOW = "NO_SHOW"
S = BookingStatus
TRANSITIONS: dict[BookingStatus, set[BookingStatus]] = {
S.HELD: {S.CONFIRMED, S.EXPIRED, S.CANCELLED},
S.CONFIRMED: {S.CHECKED_IN, S.CANCELLED, S.NO_SHOW},
S.CHECKED_IN: {S.CHECKED_OUT},
S.CHECKED_OUT: set(), S.CANCELLED: set(), S.EXPIRED: set(), S.NO_SHOW: set(),
}
class BookingError(Exception):
pass
@dataclass(frozen=True)
class DateRange:
"""Half-open interval [check_in, check_out): the check-out day is not a night."""
check_in: date
check_out: date
def __post_init__(self) -> None:
if self.check_out <= self.check_in:
raise BookingError("check-out must be after check-in")
def overlaps(self, other: DateRange) -> bool:
return self.check_in < other.check_out and other.check_in < self.check_out
def nights(self) -> list[date]:
n = (self.check_out - self.check_in).days
return [self.check_in + timedelta(days=i) for i in range(n)]
@dataclass(frozen=True)
class Guest:
id: str
name: str
class Room:
def __init__(self, number: str, type: RoomType, floor: int, base_rate: int):
self.number, self.type, self.floor = number, type, floor
self.base_rate = base_rate # minor units (cents)
self.housekeeping = Housekeeping.CLEAN
self.lock = threading.Lock() # guards _bookings and their status
self._bookings: list[Booking] = []
def is_free(self, stay: DateRange, now: datetime, ignore: Booking | None = None) -> bool:
return not any(b is not ignore and b.blocks(now) and b.stay.overlaps(stay)
for b in self._bookings)
def try_reserve(self, booking: Booking, now: datetime) -> bool:
with self.lock: # check-and-insert is atomic
if self.housekeeping is Housekeeping.OUT_OF_ORDER or not self.is_free(booking.stay, now):
return False
self._bookings.append(booking)
return True
@dataclass
class Booking:
id: str
guest: Guest
room: Room
stay: DateRange
price: int
hold_expires_at: datetime
status: BookingStatus = BookingStatus.HELD
extras: list[tuple[str, int]] = field(default_factory=list)
def blocks(self, now: datetime) -> bool:
if self.status is S.HELD:
return now < self.hold_expires_at # lazy expiry: a stale hold blocks nothing
return self.status in (S.CONFIRMED, S.CHECKED_IN)
def move_to(self, target: BookingStatus) -> None:
if target not in TRANSITIONS[self.status]:
raise BookingError(f"illegal transition {self.status.name} -> {target.name}")
self.status = target
# ---------- pricing (Strategy + Decorator) ----------
class PricingStrategy(Protocol):
def nightly_rate(self, room: Room, night: date) -> int: ...
class BaseRate:
def nightly_rate(self, room: Room, night: date) -> int:
return room.base_rate
class WeekendSurcharge:
def __init__(self, inner: PricingStrategy, percent: int):
self.inner, self.percent = inner, percent
def nightly_rate(self, room: Room, night: date) -> int:
rate = self.inner.nightly_rate(room, night)
return rate * (100 + self.percent) // 100 if night.weekday() in (4, 5) else rate # Fri, Sat
class SeasonalRate:
def __init__(self, inner: PricingStrategy, season: DateRange, percent: int):
self.inner, self.season, self.percent = inner, season, percent
def nightly_rate(self, room: Room, night: date) -> int:
rate = self.inner.nightly_rate(room, night)
in_season = self.season.check_in <= night < self.season.check_out
return rate * (100 + self.percent) // 100 if in_season else rate
def quote(pricing: PricingStrategy, room: Room, stay: DateRange) -> int:
return sum(pricing.nightly_rate(room, n) for n in stay.nights())
# ---------- allocation (Strategy) ----------
class AllocationStrategy(Protocol):
def rank(self, rooms: list[Room]) -> list[Room]: ...
class CheapestFirst:
def rank(self, rooms: list[Room]) -> list[Room]:
return sorted(rooms, key=lambda r: (r.base_rate, r.number))
class LowestFloorFirst:
def rank(self, rooms: list[Room]) -> list[Room]:
return sorted(rooms, key=lambda r: (r.floor, r.number))
@dataclass(frozen=True)
class Invoice:
room_total: int
extras_total: int
tax: int
@property
def total(self) -> int:
return self.room_total + self.extras_total + self.tax
class HotelService:
HOLD_TTL = timedelta(minutes=10)
def __init__(self, pricing: PricingStrategy | None = None,
allocation: AllocationStrategy | None = None,
clock: Callable[[], datetime] = datetime.now, tax_percent: int = 18):
self.pricing = pricing or BaseRate()
self.allocation = allocation or CheapestFirst()
self.clock = clock
self.tax_percent = tax_percent
self.rooms: list[Room] = []
self.bookings: dict[str, Booking] = {}
self._ids = itertools.count(1)
self._registry_lock = threading.Lock() # guards self.bookings and id generation
def add_room(self, room: Room) -> None:
self.rooms.append(room)
def search(self, stay: DateRange, room_type: RoomType | None = None) -> list[tuple[Room, int]]:
"""A snapshot. It can be stale by the time the guest clicks Book, so hold() re-checks."""
now = self.clock()
return [(r, quote(self.pricing, r, stay)) for r in self.allocation.rank(self.rooms)
if (room_type is None or r.type is room_type)
and r.housekeeping is not Housekeeping.OUT_OF_ORDER and r.is_free(stay, now)]
def hold(self, guest: Guest, room_type: RoomType, stay: DateRange) -> Booking:
now = self.clock()
candidates = self.allocation.rank([r for r in self.rooms if r.type is room_type])
for room in candidates:
with self._registry_lock:
booking_id = f"B{next(self._ids)}"
booking = Booking(booking_id, guest, room, stay,
quote(self.pricing, room, stay), now + self.HOLD_TTL)
if room.try_reserve(booking, now): # lost a race? try the next room
with self._registry_lock:
self.bookings[booking.id] = booking
return booking
raise BookingError(f"no {room_type.name} room free for {stay}")
def _get(self, booking_id: str) -> Booking:
with self._registry_lock:
booking = self.bookings.get(booking_id)
if booking is None:
raise BookingError(f"unknown booking {booking_id}")
return booking
def confirm(self, booking_id: str) -> Booking:
b = self._get(booking_id)
with b.room.lock:
if b.status is S.HELD and self.clock() >= b.hold_expires_at:
b.move_to(S.EXPIRED)
raise BookingError("hold expired")
b.move_to(S.CONFIRMED)
return b
def cancel(self, booking_id: str) -> None:
b = self._get(booking_id)
with b.room.lock:
b.move_to(S.CANCELLED) # non-blocking status frees the nights
def check_in(self, booking_id: str, today: date) -> Room:
b = self._get(booking_id)
with b.room.lock:
if not (b.stay.check_in <= today < b.stay.check_out):
raise BookingError("check-in only during the stay")
if b.room.housekeeping is not Housekeeping.CLEAN:
raise BookingError(f"room {b.room.number} is not ready")
b.move_to(S.CHECKED_IN)
return b.room
def add_charge(self, booking_id: str, description: str, amount: int) -> None:
b = self._get(booking_id)
with b.room.lock:
if b.status is not S.CHECKED_IN:
raise BookingError("charges only while checked in")
b.extras.append((description, amount))
def check_out(self, booking_id: str) -> Invoice:
b = self._get(booking_id)
with b.room.lock:
b.move_to(S.CHECKED_OUT)
b.room.housekeeping = Housekeeping.DIRTY
extras = sum(a for _, a in b.extras)
tax = (b.price + extras) * self.tax_percent // 100
return Invoice(b.price, extras, tax)
def mark_clean(self, room: Room) -> None:
with room.lock:
room.housekeeping = Housekeeping.CLEAN
def mark_no_shows(self, today: date) -> int:
with self._registry_lock:
snapshot = list(self.bookings.values())
count = 0
for b in snapshot:
with b.room.lock:
if b.status is S.CONFIRMED and b.stay.check_in < today:
b.move_to(S.NO_SHOW)
count += 1
return count
# ---------- self-check ----------
if __name__ == "__main__":
d = date
now = [datetime(2026, 3, 1, 12, 0)]
hotel = HotelService(pricing=WeekendSurcharge(BaseRate(), 20), clock=lambda: now[0])
r101 = Room("101", RoomType.DELUXE, 1, 500_00)
r201 = Room("201", RoomType.DELUXE, 2, 450_00)
hotel.add_room(r101)
hotel.add_room(r201)
alice, bob, carol = Guest("g1", "Alice"), Guest("g2", "Bob"), Guest("g3", "Carol")
mar20_23 = DateRange(d(2026, 3, 20), d(2026, 3, 23)) # Fri, Sat, Sun nights
# back-to-back stays share a boundary day but do not overlap
assert not mar20_23.overlaps(DateRange(d(2026, 3, 23), d(2026, 3, 25)))
assert mar20_23.overlaps(DateRange(d(2026, 3, 22), d(2026, 3, 24)))
# pricing: 450 * 1.2 (Fri) + 450 * 1.2 (Sat) + 450 (Sun)
a = hotel.hold(alice, RoomType.DELUXE, mar20_23)
assert a.room is r201 and a.price == 540_00 * 2 + 450_00
hotel.confirm(a.id)
b = hotel.hold(bob, RoomType.DELUXE, mar20_23)
assert b.room is r101
try: # both deluxe rooms taken
hotel.hold(carol, RoomType.DELUXE, DateRange(d(2026, 3, 22), d(2026, 3, 24)))
raise AssertionError("overbooked")
except BookingError:
pass
assert hotel.hold(carol, RoomType.DELUXE, DateRange(d(2026, 3, 23), d(2026, 3, 25))).room is r201
# Bob's hold lapses, so Carol can take room 101, and Bob's late confirm fails
now[0] += timedelta(minutes=11)
c = hotel.hold(carol, RoomType.DELUXE, mar20_23)
assert c.room is r101
try:
hotel.confirm(b.id)
raise AssertionError("expired hold confirmed")
except BookingError:
assert b.status is S.EXPIRED
# illegal transitions are rejected
try:
hotel.check_out(a.id)
raise AssertionError("checked out without checking in")
except BookingError:
pass
# stay, extras, invoice, housekeeping
hotel.check_in(a.id, d(2026, 3, 20))
hotel.add_charge(a.id, "minibar", 25_00)
inv = hotel.check_out(a.id)
assert inv.room_total == 1530_00 and inv.extras_total == 25_00
assert inv.tax == 1555_00 * 18 // 100 and inv.total == 1555_00 + 279_90
assert r201.housekeeping is Housekeeping.DIRTY
later = hotel.hold(alice, RoomType.DELUXE, DateRange(d(2026, 4, 1), d(2026, 4, 2)))
hotel.confirm(later.id)
try:
hotel.check_in(later.id, d(2026, 4, 1)) # cheapest room is still dirty
raise AssertionError("checked into a dirty room")
except BookingError:
pass
hotel.mark_clean(later.room)
hotel.check_in(later.id, d(2026, 4, 1))
# cancel frees the nights
hotel.confirm(c.id)
hotel.cancel(c.id)
assert any(r is r101 for r, _ in hotel.search(mar20_23, RoomType.DELUXE))
# concurrency: 50 threads race for one suite, exactly one wins
h2 = HotelService(clock=lambda: now[0])
h2.add_room(Room("901", RoomType.SUITE, 9, 900_00))
wins: list[Booking] = []
barrier = threading.Barrier(50)
def attempt(i: int) -> None:
barrier.wait()
try:
wins.append(h2.hold(Guest(f"t{i}", "T"), RoomType.SUITE, mar20_23))
except BookingError:
pass
threads = [threading.Thread(target=attempt, args=(i,)) for i in range(50)]
for t in threads:
t.start()
for t in threads:
t.join()
assert len(wins) == 1, len(wins)
print("hotel.py: all assertions passed")
enum RoomType { SINGLE = "SINGLE", DOUBLE = "DOUBLE", DELUXE = "DELUXE", SUITE = "SUITE" }
enum Housekeeping { CLEAN = "CLEAN", DIRTY = "DIRTY", OUT_OF_ORDER = "OUT_OF_ORDER" }
enum BookingStatus {
HELD = "HELD", CONFIRMED = "CONFIRMED", CHECKED_IN = "CHECKED_IN", CHECKED_OUT = "CHECKED_OUT",
CANCELLED = "CANCELLED", EXPIRED = "EXPIRED", NO_SHOW = "NO_SHOW",
}
const TRANSITIONS: Record<BookingStatus, BookingStatus[]> = {
[BookingStatus.HELD]: [BookingStatus.CONFIRMED, BookingStatus.EXPIRED, BookingStatus.CANCELLED],
[BookingStatus.CONFIRMED]: [BookingStatus.CHECKED_IN, BookingStatus.CANCELLED, BookingStatus.NO_SHOW],
[BookingStatus.CHECKED_IN]: [BookingStatus.CHECKED_OUT],
[BookingStatus.CHECKED_OUT]: [], [BookingStatus.CANCELLED]: [],
[BookingStatus.EXPIRED]: [], [BookingStatus.NO_SHOW]: [],
};
class BookingError extends Error {}
const MS_PER_DAY = 86_400_000;
/** Calendar days as integers (days since 1970-01-01 UTC), so time zones and DST never shift a night. */
function day(iso: string): number {
const [y, m, d] = iso.split("-").map(Number);
return Date.UTC(y, m - 1, d) / MS_PER_DAY;
}
const weekday = (dayNumber: number): number => new Date(dayNumber * MS_PER_DAY).getUTCDay(); // 0 = Sun
/** Half-open interval [checkIn, checkOut): the check-out day is not a night. */
class DateRange {
constructor(readonly checkIn: number, readonly checkOut: number) {
if (checkOut <= checkIn) throw new BookingError("check-out must be after check-in");
}
static of(from: string, to: string): DateRange { return new DateRange(day(from), day(to)); }
overlaps(o: DateRange): boolean { return this.checkIn < o.checkOut && o.checkIn < this.checkOut; }
contains(d: number): boolean { return this.checkIn <= d && d < this.checkOut; }
nights(): number[] {
const out: number[] = [];
for (let d = this.checkIn; d < this.checkOut; d++) out.push(d);
return out;
}
}
class Guest { constructor(readonly id: string, readonly name: string) {} }
class Room {
housekeeping = Housekeeping.CLEAN;
private readonly bookings: Booking[] = [];
constructor(readonly num: string, readonly type: RoomType, readonly floor: number,
readonly baseRate: number /* cents */) {}
isFree(stay: DateRange, now: number, ignore?: Booking): boolean {
return !this.bookings.some(b => b !== ignore && b.blocks(now) && b.stay.overlaps(stay));
}
/** Synchronous check-and-insert: no await between the check and the push, so it is atomic. */
tryReserve(booking: Booking, now: number): boolean {
if (this.housekeeping === Housekeeping.OUT_OF_ORDER || !this.isFree(booking.stay, now)) return false;
this.bookings.push(booking);
return true;
}
}
class Booking {
status = BookingStatus.HELD;
readonly extras: number[] = [];
constructor(readonly id: string, readonly guest: Guest, readonly room: Room, public stay: DateRange,
public price: number, readonly holdExpiresAt: number) {}
blocks(now: number): boolean {
if (this.status === BookingStatus.HELD) return now < this.holdExpiresAt; // lazy expiry
return this.status === BookingStatus.CONFIRMED || this.status === BookingStatus.CHECKED_IN;
}
moveTo(target: BookingStatus): void {
if (!TRANSITIONS[this.status].includes(target))
throw new BookingError(`illegal transition ${this.status} -> ${target}`);
this.status = target;
}
}
// ---------- pricing (Strategy + Decorator) ----------
interface PricingStrategy { nightlyRate(room: Room, night: number): number; }
class BaseRate implements PricingStrategy {
nightlyRate(room: Room): number { return room.baseRate; }
}
class WeekendSurcharge implements PricingStrategy {
constructor(private readonly inner: PricingStrategy, private readonly percent: number) {}
nightlyRate(room: Room, night: number): number {
const rate = this.inner.nightlyRate(room, night);
const wd = weekday(night);
return wd === 5 || wd === 6 ? Math.floor(rate * (100 + this.percent) / 100) : rate; // Fri, Sat
}
}
class SeasonalRate implements PricingStrategy {
constructor(private readonly inner: PricingStrategy, private readonly season: DateRange,
private readonly percent: number) {}
nightlyRate(room: Room, night: number): number {
const rate = this.inner.nightlyRate(room, night);
return this.season.contains(night) ? Math.floor(rate * (100 + this.percent) / 100) : rate;
}
}
const quote = (p: PricingStrategy, room: Room, stay: DateRange): number =>
stay.nights().reduce((sum, n) => sum + p.nightlyRate(room, n), 0);
// ---------- allocation (Strategy) ----------
interface AllocationStrategy { rank(rooms: Room[]): Room[]; }
class CheapestFirst implements AllocationStrategy {
rank(rooms: Room[]): Room[] {
return [...rooms].sort((a, b) => a.baseRate - b.baseRate || a.num.localeCompare(b.num));
}
}
class LowestFloorFirst implements AllocationStrategy {
rank(rooms: Room[]): Room[] {
return [...rooms].sort((a, b) => a.floor - b.floor || a.num.localeCompare(b.num));
}
}
interface Invoice { roomTotal: number; extrasTotal: number; tax: number; total: number; }
class HotelService {
static readonly HOLD_TTL_MS = 10 * 60_000;
readonly rooms: Room[] = [];
readonly bookings = new Map<string, Booking>();
private nextId = 1;
constructor(public pricing: PricingStrategy = new BaseRate(),
private readonly allocation: AllocationStrategy = new CheapestFirst(),
protected readonly clock: () => number = () => Date.now(),
private readonly taxPercent = 18) {}
addRoom(room: Room): void { this.rooms.push(room); }
/** A snapshot. It can be stale by the time the guest clicks Book, so hold() re-checks. */
search(stay: DateRange, type?: RoomType): Room[] {
const now = this.clock();
return this.allocation.rank(this.rooms).filter(r =>
(type === undefined || r.type === type) &&
r.housekeeping !== Housekeeping.OUT_OF_ORDER && r.isFree(stay, now));
}
hold(guest: Guest, type: RoomType, stay: DateRange): Booking {
const now = this.clock();
for (const room of this.allocation.rank(this.rooms.filter(r => r.type === type))) {
const b = new Booking(`B${this.nextId++}`, guest, room, stay,
quote(this.pricing, room, stay), now + HotelService.HOLD_TTL_MS);
if (room.tryReserve(b, now)) {
this.bookings.set(b.id, b);
return b;
}
}
throw new BookingError(`no ${type} room free`);
}
get(id: string): Booking {
const b = this.bookings.get(id);
if (!b) throw new BookingError(`unknown booking ${id}`);
return b;
}
confirm(id: string): Booking {
const b = this.get(id);
if (b.status === BookingStatus.HELD && this.clock() >= b.holdExpiresAt) {
b.moveTo(BookingStatus.EXPIRED);
throw new BookingError("hold expired");
}
b.moveTo(BookingStatus.CONFIRMED);
return b;
}
cancel(id: string): void { this.get(id).moveTo(BookingStatus.CANCELLED); }
checkIn(id: string, today: number): Room {
const b = this.get(id);
if (!b.stay.contains(today)) throw new BookingError("check-in only during the stay");
if (b.room.housekeeping !== Housekeeping.CLEAN) throw new BookingError(`room ${b.room.num} is not ready`);
b.moveTo(BookingStatus.CHECKED_IN);
return b.room;
}
addCharge(id: string, amount: number): void {
const b = this.get(id);
if (b.status !== BookingStatus.CHECKED_IN) throw new BookingError("charges only while checked in");
b.extras.push(amount);
}
checkOut(id: string): Invoice {
const b = this.get(id);
b.moveTo(BookingStatus.CHECKED_OUT);
b.room.housekeeping = Housekeeping.DIRTY;
const extrasTotal = b.extras.reduce((s, x) => s + x, 0);
const tax = Math.floor((b.price + extrasTotal) * this.taxPercent / 100);
return { roomTotal: b.price, extrasTotal, tax, total: b.price + extrasTotal + tax };
}
markClean(room: Room): void { room.housekeeping = Housekeeping.CLEAN; }
markNoShows(today: number): number {
let count = 0;
for (const b of this.bookings.values()) {
if (b.status === BookingStatus.CONFIRMED && b.stay.checkIn < today) {
b.moveTo(BookingStatus.NO_SHOW);
count++;
}
}
return count;
}
}
// ---------- self-check ----------
function assert(cond: unknown, msg = "assertion failed"): asserts cond {
if (!cond) throw new Error(msg);
}
function expectFail(fn: () => unknown, why: string): void {
try { fn(); } catch (e) { if (e instanceof BookingError) return; throw e; }
throw new Error(why);
}
async function main(): Promise<void> {
let now = Date.UTC(2026, 2, 1, 12);
const hotel = new HotelService(new WeekendSurcharge(new BaseRate(), 20), new CheapestFirst(), () => now);
const r101 = new Room("101", RoomType.DELUXE, 1, 500_00);
const r201 = new Room("201", RoomType.DELUXE, 2, 450_00);
hotel.addRoom(r101); hotel.addRoom(r201);
const alice = new Guest("g1", "Alice"), bob = new Guest("g2", "Bob"), carol = new Guest("g3", "Carol");
const mar20to23 = DateRange.of("2026-03-20", "2026-03-23");
assert(!mar20to23.overlaps(DateRange.of("2026-03-23", "2026-03-25")), "back-to-back must not overlap");
assert(mar20to23.overlaps(DateRange.of("2026-03-22", "2026-03-24")));
const a = hotel.hold(alice, RoomType.DELUXE, mar20to23);
assert(a.room === r201 && a.price === 540_00 * 2 + 450_00, `price ${a.price}`);
hotel.confirm(a.id);
const b = hotel.hold(bob, RoomType.DELUXE, mar20to23);
assert(b.room === r101);
expectFail(() => hotel.hold(carol, RoomType.DELUXE, DateRange.of("2026-03-22", "2026-03-24")), "overbooked");
assert(hotel.hold(carol, RoomType.DELUXE, DateRange.of("2026-03-23", "2026-03-25")).room === r201);
now += 11 * 60_000;
const c = hotel.hold(carol, RoomType.DELUXE, mar20to23);
assert(c.room === r101);
expectFail(() => hotel.confirm(b.id), "expired hold confirmed");
assert(b.status === BookingStatus.EXPIRED);
expectFail(() => hotel.checkOut(a.id), "checked out without checking in");
hotel.checkIn(a.id, day("2026-03-20"));
hotel.addCharge(a.id, 25_00);
const inv = hotel.checkOut(a.id);
assert(inv.roomTotal === 1530_00 && inv.extrasTotal === 25_00 && inv.tax === 279_90 && inv.total === 1834_90);
assert(r201.housekeeping === Housekeeping.DIRTY);
const later = hotel.hold(alice, RoomType.DELUXE, DateRange.of("2026-04-01", "2026-04-02"));
hotel.confirm(later.id);
expectFail(() => hotel.checkIn(later.id, day("2026-04-01")), "checked into a dirty room");
hotel.markClean(later.room);
hotel.checkIn(later.id, day("2026-04-01"));
hotel.confirm(c.id);
hotel.cancel(c.id);
assert(hotel.search(mar20to23, RoomType.DELUXE).includes(r101));
// concurrency: 50 async callers interleave at an await, exactly one gets the suite
const h2 = new HotelService(new BaseRate(), new CheapestFirst(), () => now);
h2.addRoom(new Room("901", RoomType.SUITE, 9, 900_00));
const results = await Promise.all(Array.from({ length: 50 }, async (_, i) => {
await Promise.resolve(); // yield, like a real request handler would
try { return h2.hold(new Guest(`t${i}`, "T"), RoomType.SUITE, mar20to23); } catch { return null; }
}));
assert(results.filter(r => r !== null).length === 1);
console.log("hotel.ts: all assertions passed");
}
main();
Walking through the important decisions
DateRange validates itself. The constructor refuses checkOut <= checkIn, so every other method can assume a non-empty stay. overlaps is the one-line half-open test from earlier, and nights() lists the nights for pricing. In Java, LocalDate.datesUntil already excludes the end date, which is exactly the half-open behaviour we want.
Room.tryReserve is the heart of the design. It's the only method that adds to a room's calendar, and it does the check and the append under the same lock. In Java the lock is the room's monitor (synchronized), in Python an explicit threading.Lock, and in TypeScript the absence of any await between the check and the push. Every other piece of the system can be wrong about availability (search can be stale, the allocation ranking can be stale) without causing an overbooking, because the final word belongs to this method.
hold loops over candidates. It ranks the rooms of the requested type, builds a booking for the first, and calls tryReserve. If that fails, because the room was taken between ranking and reserving, it moves to the next room. This is optimistic concurrency in miniature. We don't lock the whole hotel to decide which room to give, we just try, and accept that a try can fail. The price is quoted per room inside the loop, because rooms of the same type can have different base rates.
Booking.blocks(now) answers "does this booking occupy its nights?" Held bookings block until their expiry, confirmed and checked-in ones always block, and terminal ones never do. Because isFree filters through blocks, cancelling, expiring, no-shows and early check-outs all free the room with no extra code.
moveTo enforces the transition table. checkOut on a confirmed booking throws illegal transition CONFIRMED -> CHECKED_OUT, which is exactly the message you want in a log at 3 a.m.
Every mutation of a booking takes its room's lock. confirm, cancel, checkIn, addCharge and checkOut all lock b.room. That gives one lock per room protecting both the calendar and the statuses of the bookings in it, so "is this booking still blocking?" and "change its status" can never interleave.
The clock is a constructor argument. The self-check advances a fake clock by 11 minutes to expire a hold instead of sleeping. The same trick tests no-shows and check-in windows. See designing for testability.
What's deliberately missing. There's no persistence, no payment call, no guest profile beyond a name, and no partial refunds. Each is a sentence in the interview, not code.
Concurrency
A hotel takes bookings from the front desk, its own website, and channel managers that resell rooms on travel sites, all at once. "Prevent double booking" is the concurrency requirement interviewers care about most, and the one the first version got wrong.
What's shared
| State | Who reads it | Who writes it | Protected by |
|---|---|---|---|
| A room's calendar (its list of bookings) | search, hold, changeDates, occupancy | tryReserve | The room's lock |
| A booking's status, stay and price | isFree (through blocks) | confirm, cancel, checkIn, checkOut, markNoShows | The lock of the booking's room |
| A room's housekeeping state | tryReserve, checkIn, search | checkOut, markClean | The room's lock |
| The booking registry (id to booking) | every lookup | hold | ConcurrentHashMap in Java, a small registry lock in Python, nothing in TypeScript (single-threaded) |
| The booking id counter | hold | hold | AtomicLong, the registry lock, or plain increment in TypeScript |
| The pricing strategy | quotes | an admin swapping rules at runtime | volatile in Java, so readers see the new stack |
The race, precisely
The first version did this:
available = search(dates, type) # step 1: check
if available is empty: fail
store(new reservation) # step 2: act
Two requests for the last room can both finish step 1 before either does step 2. Both see one free room and both store a reservation. This is the classic check-then-act race, and no amount of care in the check fixes it, because the problem is the gap between the check and the act. The fix is to make check-and-act one atomic operation, which is what tryReserve does:
lock(room)
if no live booking on this room overlaps the stay: append booking, return true
else return false
unlock(room)
Why a lock per room, and not one for the whole hotel
A single hotel-wide lock is a perfectly good first answer. It's obviously correct, and a hotel's booking rate is small: even a busy property takes a few bookings a second. Say so, and offer per-room locking as the refinement:
- Per-room locks let unrelated bookings proceed in parallel. A suite booking doesn't wait for a single-room booking.
- They can't deadlock in this design, because no operation ever holds two room locks at once.
holdtries rooms one at a time and releases each lock before trying the next. - The invariant is per room anyway. "No two live bookings overlap" only ever relates bookings on the same room, so the room is the natural unit of locking.
If you add an operation that needs two rooms (moving a guest from 201 to 305 atomically), take both locks in a fixed global order, such as by room number, so two opposite moves can't deadlock.
Search is deliberately unlocked
search reads calendars without coordinating with writers, so its answer can be stale by the time the guest clicks "Book". That's fine, because the result is advisory and hold re-checks under the lock. Locking search would make the read path slower and still wouldn't help: the guest takes seconds to decide, and no lock should be held across a human. In Java, isFree is synchronized so each per-room read sees a consistent list. In Python, iterating a list while another thread appends is safe in CPython but may or may not include the newest booking, which is the same staleness we've already accepted.
Holds instead of locks across payment
Payment can take seconds and can fail. Holding a lock while waiting for a payment gateway would serialise every booking in the hotel behind the slowest card. Instead, the hold is the reservation: a booking in HELD status that blocks the nights for 10 minutes. Payment happens with no locks held, and confirm takes the room's lock only to check the expiry and flip the status. Two consequences to mention:
- Confirm and expiry can't interleave.
confirmreads the clock and changes the status under the same lock thatisFreeuses, so the room can't be handed to someone else halfway through a confirm. - A payment that succeeds after the hold lapsed must be refunded.
confirmthrowshold expiredand the caller refunds. Making the gateway call idempotent (with an idempotency key per booking) means a retried confirm never charges twice.
Python and the GIL
The GIL doesn't make if free: append atomic. A thread can be switched out between the check and the append, which is exactly the race above. The window is narrow, so the race is rare and hard to see: when we removed the lock from try_reserve, the 50-thread test still passed in three runs out of three. Add a time.sleep(0.001) between the check and the append (standing in for any real work, a log line or a metrics call) and all 50 threads "won" the same room in three runs out of three. A test that passes doesn't prove the absence of a race. That's why the lock is there by reasoning, and the test only guards against regressions. Locks are still needed in Python.
TypeScript and the event loop
Node runs JavaScript on one thread, so a synchronous function can't be interrupted. tryReserve contains no await, so it's atomic with respect to every other request in the process. The danger in TypeScript is an await between the check and the act:
// broken: another request can run while we wait for the price service
if (room.isFree(stay, now)) {
const price = await pricingService.quote(room, stay); // other handlers run here
room.bookings.push(new Booking(/* ... */ price)); // the room may no longer be free
}
The fix is the same as everywhere else: do any slow work first, then check and insert in one synchronous step. And once you run more than one Node process, in-process atomicity is gone, and the database has to enforce the invariant.
When the state lives in a database
In production the calendar is a table, and the same invariant can be enforced there. In rough order of preference:
- An exclusion constraint (PostgreSQL):
EXCLUDE USING gist (room_id WITH =, stay WITH &&)on adaterangecolumn, with thebtree_gistextension for the equality part. The database rejects any overlapping insert, whatever the application does. - A room-night table with a unique key on
(room_id, night). A booking inserts one row per night in a transaction, and a duplicate-key error means someone else got a night first. - Pessimistic locking:
SELECT ... FROM rooms WHERE id = ? FOR UPDATE, then check overlaps and insert in the same transaction. This is the direct translation oftryReserve. - Optimistic locking: a
versioncolumn on the room, incremented on every booking, with the insert conditional on the version being unchanged. Retry on conflict.
The in-memory design maps onto any of them: the room's lock becomes the row lock or the constraint, and the hold TTL becomes an expires_at column that availability queries filter on. Booking and inventory concurrency compares these options in depth, and thread-safe class design covers the coarse-versus-fine locking trade-off in general.
Extensions: "The Interviewer Adds…"
With ten minutes left, the interviewer usually adds a requirement to see whether the design bends or breaks. Here are three common ones. All three are added in a subclass HotelServiceV2 plus one new pricing decorator, without editing a line of the booking core, which is the point you want to make out loud. The code is below, after the three explanations, and was run against the complete implementation above.
1. "Guests can change their dates"
The naive version cancels the booking and makes a new one. That's wrong in two ways: between the cancel and the new hold, another guest can take the room, and if the new dates aren't available the guest has lost their original booking too.
The correct version changes the dates atomically on the same room: under the room's lock, check that the new range is free ignoring this booking's own nights (otherwise moving a stay one day later would conflict with itself), then swap the range and re-quote. The ignore parameter on isFree exists for exactly this. If the room isn't free for the new dates, the booking is left untouched. A fuller version would then try other rooms of the same type, taking both room locks in room-number order.
2. "If the room type is sold out, upgrade the guest"
Hotels upgrade rather than turn guests away, at the price of the type they asked for. holdWithUpgrade quotes the requested type first, then walks the types from the requested one upward, calling the ordinary hold for each. The first success wins, and its price is capped at the original quote. Because it reuses hold, it inherits the same concurrency guarantees for free. Note what didn't change: the room, the lock and the overlap test.
3. "Prices go up when the hotel is nearly full"
Occupancy-based pricing is another decorator. OccupancySurge wraps any pricing strategy and adds a surcharge on nights where occupancy is at or above a threshold. It takes occupancy as a function, so it doesn't depend on the hotel class at all, and the hotel passes in its own occupancy(night) method. The pricing stack becomes OccupancySurge(WeekendSurcharge(SeasonalRate(BaseRate))), assembled at start-up or swapped at runtime.
A subtle point about dynamic prices
A quote is a snapshot of a price that can change. The booking stores the price at hold time (booking.price), and that's what the guest pays, even if occupancy rises a minute later. Never recompute a confirmed booking's price from the live pricing stack.
/** Extension 3: decorate any pricing with a surcharge on nights above an occupancy threshold. */
static class OccupancySurge implements PricingStrategy {
private final PricingStrategy inner;
private final java.util.function.Function<LocalDate, Double> occupancy;
private final double threshold; private final int percent;
OccupancySurge(PricingStrategy inner, java.util.function.Function<LocalDate, Double> occupancy,
double threshold, int percent) {
this.inner = inner; this.occupancy = occupancy; this.threshold = threshold; this.percent = percent;
}
public long nightlyRate(Room room, LocalDate night) {
long rate = inner.nightlyRate(room, night);
return occupancy.apply(night) >= threshold ? rate * (100 + percent) / 100 : rate;
}
}
static class HotelServiceV2 extends HotelService {
HotelServiceV2(PricingStrategy p, AllocationStrategy a, Supplier<Instant> clock, int tax) {
super(p, a, clock, tax);
}
/** Extension 1: move a booking to new dates on the same room, atomically. */
Booking changeDates(String id, DateRange newStay) {
Booking b = get(id);
synchronized (b.room) {
if (b.status != BookingStatus.HELD && b.status != BookingStatus.CONFIRMED)
throw new BookingException("only bookings that have not started can change dates");
if (!b.room.isFree(newStay, clock.get(), b)) // ignore its own old nights
throw new BookingException("room " + b.room.number + " is not free for the new dates");
b.stay = newStay;
b.price = quote(pricing, b.room, newStay);
}
return b;
}
/** Extension 2: if the requested type is sold out, give the next type up at the requested price. */
Booking holdWithUpgrade(Guest guest, RoomType type, DateRange stay) {
long quoted = rooms.stream().filter(r -> r.type == type)
.mapToLong(r -> quote(pricing, r, stay)).min()
.orElseThrow(() -> new BookingException("hotel has no " + type + " rooms"));
for (RoomType t : RoomType.values()) { // enum order = SINGLE < ... < SUITE
if (t.ordinal() < type.ordinal()) continue;
Booking b;
try { b = hold(guest, t, stay); } catch (BookingException soldOut) { continue; }
synchronized (b.room) { b.price = Math.min(b.price, quoted); } // never costs more
return b;
}
throw new BookingException("sold out, even with upgrades");
}
double occupancy(LocalDate night) {
DateRange oneNight = new DateRange(night, night.plusDays(1));
Instant now = clock.get();
long taken = rooms.stream().filter(r -> !r.isFree(oneNight, now, null)).count();
return rooms.isEmpty() ? 0 : (double) taken / rooms.size();
}
}
class OccupancySurge:
"""Extension 3: decorate any pricing with a surcharge on nights above an occupancy threshold."""
def __init__(self, inner: PricingStrategy, occupancy: Callable[[date], float],
threshold: float = 0.8, percent: int = 25):
self.inner, self.occupancy = inner, occupancy
self.threshold, self.percent = threshold, percent
def nightly_rate(self, room: Room, night: date) -> int:
rate = self.inner.nightly_rate(room, night)
return rate * (100 + self.percent) // 100 if self.occupancy(night) >= self.threshold else rate
class HotelServiceV2(HotelService):
def change_dates(self, booking_id: str, new_stay: DateRange) -> Booking:
"""Extension 1: move a booking to new dates on the same room, atomically."""
b = self._get(booking_id)
with b.room.lock:
if b.status not in (S.HELD, S.CONFIRMED):
raise BookingError("only bookings that have not started can change dates")
if not b.room.is_free(new_stay, self.clock(), ignore=b): # ignore its own old nights
raise BookingError(f"room {b.room.number} is not free for the new dates")
b.stay = new_stay
b.price = quote(self.pricing, b.room, new_stay)
return b
def hold_with_upgrade(self, guest: Guest, room_type: RoomType, stay: DateRange) -> Booking:
"""Extension 2: if the requested type is sold out, give the next type up at the requested price."""
requested = [r for r in self.rooms if r.type is room_type]
if not requested:
raise BookingError(f"hotel has no {room_type.name} rooms")
quoted = min(quote(self.pricing, r, stay) for r in requested)
for t in sorted(RoomType, key=lambda t: t.value):
if t.value < room_type.value:
continue
try:
b = self.hold(guest, t, stay)
except BookingError:
continue
with b.room.lock:
b.price = min(b.price, quoted) # an upgrade never costs the guest more
return b
raise BookingError("sold out, even with upgrades")
def occupancy(self, night: date) -> float:
one_night = DateRange(night, night + timedelta(days=1))
now = self.clock()
taken = sum(1 for r in self.rooms if not r.is_free(one_night, now))
return taken / len(self.rooms) if self.rooms else 0.0
/** Extension 3: decorate any pricing with a surcharge on nights above an occupancy threshold. */
class OccupancySurge implements PricingStrategy {
constructor(private readonly inner: PricingStrategy, private readonly occupancy: (night: number) => number,
private readonly threshold = 0.8, private readonly percent = 25) {}
nightlyRate(room: Room, night: number): number {
const rate = this.inner.nightlyRate(room, night);
return this.occupancy(night) >= this.threshold ? Math.floor(rate * (100 + this.percent) / 100) : rate;
}
}
const TYPE_ORDER = [RoomType.SINGLE, RoomType.DOUBLE, RoomType.DELUXE, RoomType.SUITE];
class HotelServiceV2 extends HotelService {
/** Extension 1: move a booking to new dates on the same room, atomically (no await inside). */
changeDates(id: string, newStay: DateRange): Booking {
const b = this.get(id);
if (b.status !== BookingStatus.HELD && b.status !== BookingStatus.CONFIRMED)
throw new BookingError("only bookings that have not started can change dates");
if (!b.room.isFree(newStay, this.clock(), b)) // ignore its own old nights
throw new BookingError(`room ${b.room.num} is not free for the new dates`);
b.stay = newStay;
b.price = quote(this.pricing, b.room, newStay);
return b;
}
/** Extension 2: if the requested type is sold out, give the next type up at the requested price. */
holdWithUpgrade(guest: Guest, type: RoomType, stay: DateRange): Booking {
const requested = this.rooms.filter(r => r.type === type);
if (requested.length === 0) throw new BookingError(`hotel has no ${type} rooms`);
const quoted = Math.min(...requested.map(r => quote(this.pricing, r, stay)));
for (const t of TYPE_ORDER.slice(TYPE_ORDER.indexOf(type))) {
let b: Booking;
try { b = this.hold(guest, t, stay); } catch { continue; }
b.price = Math.min(b.price, quoted); // an upgrade never costs the guest more
return b;
}
throw new BookingError("sold out, even with upgrades");
}
occupancy(night: number): number {
const oneNight = new DateRange(night, night + 1);
const now = this.clock();
const taken = this.rooms.filter(r => !r.isFree(oneNight, now)).length;
return this.rooms.length ? taken / this.rooms.length : 0;
}
}
Testing
The self-checks at the bottom of each implementation are the test suite in miniature. In a real codebase you'd split them into named unit tests. The cases worth having, and the bug each one catches:
| Test | What it catches |
|---|---|
| Back-to-back stays (20–23 and 23–25) don't overlap | <= instead of < in the overlap test |
| A stay sharing one night does overlap | < on the wrong side, or comparing only start dates |
| Same room, same dates, second hold fails | Missing overlap check: the first version's bug |
| Same type, different room has space, second hold succeeds on the other room | Allocation that gives up after the first candidate |
| Quote for Fri, Sat, Sun nights = 540 + 540 + 450 | Counting the check-out day as a night. Weekday off-by-one |
| Hold lapses after 10 minutes on a fake clock, room becomes bookable, late confirm throws | Expiry that depends on a background thread. Confirm that ignores the TTL |
checkOut on a CONFIRMED booking throws | Missing transition checks |
Check-in into a dirty room throws, succeeds after markClean | Housekeeping state ignored |
| Cancelled booking frees its nights | Status changes that don't affect availability |
| Invoice totals in integer cents | Floating-point drift, double-taxing extras |
| 50 threads race for one room, exactly one wins | Check-then-act races |
Testing the concurrency, honestly
The race test starts 50 threads behind a barrier (Python) or a latch (Java) so they hit hold as close to simultaneously as possible, then asserts exactly one success. Two caveats to say aloud:
- A passing race test is weak evidence. As the concurrency section showed, removing the lock didn't make the Python test fail until we widened the window. Correctness comes from the design (one lock around check-and-insert), and the test is a regression guard.
- Assert on the invariant, not the winner. Which thread wins is non-deterministic. What must hold is "exactly one booking exists for that room and those nights".
In TypeScript the equivalent test fires 50 async callers that each await once before calling hold, so they interleave on the event loop. It verifies there's no await inside the critical section.
Testing the extensions
The extension code was run with this Python self-check appended (the Java and TypeScript versions assert the same things):
if __name__ == "__main__":
clock = lambda: datetime(2026, 3, 1, 12, 0)
h = HotelServiceV2(clock=clock)
rooms = [Room("101", RoomType.DOUBLE, 1, 200_00), Room("102", RoomType.DOUBLE, 1, 200_00),
Room("301", RoomType.SUITE, 3, 600_00)]
for r in rooms:
h.add_room(r)
g = Guest("g", "G")
s1 = DateRange(date(2026, 5, 4), date(2026, 5, 6)) # Mon, Tue nights
# change dates: blocked by another guest, allowed into its own old nights
x = h.hold(g, RoomType.DOUBLE, s1)
y = h.hold(g, RoomType.DOUBLE, DateRange(date(2026, 5, 6), date(2026, 5, 8)))
assert x.room is rooms[0] and y.room is rooms[0] # back-to-back on room 101
assert h.hold(g, RoomType.DOUBLE, DateRange(date(2026, 5, 6), date(2026, 5, 7))).room is rooms[1]
try:
h.change_dates(x.id, DateRange(date(2026, 5, 5), date(2026, 5, 7)))
raise AssertionError("moved onto someone else's night")
except BookingError:
pass
h.change_dates(x.id, DateRange(date(2026, 5, 3), date(2026, 5, 5))) # overlaps only itself
assert x.stay.check_in == date(2026, 5, 3) and x.price == 400_00
# upgrade: both doubles taken on May 6, so the guest gets the suite at the double price
up = h.hold_with_upgrade(g, RoomType.DOUBLE, DateRange(date(2026, 5, 6), date(2026, 5, 7)))
assert up.room is rooms[2] and up.price == 200_00
# occupancy surge: May 6 is 3/3 full, May 10 is empty
h.pricing = OccupancySurge(BaseRate(), h.occupancy, threshold=0.8, percent=25)
assert h.occupancy(date(2026, 5, 6)) == 1.0
assert quote(h.pricing, rooms[0], DateRange(date(2026, 5, 6), date(2026, 5, 7))) == 250_00
assert quote(h.pricing, rooms[0], DateRange(date(2026, 5, 10), date(2026, 5, 11))) == 200_00
print("ext.py: all assertions passed")
Common Mistakes
- A single status field on the room.
room.status = RESERVEDcan't express "reserved on the 21st, free on the 25th". Availability is a property of a room and a date range, so it has to be computed from bookings. The first version'sRoomStatus.RESERVEDis the tell. - Closed intervals. Treating check-out as a night, or testing overlap with
<=, either refuses every back-to-back stay or counts one night too many. Say "half-open" in the interview and write the test case for back-to-back stays. - Checking availability, then booking, in two steps. The check-then-act race. The check and the insert have to be one atomic step on whatever holds the truth: an object lock in memory, a constraint or row lock in a database.
- Locking across user think-time or payment. Holding a lock while the guest types their card number serialises the hotel. Use a hold with a TTL instead.
- A background thread as the only thing that expires holds. If the sweeper is late or dies, rooms stay blocked. Lazy expiry (a stale hold simply doesn't count) makes correctness independent of the sweeper.
- Status changes scattered through the code.
booking.status = CANCELLEDin five places means one of them will cancel a checked-out stay. Route every change through one transition table. - Deleting cancelled bookings. You lose the audit trail and the no-show and cancellation statistics. Keep them, and let the status decide whether they block.
- Floats for money. Use integer minor units or a decimal type, and round once.
- Pricing per stay instead of per night. A weekend surcharge, a seasonal rate or a mid-stay price change all need the nightly view. Quote = sum of nightly rates.
- Recomputing the price at check-out from current rules. The guest pays what they were quoted. Store the price on the booking.
new Date()inside business logic. Untestable expiry and no-show logic. Inject a clock.- Over-patterning. A
RoomFactory, aBookingBuilder, anObserverbus and aRepositoryinterface in a 45-minute round leave no time for the overlap test and the lock, which are what's being graded. See common LLD mistakes.
Interview Follow-ups
Q: Why assign a concrete room at booking time? Real hotels assign rooms at check-in. Both work, and it's a good trade-off to discuss. Assigning at booking makes the invariant local and simple: a room's own calendar can't overlap, checked under one lock. Assigning at check-in (type-level inventory) is more flexible: the hotel can reshuffle guests to avoid fragmentation and handle late room changes. It needs a per-type, per-night counter that must never exceed the number of rooms of that type, checked atomically across all the nights of the stay. There's a nice theorem behind it: for intervals, if no night exceeds the room count, a valid room assignment always exists, and assigning greedily by check-in date finds it (interval graphs need exactly as many "colours" as their maximum overlap). So counting per night is sufficient.
Q: Can pre-assigning rooms turn away a guest who could have fitted? Yes, that's fragmentation. Suppose room 101 holds the nights of the 1st and 3rd for two short stays, and room 102 holds the 2nd. A guest asking for the 1st to the 4th is refused, though every night has a free room. Moving the 2nd-night stay into 101 would make room for them. Fixes: assign at check-in, or run a re-packing step over not-yet-checked-in bookings when a request fails. Mention it, and don't build it unless asked.
Q: What if the interviewer wants deliberate overbooking, like airlines? Then the invariant changes from "live bookings on a type per night ≤ rooms" to "≤ rooms × (1 + allowance)", using type-level inventory, plus a policy for when more guests arrive than rooms exist: upgrade, then "walk" the guest to a partner hotel at the hotel's cost. The allowance comes from the historical no-show rate. It only makes sense with type-level inventory, because you can't put two bookings on the same room's calendar on purpose.
Q: How does search scale to a year of bookings and 500 rooms? Prune history first: bookings that ended before today can't overlap anything you'd search for. Then keep each room's bookings sorted by check-in and binary-search, which makes each room check O(log k). For a hotel that's enough. For a multi-hotel search engine you'd precompute availability per type per night, so a search becomes "is the minimum free count over these nights ≥ 1?", a range-minimum query.
Q: How do you notify housekeeping, send confirmation emails and update the channel manager?
Observer. HotelService publishes events (BookingConfirmed, GuestCheckedOut, BookingCancelled) to registered listeners: housekeeping creates a cleaning task, the mailer sends an email, the channel sync pushes the new availability. Publish after releasing the room lock, so a slow email server can't block bookings. In production the events go to a queue, and listeners are idempotent because queues deliver at least once. See Observer and the notification service case study.
Q: How would you implement cancellation fees?
A CancellationPolicy strategy: refund(booking, now) -> amount. "Free until 48 hours before check-in, then one night's charge" is one implementation, "non-refundable" another. The policy is chosen per rate plan at booking time and stored on the booking, so changing the hotel's policy later doesn't change existing bookings' terms.
Q: Two receptionists check out the same guest at the same moment. What happens?
The second call hits moveTo(CHECKED_OUT) from CHECKED_OUT, which isn't a legal transition, and throws. Both calls hold the room's lock while they transition, so they're serialised and exactly one invoice is produced. If the UI must be idempotent instead of erroring, have checkOut return the existing invoice when the booking is already checked out.
Q: What about the night audit, when the day rolls over?
A scheduled job at the hotel's rollover time: markNoShows(today) moves confirmed bookings whose check-in day has passed to NO_SHOW (and charges the no-show fee per policy), posts the night's room charges for in-house guests, and sweeps expired holds for reporting. It takes the same per-room locks as everything else, one room at a time.
Q: How would this change for a hotel chain?
One HotelService per property (another reason not to make it a Singleton), with a thin search layer on top that fans out by city and dates. Bookings never span properties, so the locking story doesn't change. The interesting new problems are distributed (a shared guest profile, loyalty points, a central reservation system) and belong in a system design round.
Q: Isn't a room-level lock overkill for a single hotel?
Possibly, and saying so is a good signal. A single lock around hold, confirm and friends would be correct and fast enough for one property. Per-room locks are the refinement you offer when asked about throughput, and they come with no deadlock risk because no operation holds two at once.
Q: How is this different from movie seat booking? A movie seat is booked for one show, a point in time, so availability is a set membership test on (show, seat). A hotel room is booked for a range of nights, so availability is an interval-overlap test, and two bookings for the same room can coexist if their ranges don't touch. The hold-and-confirm flow and the locking are the same. Compare with movie booking, and see meeting room booking and car rental for the same interval problem in different clothes.
Further Reading
- LLD Interviews Overview — SOLID principles and patterns
- Design Movie Ticket Booking — similar booking patterns with seat locking
- Design ATM Machine — state machine for sequential flows
- Design Meeting Room Booking: the same interval-overlap problem, with time slots instead of nights
- Design Car Rental: date-range inventory plus vehicle pickup and return
- Strategy pattern and Decorator pattern: the pricing and allocation stacks
- State pattern: when to use per-state classes instead of a transition table
- The LLD interview framework: the 45-minute route this page follows