Notes
Requirements
Fix the scope. Hotels sit in many cities and have room types like standard and deluxe. A guest searches by city, dates and number of guests, then holds a room while paying; the hold expires after ten minutes. Bookings can be confirmed, cancelled and checked in. Prices rise on weekends and in peak season, and the refund depends on the policy chosen. Above all, never sell the same room twice for the same night.
Ask the questions that change the code. Does the guest pick a room number or a type? A type, and we assign a free room. Is the check-out day a night of the stay? No, so a stay is a half-open range. Is the price fixed when the guest pays, or when they hold? At hold time, so the price never jumps mid-checkout. Whose time zone decides the cancellation deadline? The hotel's.
- hotels in many cities
- room types: standard, deluxe
- search by city, dates, guests
- hold a room while paying
- hold expires after 10 minutes
- confirm, cancel, check in
- price changes on weekends
- and in peak season
- refund depends on a policy
- never sell one room twice
- out of scope: reviews, loyalty
- guest books a type or a room?
- a type; we pick the room
- is check-out day a night?
- no: nights are [in, out)
- one room per booking?
- yes, many rooms = many bookings
- price fixed when?
- quoted at hold time
- time zone?
- the hotel's own
Entities
Now the entities. A hotel has many rooms, and each room is of one room type, which holds the name, capacity and base nightly rate. A booking belongs to one room and covers a stay, which is just a check-in and check-out date. Notice that availability is not a class or a table of free nights. It is computed from the bookings on each room, so there is only one source of truth.
Class diagram
Turn them into types. Room type and stay are records, because they never change. A stay validates itself: check-out must be after check-in. The room keeps its own list of bookings and is also the lock that guards them. A booking stores the price quoted at hold time, the cancellation policy chosen, when the hold expires, and a status. Money is a long number of paise.
record RoomType(code, name, capacity,
long baseNightCents)
record Stay(LocalDate checkIn,
LocalDate checkOut)
class Room {
String number; RoomType type;
List<Booking> bookings; // guarded
}
class Booking { id, guest, room, stay,
totalCents, policy, holdExpiresAt,
Status status } Date ranges
The overlap rule is the whole search, so get it exactly right. Treat a stay as half-open: it includes the check-in night and excludes the check-out day. Two stays clash only if each one starts before the other ends. So the eighteenth to the twenty-first clashes with the twentieth to the twenty-second, but not with the twenty-first to the twenty-third. A guest can leave in the morning and a new one arrive that afternoon.
// nights are [checkIn, checkOut)
boolean overlaps(Stay o) {
return checkIn.isBefore(o.checkOut)
&& o.checkIn.isBefore(checkOut);
}
18-21 vs 20-22: overlap
18-21 vs 21-23: no overlap
(same day turnover is allowed) Flow: search
Search walks the hotels in the city, skips rooms that are too small for the party, and checks each room for a blocking booking that overlaps the stay. Free rooms are counted per type and each offer gets a total price. Search is only a read: by the time the guest clicks, the count may have changed. That is fine, because the hold step checks again under a lock. Never trust a search result for correctness.
for each hotel in the city
for each room with capacity ok
free = no blocking booking
overlaps the stay
group by room type: count
total = sum of nightly prices
a read: the count may change
a moment later, so hold()
checks again under the lock Holds
Paying takes minutes: a one-time password, a bank page, a slow network. If we only reserved the room after payment, two guests could pay for the same room and one would need a refund. So booking has two steps. First a hold, which blocks the room until an expiry time ten minutes away. Then confirm, once payment succeeds. If the guest wanders off, the hold simply runs out and the room is free again.
How does a hold expire? Not with a timer per booking. A held booking blocks the room only while the current time is before its expiry, so the moment it passes, search and hold ignore it. A background sweeper later moves stale holds to expired, but correctness never depends on it running on time. The current time comes from an injected clock, so a test moves time forward eleven minutes without sleeping.
- payment takes minutes: OTP,
- bank page, a slow network
- without a hold: two guests pay
- for one room, one gets refunded
- with a hold: the room is
- blocked only until expiresAt
- expiresAt = now + 10 minutes
- confirm after that: rejected,
- please search again
boolean blocks(Instant now) {
return status == CONFIRMED
|| status == CHECKED_IN
|| (status == HELD
&& now.isBefore(holdExpiresAt));
}
expireHolds(): HELD past expiry
moves to EXPIRED (tidy only) State machine
A booking has a small life. Held can become confirmed, expired or cancelled. Confirmed can become cancelled or checked in, and checked in ends as checked out. Expired, cancelled and checked out are final. Each status answers whether a move is allowed, with a switch the compiler checks for every value, and one move method throws on anything else. So nobody can check in a cancelled booking by mistake.
return switch (this) {
case HELD -> next == CONFIRMED
|| next == EXPIRED
|| next == CANCELLED;
case CONFIRMED -> next == CANCELLED
|| next == CHECKED_IN;
case CHECKED_IN -> next == CHECKED_OUT;
case EXPIRED, CANCELLED,
CHECKED_OUT -> false;
}; Flow: hold and confirm
Walk the hold. For each room of the requested type, take that room's lock, check it is free for the stay right now, and if so add a held booking with the quoted price, the chosen cancellation policy and an expiry time. Then return it. If no room is free, throw a clear error. Confirm takes the same room lock: if the hold has already expired it is marked expired and rejected, otherwise it becomes confirmed.
for (Room r : rooms of that type) {
synchronized (r) {
if (!r.isFree(stay, now)) continue;
Booking b = new Booking(.., price,
policy, now.plus(holdFor));
r.bookings.add(b);
return b;
}
}
throw: no room of this type free Concurrency
Now the race. Eight guests click book on the last deluxe room at the same instant. If checking and adding were separate steps, two threads could both see the room free and both add a booking. So the check and the add happen inside one lock on that room. The first thread adds its hold; the others wait a moment, then see the hold and move on. The lock is per room, so bookings for other rooms and hotels never wait.
With many servers, the lock moves into the database. One common design stores a row per room per night with a unique key on room and night, and inserts all nights of a stay in one transaction, so a clash fails the whole insert. Another locks the room row for update, checks overlaps, then inserts. Either way the database, not a hopeful check in code, is what refuses the second booking.
- bad: check free, then add
- two threads both see free,
- both add: room sold twice
- good: check and add inside
- synchronized (room)
- the second thread waits, then
- sees the first hold, moves on
- lock per room: other rooms
- and hotels never wait
- one row per room per night
- unique (room_id, night)
- insert all nights or none
- or: SELECT room FOR UPDATE,
- check overlaps, insert
- or: optimistic version column
- on the room, retry on clash
- holds: expires_at column,
- ignored once it has passed
Strategy: pricing
Pricing is a strategy that prices one night of one room type. The stay total is the sum of its nights, which handles a stay that crosses from weekday into weekend or into a season. Rules stack as decorators of the same interface: a base rate, wrapped by a twenty percent weekend surcharge for Friday and Saturday nights, wrapped by a fifty percent peak season. A festival rate is one more wrapper, with no change to the service.
interface PricingStrategy {
long nightCents(RoomType t, LocalDate n);
}
new Season(new WeekendSurcharge(
new BaseRate(), 20),
20 Dec, 5 Jan, 50)
Fri 18 Dec deluxe: 6,000.00
Sat 19 Dec deluxe: 6,000.00
Sun 20 Dec deluxe: 7,500.00
stay total: 19,500.00 Strategy: refunds
Refunds are another strategy. A flexible policy refunds everything up to forty-eight hours before check-in, half after that, and nothing once check-in time has passed. A non-refundable rate always refunds zero, which is why it is cheaper. The policy object is stored on the booking when it is made, so if the hotel changes its rules next month, existing guests keep the deal they agreed to. Deadlines use the hotel's time zone.
interface CancellationPolicy {
long refundCents(Booking b, Instant now);
}
Flexible:
48h or more before 14:00 check-in: all
less than 48h: half
after check-in time: nothing
NonRefundable: always 0
cancel 28h before: 9,750 of 19,500 Concurrency
Check every shared field. A room's bookings, and the status of each of those bookings, are guarded by the room lock, so search, hold, confirm and cancel all see a consistent picture. Hotels and bookings by id sit in concurrent maps, ids come from an atomic counter, and stays and room types are immutable records. Each operation holds at most one lock at a time, so deadlock is impossible.
- room bookings: guarded by room
- booking status: changed under
- its room lock
- hold: check + add, one lock
- confirm, cancel: same lock
- hotels, bookings: concurrent maps
- ids: AtomicLong
- Stay, RoomType: immutable
- one lock at a time: no deadlock
Extensibility
Now the stretches. Booking three rooms at once means locking several rooms, so lock them in room number order to avoid deadlock, and roll back all holds if one fails. Hotels that overbook slightly get a capacity rule per type. Which room to assign, quiet floor or near the lift, is another strategy. For fast search at scale, keep a count of free rooms per type per night and update it with each booking.
- many rooms in one booking:
- lock rooms in number order
- overbooking a few percent:
- a capacity rule per type
- free upgrade: assign a
- higher type if base is full
- room assignment: a strategy
- notifications: Observer
- faster search: per type count
- of free rooms per night
Testing
The full code is below the player. The demo prices a stay across a weekend and into peak season, holds the deluxe room, moves the fake clock eleven minutes and shows the room free again and the late confirm rejected. Eight threads race for the room and exactly one wins. An overlapping stay is refused while a back to back stay is accepted, and the two cancellation policies refund half and nothing.
Deluxe 18-21 Dec: 1 free, 19,500.00 held B1, then 11 minutes pass: 1 free again; confirm B1 rejected race for 1 deluxe: 1 held, 7 away overlap 20-22 Dec: no room free back to back 21-23 Dec: CONFIRMED cancel flexible, 28h before: refund 9,750.00 of 19,500.00 non-refundable: refund 0.00 cancelled cannot check in
Follow-ups
Expect follow-ups. Why not lock the whole hotel? It is correct, but on a holiday weekend every guest waits in one line. How long should a hold last? Long enough for slow payers, short enough not to block real guests. What if a payment succeeds just after the hold expired? Try to claim the room again, and if it is gone, refund automatically. Which patterns did you use? Strategy, Decorator and a state machine.
- why not lock the whole hotel?
- correct but slow at peak
- hold length? a trade-off:
- too short fails slow payers
- payment succeeds after expiry?
- re-check; free: confirm,
- taken: auto refund
- price changes during a hold?
- the quoted price is kept
- which patterns? Strategy,
- Decorator, State
Say it like this
Here is the short version to say out loud. Rooms own their bookings and the lock that guards them. Stays are half-open date ranges. A hold is a booking that blocks the room only until it expires, so there are no timers to manage. Checking and claiming happen under the room lock, so the last room is sold once. Pricing is per night with stacked rules, and the refund policy is fixed when the guest books.
- "Rooms own their bookings and
- the lock. Stays are half-open
- ranges. A hold is a booking
- that blocks only until it
- expires, so no timers. Check
- and claim under the room lock.
- Pricing is per night, stacked
- as decorators; refund policy
- is fixed at booking time."