LLD

Full Designs

Hotel Booking

A weak answer gives every room a list of bookings and loops over it. We build one that holds up when the interviewer pushes: how a three-night stay gets every night or none while other guests book the same dates, why the room number is chosen at check-in, how weekend and peak rates and refunds come out exact to the cent, and what happens when the bank does not answer.

"Design a hotel booking system" sounds like a list of rooms and a calendar. A weak answer gives each Room a list of bookings, loops over the list to look for a clash, and stops. The classes look right, and the questions that make a hotel different from a cinema or a meeting room are still open.

The interviewer is checking a few specific things. A stay of three nights must get a room on all three nights or on none, while other guests book the same dates. The design must say when a guest gets a room number, and why. Weekend rates, a peak season and the refund on a cancellation must all come out exact to the cent. And the card is charged while the nights are held, so the design must say what happens when the bank says no, or says nothing at all.

This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

A booking at a glance
Asha's phone asks Hotel to book a DELUXE room from 18 to 21 December (1). RatePlan prices each of the three nights (2). The DELUXE RoomTypeInventory takes one room on every night, or on none (3). PaymentGateway charges the card with no lock held (4). On 18 December the front desk checks Asha in (5), and FreeRooms hands out the lowest free DELUXE room, 201 (6). If she cancels instead, CancellationPolicy decides the refund (7).Asha's phone asks Hotel to book a DELUXE room from 18 to 21 December (1). RatePlan prices each of the three nights (2). The DELUXE RoomTypeInventory takes one room on every night, or on none (3). PaymentGateway charges the card with no lock held (4). On 18 December the front desk checks Asha in (5), and FreeRooms hands out the lowest free DELUXE room, 201 (6). If she cancels instead, CancellationPolicy decides the refund (7).
A booking holds a room type on every night. The room number comes at check-in. Asha's phone asks Hotel to book a DELUXE room from 18 to 21 December (1). RatePlan prices each of the three nights (2). The DELUXE RoomTypeInventory takes one room on every night, or on none (3). PaymentGateway charges the card with no lock held (4). On 18 December the front desk checks Asha in (5), and FreeRooms hands out the lowest free DELUXE room, 201 (6). If she cancels instead, CancellationPolicy decides the refund (7).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Does a guest book a room, or a kind of room?A room type. The front desk picks the room at check-inCounts per room type per night, and FreeRooms for check-in
What is a night?The date the guest sleeps there. A stay from the 18th to the 21st is the nights of the 18th, 19th and 20thA Stay that leaves out its departure date
How long, and how far ahead?1 to 30 nights, arriving within the next 365 daysLimits checked in Stay and in book
How is a night priced?A weekday and a weekend rate per room type. Friday and Saturday are weekend nights. A peak season adds 25%A RatePlan interface, asked once per night
When does the guest pay?In full, by card, while bookingbook takes the nights, charges and confirms in one call
What if the bank does not answer?Nobody knows whether the money movedA pending status, and a job that asks the bank later
Can a guest cancel?Yes, before the stay ends. A full refund until 2 days before arrival, then everything except the first nightA CancellationPolicy interface
Can the hotel sell more rooms than it has?NoA night is full at exactly the room count
Do many guests book at once?Yes, often the same room type for the same datesTaking nights must be safe from many threads

The first question matters most. If a booking holds room 201, the design needs a calendar per room, and a new stay must find one room that is free on every night. If a booking holds "one DELUXE room", the design needs only a count per type per night, and the room number can wait until the guest is at the desk. We take the second answer and argue for it in "What a booking holds" below.

Requirements

Functional:

  1. A guest can get a quote for a room type and dates, with one price per night, exact to the cent.
  2. A booking takes one room of its type on every night of the stay, or on none. If any night is full, the booking is refused, and the refusal names that night.
  3. The card is charged in full while booking. If it is declined, every night is given back. If the bank does not answer, the nights stay held until the bank says whether the money moved.
  4. A guest can cancel a confirmed booking before the stay ends. The refund follows the hotel's policy, and the nights go back on sale.
  5. On a day of the stay, the front desk checks the guest in to a free room of the booked type. Check-out frees the room.
  6. No night ever has more rooms of a type sold than the hotel has.

Out of scope: choosing a room number when booking, selling more rooms than exist on purpose, no-show fees, refunds for leaving early, taxes, several hotels, and search. We come back to these at the end, because each is a likely follow-up.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Many bookings at once. book and cancel are called from many threads, often for the same room type and dates.
  • Rules that change. Rates and the refund policy each sit behind an interface.
  • A bank that fails. The card processor can decline, or not answer at all.
  • Testable time. Booking limits, refunds and check-in depend on today's date, so the hotel takes a Clock.

Finding the classes

Picking the nouns out of the requirements gives a first list. Three of them carry state that changes and that several threads touch: the count of rooms sold per night, the rooms free right now, and a booking. They become classes. The rules become interfaces.

From nouns to classes
Hotel, the count of rooms sold per night, the free rooms and the booking become classes. Room, stay and price become records, and room type becomes an enum. The rate, the cancellation rule and the payment become interfaces. Five nouns are dropped. A guest is a name on the booking. The front desk calls Hotel. A key card is hardware. A room's own calendar is not needed, because a booking holds a type. A night is a LocalDate.Hotel, the count of rooms sold per night, the free rooms and the booking become classes. Room, stay and price become records, and room type becomes an enum. The rate, the cancellation rule and the payment become interfaces. Five nouns are dropped. A guest is a name on the booking. The front desk calls Hotel. A key card is hardware. A room's own calendar is not needed, because a booking holds a type. A night is a LocalDate.
Most nouns become classes, records or interfaces. Five do not. Hotel, the count of rooms sold per night, the free rooms and the booking become classes. Room, stay and price become records, and room type becomes an enum. The rate, the cancellation rule and the payment become interfaces. Five nouns are dropped. A guest is a name on the booking. The front desk calls Hotel. A key card is hardware. A room's own calendar is not needed, because a booking holds a type. A night is a LocalDate.
Decision

Should a guest be a class?

A Guest class with a name, contact details and a list of bookings

It mirrors the app's profile screen. But no rule in this design reads anything about a guest except the name on the booking. The list of bookings would be a second copy of what Hotel already keeps.

No: a guest is a name on the bookingOur pick

Booking keeps a guestName for the front desk, and the booking id is what the guest quotes. If a rule ever needs the guest, such as a loyalty discount, a Guest class can come then.

Data or behaviour?

Some classes only carry values that never change: a room, a stay, a quote. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. Booking, RoomTypeInventory and FreeRooms are ordinary classes, because their state changes and their methods guard those changes.

The class diagram

The classes and how they connect
Hotel owns one RoomTypeInventory per room type, one FreeRooms and every Booking. It uses three interfaces: RatePlan, CancellationPolicy and PaymentGateway, and it reads the date from a Clock. The notes under RatePlan and CancellationPolicy name the classes behind them, and PeakSeason wraps another RatePlan. Methods marked ~ are package-private, and only Hotel calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.Hotel owns one RoomTypeInventory per room type, one FreeRooms and every Booking. It uses three interfaces: RatePlan, CancellationPolicy and PaymentGateway, and it reads the date from a Clock. The notes under RatePlan and CancellationPolicy name the classes behind them, and PeakSeason wraps another RatePlan. Methods marked ~ are package-private, and only Hotel calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.
Hotel coordinates. Each piece of shared state has its own class and its own lock. Hotel owns one RoomTypeInventory per room type, one FreeRooms and every Booking. It uses three interfaces: RatePlan, CancellationPolicy and PaymentGateway, and it reads the date from a Clock. The notes under RatePlan and CancellationPolicy name the classes behind them, and PeakSeason wraps another RatePlan. Methods marked ~ are package-private, and only Hotel calls them. The records and enums along the bottom are the values the classes above hold. The three exceptions are not drawn.

The classes fall into three groups:

  • Data: the records Room, Stay and Quote, and the enums RoomType, BookingStatus and PaymentStatus.
  • The core: Hotel, RoomTypeInventory, FreeRooms and Booking. Hotel coordinates. The other three each guard their own state with their own lock.
  • Rules and outside systems: RatePlan, CancellationPolicy and PaymentGateway, all interfaces.

Building it

Stays and nights

A guest who arrives on the 18th and leaves on the 21st sleeps three nights: the 18th, the 19th and the 20th. The departure date is not a night. A Stay holds a room type and the two dates:

stay/Stay.javalines 10–33 of 34
/** A room type from the arrival date up to, but not including, the departure date. */public record Stay(RoomType roomType, LocalDate arrival, LocalDate departure) {    public static final int MAX_NIGHTS = 30;     public Stay {        Objects.requireNonNull(roomType, "roomType");        Objects.requireNonNull(arrival, "arrival");        Objects.requireNonNull(departure, "departure");        if (!departure.isAfter(arrival)) {            throw new IllegalArgumentException("Departure must be after arrival");        }        if (ChronoUnit.DAYS.between(arrival, departure) > MAX_NIGHTS) {            throw new IllegalArgumentException("A stay is at most " + MAX_NIGHTS + " nights");        }    }     public int nightCount() {        return (int) ChronoUnit.DAYS.between(arrival, departure);    }     /** One date per night: the arrival date, and every date before the departure date. */    public List<LocalDate> nights() {        return arrival.datesUntil(departure).toList();    }

The constructor refuses a departure on or before the arrival, and a stay longer than 30 nights. nights() lists every date from the arrival up to, but not including, the departure. This is the same rule the Meeting Room Scheduler uses for a slot's end minute. Here it means a guest leaving on the 18th and a guest arriving on the 18th never need the same night.

What a booking holds

There are two ways to answer "is there a room for me?". The hotel can keep a calendar per room and look for one room that is free on every night. Or it can keep a count per room type per night and give out room numbers later.

Holding a room, or a room type
Two DELUXE rooms, three nights. On the left, rooms are fixed when booking: Ben holds 201 on Wednesday and Chen holds 202 on Tuesday. Asha asks for the nights of Monday to Wednesday. Every night has a room free, but no single room is free on all three, so she is refused. On the right, the hotel keeps only counts: 0, 1 and 1 of 2 sold, so Asha's booking fits. At check-in, Asha gets 201 on Monday, Chen gets 202 on Tuesday, and Ben gets 202 on Wednesday after Chen leaves.Two DELUXE rooms, three nights. On the left, rooms are fixed when booking: Ben holds 201 on Wednesday and Chen holds 202 on Tuesday. Asha asks for the nights of Monday to Wednesday. Every night has a room free, but no single room is free on all three, so she is refused. On the right, the hotel keeps only counts: 0, 1 and 1 of 2 sold, so Asha's booking fits. At check-in, Asha gets 201 on Monday, Chen gets 202 on Tuesday, and Ben gets 202 on Wednesday after Chen leaves.
Fixed rooms can refuse a stay that the counts can fit. Two DELUXE rooms, three nights. On the left, rooms are fixed when booking: Ben holds 201 on Wednesday and Chen holds 202 on Tuesday. Asha asks for the nights of Monday to Wednesday. Every night has a room free, but no single room is free on all three, so she is refused. On the right, the hotel keeps only counts: 0, 1 and 1 of 2 sold, so Asha's booking fits. At check-in, Asha gets 201 on Monday, Chen gets 202 on Tuesday, and Ben gets 202 on Wednesday after Chen leaves.

With fixed rooms, the calendar breaks into short gaps that a longer stay cannot fit into. The hotel either turns Asha away, or moves Chen or Ben to another room, which means solving a puzzle across every booking each time a stay comes in.

With counts, Asha fits. And at check-in, the front desk can give her any free DELUXE room. This always works, as long as guests leaving on a date check out before guests arriving that date check in. On any day, the guests already in a room all stay that night, and so does the guest who has just arrived. The count for that night includes every one of them, and it is never above the number of rooms. So at least one room is free for the new arrival.

Decision

Does a booking hold a room or a room type?

A room, fixed when booking

A guest can be promised room 305 with the sea view. But stays fragment the calendar, as in the figure, so the hotel refuses stays it has room for, or moves guests between rooms. A room that goes out of order also breaks every booking that named it.

A room type; the room is given out at check-inOur pick

A count per type per night is all a booking needs, and checking a stay is one look per night. Any free room of the type works at check-in. The cost is that a guest cannot pick a room number when booking. A wish such as "high floor" would be a note for the front desk to read at check-in.

The guarantee has one condition. If a guest stays past their departure date, the arriving guest can find every room taken. checkIn then refuses with "No DELUXE room is free yet", and the booking stays as it was.

Counting rooms per night

RoomTypeInventory keeps the count. There is one per room type, and each has its own lock:

hotel/RoomTypeInventory.javalines 13–56 of 68
/** How many rooms of one type are sold on each night. Its lock guards every count for that type. */public class RoomTypeInventory {    private final RoomType type;    private final int rooms;    private final Map<LocalDate, Integer> soldByNight = new HashMap<>();     RoomTypeInventory(RoomType type, int rooms) {        this.type = Objects.requireNonNull(type, "type");        if (rooms < 0) {            throw new IllegalArgumentException("A room count cannot be negative");        }        this.rooms = rooms;    }     /** Takes one room on every night of the stay, or on none of them. */    synchronized void reserve(Stay stay) {        List<LocalDate> nights = nightsOf(stay);        for (LocalDate night : nights) {            if (sold(night) >= rooms) {                throw new SoldOutException(type, night);            }        }        for (LocalDate night : nights) {            soldByNight.merge(night, 1, Integer::sum);        }    }     /** Gives back one room on every night of the stay. */    synchronized void release(Stay stay) {        List<LocalDate> nights = nightsOf(stay);        for (LocalDate night : nights) {            if (sold(night) == 0) {                throw new IllegalStateException("Nothing to release on " + night);            }        }        for (LocalDate night : nights) {            soldByNight.merge(night, -1, Integer::sum);            soldByNight.remove(night, 0);        }    }     public synchronized int roomsLeft(LocalDate night) {        return rooms - sold(night);    }

soldByNight maps a date to the number of rooms of this type sold that night. A date that is not in the map has none sold. reserve makes two passes over the nights. The first pass checks every night and throws SoldOutException, naming the first full night, before anything changes. The second pass adds one to every night. Both passes run under the same lock, so nobody can fill a night between the check and the add. release does the same in reverse. roomsLeft takes the lock too, so a reader never reads the map while reserve or release is changing it.

Decision

How do we know a night has a room left?

Look through the bookings for ones that overlap

It needs no extra state, and the Meeting Room Scheduler checks for overlap in one room. Here a night is full only when as many bookings as rooms overlap it, so every check must read every booking of the type, and the work grows with the bookings.

A count of rooms sold, per room type, per nightOur pick

Checking a stay reads one number per night, however many bookings exist. Taking and giving back is one change per night. The cost is that the count and the bookings must agree, so every path that takes nights must give them back on every failure.

Pricing each night

A stay from Friday the 18th to Monday the 21st has two weekend nights and one weekday night. In this demo, the Sunday is also the first night of the December peak season. So a stay cannot be priced as "the rate times the number of nights". Each night needs its own price.

WeekendRates holds two tables of cents, one for weekday nights and one for Friday and Saturday nights:

pricing/WeekendRates.javalines 21–27 of 41
    @Override    public long nightlyCents(RoomType type, LocalDate night) {        Objects.requireNonNull(type, "type");        DayOfWeek day = night.getDayOfWeek();        boolean weekend = day == DayOfWeek.FRIDAY || day == DayOfWeek.SATURDAY;        return weekend ? weekendCents.get(type) : weekdayCents.get(type);    }

A peak season is a rule on top of another rule, so it wraps one:

pricing/PeakSeason.javalines 29–37 of 38
    @Override    public long nightlyCents(RoomType type, LocalDate night) {        long cents = base.nightlyCents(type, night);        if (night.isBefore(from) || !night.isBefore(until)) {            return cents;        }        // Multiply first, then divide once, rounding half a cent up.        return Math.addExact(Math.multiplyExact(cents, percentOfBase), 50) / 100;    }

The season leaves out its until date, like a stay. The constructor refuses a percentage below 100, which would lower prices, and one above 500, which would be a typo. A monsoon discount would be its own class. PeakSeason multiplies first and divides once, adding 50 so that half a cent rounds up. On 20 December, a DELUXE room's $129.99 becomes $162.4875, which rounds to $162.49. Asha's stay is $169.99 + $169.99 + $162.49 = $502.47.

Hotel.quote asks the plan once per night and builds a Quote record with one line per night. The record refuses a night priced at zero or less. It adds up its total with Math.addExact when it is created, so an overflow throws before any night is taken, instead of wrapping round.

Decision

How is a stay priced?

The arrival night's rate, times the number of nights

It is one multiplication. But a guest arriving on a Thursday would pay weekday rates for Friday and Saturday too, and a stay that starts the day before the season would never pay the season's rate.

Night by night, and the lines are kept on the bookingOur pick

Each night gets the rate for that date, so weekends and seasons come out right for any stay. The booking keeps its Quote, so a refund later uses the prices the guest paid, not today's rates. The cost is one call to the plan per night, at most 30.

Booking and paying

book puts the pieces together:

hotel/Hotel.javalines 60–96 of 220
    public Booking book(String guestName, String cardToken, Stay stay) {        Objects.requireNonNull(guestName, "guestName");        Objects.requireNonNull(cardToken, "cardToken");        Objects.requireNonNull(stay, "stay");        if (guestName.isBlank() || cardToken.isBlank()) {            throw new IllegalArgumentException("A booking needs a guest name and a card");        }        LocalDate today = today();        LocalDate lastArrival = today.plusDays(BOOKING_WINDOW_DAYS);        if (stay.arrival().isBefore(today) || stay.arrival().isAfter(lastArrival)) {            throw new NotAllowedException("Arrival must be between " + today + " and " + lastArrival);        }        Quote quote = quote(stay);        inventory.get(stay.roomType()).reserve(stay);        Booking booking = new Booking("B-" + nextId.getAndIncrement(), guestName, quote, UUID.randomUUID().toString());        bookings.put(booking.id(), booking);         boolean approved;        boolean answered = false;        try {            approved = payments.charge(booking.paymentKey(), cardToken, quote.totalCents());            answered = true;        } catch (RuntimeException noAnswer) {            // A real system logs noAnswer with the booking id here.            return booking;        } finally {            if (!answered) {                // The money may have moved, so the nights stay taken until the bank says which.                unansweredPayments.add(booking.id());            }        }        settle(booking, approved);        if (!approved) {            throw new PaymentDeclinedException(booking.id());        }        return booking;    }
  1. Check the dates against today, from the hotel's Clock.
  2. Price the stay with quote (line 72). Nothing is taken yet, so a pricing bug, or a total too large for a long, changes nothing.
  3. Take every night with reserve (line 73). A full night throws here, before a booking or a booking id exists.
  4. Create the booking in PAYMENT_PENDING, with a random payment key, and store it.
  5. Charge the card, with no lock held. The gateway answers yes or no, or throws.
Decision

Hold the nights while the guest pays, or book in one call?

Hold the nights for a few minutes, then take payment in a second call

This is what BookMyShow does, because a user picks seats first and types a card number later. It needs a deadline on every hold, a status for a hold being paid, and something that frees holds whose time is up.

One call: take the nights, charge the card, confirmOur pick

Here the app sends a saved card token with the request, so there is nothing to wait for. A booking is held only for as long as one bank call takes, and no deadline or sweeper is needed. If the app later wants a payment page, the hold from BookMyShow is the change.

The bank can answer in three ways, and each one needs a different ending.

If the card is approved, settle moves the booking to CONFIRMED. If it is declined, settle moves it to DECLINED and gives back every night, and book throws PaymentDeclinedException. The guest can try again with another card, but the nights are on sale in the meantime.

If the call throws, such as on a timeout, nobody knows whether the money moved. The bank may have charged the card and lost the answer on the way back. book keeps the booking PAYMENT_PENDING, keeps its nights, and returns it, so the app can show "we are confirming your payment". A real system also logs the exception with the booking id. The finally block adds the booking to unansweredPayments whenever no answer came back. That covers an Error from the gateway too, which book lets through to the caller, so no booking can hold its nights with nothing coming back to settle it.

When the bank does not answer
book() prices the stay, takes every night and creates B-4 as PAYMENT_PENDING (1). It charges the card with B-4's payment key (2). Approved: B-4 is CONFIRMED. Declined: every night goes back and B-4 is DECLINED. No answer: B-4 stays PAYMENT_PENDING and keeps its nights (3). Later, resolvePendingPayments asks the bank about the same key (4). CHARGED confirms B-4. NOT_CHARGED gives the nights back. UNKNOWN waits for the next run.book() prices the stay, takes every night and creates B-4 as PAYMENT_PENDING (1). It charges the card with B-4's payment key (2). Approved: B-4 is CONFIRMED. Declined: every night goes back and B-4 is DECLINED. No answer: B-4 stays PAYMENT_PENDING and keeps its nights (3). Later, resolvePendingPayments asks the bank about the same key (4). CHARGED confirms B-4. NOT_CHARGED gives the nights back. UNKNOWN waits for the next run.
A decline gives the nights back. Silence keeps them until the bank says what happened. book() prices the stay, takes every night and creates B-4 as PAYMENT_PENDING (1). It charges the card with B-4's payment key (2). Approved: B-4 is CONFIRMED. Declined: every night goes back and B-4 is DECLINED. No answer: B-4 stays PAYMENT_PENDING and keeps its nights (3). Later, resolvePendingPayments asks the bank about the same key (4). CHARGED confirms B-4. NOT_CHARGED gives the nights back. UNKNOWN waits for the next run.

A job calls resolvePendingPayments every minute or so:

hotel/Hotel.javalines 98–127 of 220
    /** Run by a job: asks the bank about each charge that got no answer. Returns how many were settled. */    public int resolvePendingPayments() {        int settled = 0;        for (String bookingId : unansweredPayments) {            Booking booking = bookings.get(bookingId);            PaymentStatus status;            try {                status = payments.lookup(booking.paymentKey());            } catch (RuntimeException stillNoAnswer) {                continue;            }            if (status == null || status == PaymentStatus.UNKNOWN) {                continue;            }            if (settle(booking, status == PaymentStatus.CHARGED)) {                settled++;            }            unansweredPayments.remove(bookingId);        }        return settled;    }     /** Returns false if another answer settled the booking first. */    private boolean settle(Booking booking, boolean charged) {        boolean moved = booking.settlePayment(charged);        if (moved && !charged) {            inventory.get(booking.stay().roomType()).release(booking.stay());        }        return moved;    }

For each unanswered booking, it asks the gateway about the payment key. CHARGED confirms the booking. NOT_CHARGED declines it and gives the nights back. UNKNOWN, null or an exception from lookup leaves the booking pending for the next run. The gateway's contract makes NOT_CHARGED safe to act on:

payment/PaymentGateway.javalines 3–17 of 17
/** * The card processor, outside our code. Every call carries the booking's payment key, * and the processor promises three things about a key: * a second charge with the same key charges nothing more; * once lookup answers NOT_CHARGED, the key is closed and a late charge with it is refused; * a second refund with the same key refunds nothing more. */public interface PaymentGateway {    /** True if approved, false if declined. Throws if no answer comes back, such as on a timeout. */    boolean charge(String paymentKey, String cardToken, long amountCents);     PaymentStatus lookup(String paymentKey);     void refund(String paymentKey, long amountCents);}

Once the bank has said NOT_CHARGED, it refuses any late charge with that key. Without that promise, a charge still on its way could land after the hotel had sold the nights to someone else.

settle is called from two places, so Booking.settlePayment checks under the booking's lock that the booking is still PAYMENT_PENDING, and returns false if not. A second answer about the same payment can never give the nights back twice.

Decision

The bank did not answer. Keep the nights or give them back?

Give the nights back at once, and refund later if the money moved

The guest is not kept waiting, and the nights are not stuck. BookMyShow makes this choice for its seats. But if the money did move, the guest who paid loses the room and waits for a refund.

Keep the nights as PAYMENT_PENDING, and ask the bank with the same keyOur pick

A guest who paid always has a room. One room is off sale while the bank works it out, usually for minutes, which costs little when the stay is weeks away. The cost is a second gateway method, lookup, and a job to call it. A bank that never answers would hold the nights for good, so a real system hands a booking still pending after a day to a person.

Many guests, one room type

When a festival weekend opens for booking, many guests ask for the same room type on overlapping dates at the same moment.

Two stays, one room left
One DELUXE room is left on Tuesday and Wednesday. Asha wants the nights of Monday to Wednesday, and Ben wants the nights of Tuesday to Thursday. On the left there is no lock: both check their nights, both see a room free, and both add one, so Tuesday and Wednesday each have one more booking than rooms. On the right, reserve() holds the DELUXE lock. Asha checks and takes all three nights in one step. Ben waits, finds Tuesday full, and takes nothing.One DELUXE room is left on Tuesday and Wednesday. Asha wants the nights of Monday to Wednesday, and Ben wants the nights of Tuesday to Thursday. On the left there is no lock: both check their nights, both see a room free, and both add one, so Tuesday and Wednesday each have one more booking than rooms. On the right, reserve() holds the DELUXE lock. Asha checks and takes all three nights in one step. Ben waits, finds Tuesday full, and takes nothing.
Without a lock, both guests can see a free room on every night before either takes one. One DELUXE room is left on Tuesday and Wednesday. Asha wants the nights of Monday to Wednesday, and Ben wants the nights of Tuesday to Thursday. On the left there is no lock: both check their nights, both see a room free, and both add one, so Tuesday and Wednesday each have one more booking than rooms. On the right, reserve() holds the DELUXE lock. Asha checks and takes all three nights in one step. Ben waits, finds Tuesday full, and takes nothing.

The design keeps this safe in one place. RoomTypeInventory.reserve and release are synchronized, so checking every night and taking every night happen as one step for that room type. The bookings map is a ConcurrentHashMap, booking ids come from an AtomicLong, and each Booking guards its own status with its own lock. No lock is held during the bank call.

The project includes a check, demo/RaceCheck.java. It sends 1,000 guests at 10 DELUXE rooms through 16 threads that a latch releases together. The stays differ, but every one includes the night of 10 January, so exactly 10 can succeed:

$ java demo.RaceCheck
1,000 guests, 16 threads, 10 DELUXE rooms. Every stay includes the night of 2027-01-10
Booked: 10. Refused, sold out: 990
Nights sold more than 10 times: 0
Nights whose count disagrees with the bookings: 0

We also ran it in a scratch copy with synchronized removed from reserve. Some runs crashed inside HashMap, and the others booked more than 10 guests into 10 rooms. The exact numbers change from run to run and from machine to machine. With the lock in place but the two passes merged into one, so a stay took each night as it checked it, runs left up to 4 nights counting rooms that no booking held. Those were the nights before 10 January, taken by stays that were then refused on the 10th.

Decision

Where do the locks go?

One lock around all of book and cancel

It is correct and easy to explain. But a guest booking a STANDARD room would wait for a SUITE booking, and if the bank call sits inside the lock, every guest in the hotel waits for one slow bank.

One lock per room type per night, taken in date order

Stays that share no night never wait for each other. But a 30-night stay takes 30 locks, and the locks must always be taken in date order, or two stays can deadlock.

One lock per room type, held only while countingOur pick

The counts of one type are the only state a booking changes in many steps, so they share one lock, held for two passes over at most 30 nights. Different room types never wait for each other, and the bank call is outside every lock.

Cancelling and refunds

FirstNightPenalty gives everything back until a set number of days before arrival, and after that keeps the first night:

cancellation/FirstNightPenalty.javalines 19–26 of 27
    @Override    public long refundCents(Quote quote, LocalDate cancelledOn) {        long daysBefore = ChronoUnit.DAYS.between(cancelledOn, quote.stay().arrival());        if (daysBefore >= freeUntilDaysBefore) {            return quote.totalCents();        }        return quote.totalCents() - quote.firstNightCents();    }

TieredRefund gives back a share of the total that depends on how early the guest cancels. It multiplies before dividing and rounds down, so a refund never goes above its percentage. Here is Asha's $502.47 booking under both, with FirstNightPenalty(2) and tiers of 100% from 14 days and 50% from 3 days:

Cancelled onDays before arrivalFirstNightPenalty(2)TieredRefund
1 December17$502.47$502.47
11 December7$502.47$251.23
16 December2$502.47$0.00
17 December1$332.48$0.00

Half of $502.47 is $251.235, and TieredRefund keeps the half cent. The demo hotel uses FirstNightPenalty(2).

cancel asks the policy first and changes things second:

hotel/Hotel.javalines 129–151 of 220
    /** Cancels a confirmed booking, gives its nights back, and returns the refund in cents. */    public long cancel(String bookingId) {        Booking booking = booking(bookingId);        LocalDate today = today();        if (!today.isBefore(booking.stay().departure())) {            throw new NotAllowedException(bookingId + " ended on " + booking.stay().departure());        }        long refund = cancellationPolicy.refundCents(booking.quote(), today);        if (refund < 0 || refund > booking.quote().totalCents()) {            throw new IllegalStateException("The cancellation policy gave a refund of " + refund + " cents");        }        booking.cancel();        inventory.get(booking.stay().roomType()).release(booking.stay());        if (refund > 0) {            try {                payments.refund(booking.paymentKey(), refund);            } catch (RuntimeException bankDown) {                // The booking is cancelled either way. A job sends the refund again with the same key.                refundsToRetry.put(booking.paymentKey(), refund);            }        }        return refund;    }

The policy runs before anything changes, and cancel checks its answer: a refund below zero or above the price is a bug in the policy, so it throws IllegalStateException and the booking stays as it was. Then Booking.cancel moves the booking from CONFIRMED to CANCELLED under its lock. A second cancel, or a cancel racing a check-in, finds another status and is refused. Then the nights go back, and only then is the bank asked for the refund.

Decision

Cancel first, or refund first?

Refund first, and cancel only if the bank says yes

Nothing changes unless the money goes back. But a guest cannot cancel while the bank is down, and the nights stay off sale. And the booking is still CONFIRMED during the bank call, so a check-in can slip in after the money has gone back.

Cancel and give the nights back, then refund; a failed refund is kept to retryOur pick

The guest's cancel always works, and the nights are on sale at once. If refund throws, the amount goes into refundsToRetry under the payment key, and a job calls retryRefunds. The gateway promises that a second refund with the same key returns nothing more, so a retry is safe even if the first refund went through.

Check-in and check-out

hotel/Hotel.javalines 168–189 of 220
    public Room checkIn(String bookingId) {        Booking booking = booking(bookingId);        Stay stay = booking.stay();        LocalDate today = today();        if (today.isBefore(stay.arrival()) || !today.isBefore(stay.departure())) {            throw new NotAllowedException(bookingId + " can check in from " + stay.arrival()                    + " until " + stay.departure().minusDays(1));        }        if (booking.status() != BookingStatus.CONFIRMED) {            throw new NotAllowedException(bookingId + " is " + booking.status() + " and cannot check in");        }        Room room = freeRooms.take(stay.roomType())                .orElseThrow(() -> new NotAllowedException("No " + stay.roomType() + " room is free yet"));        try {            // Checks the status again: a cancel can land between the check above and this line.            booking.checkIn(room);        } catch (RuntimeException e) {            freeRooms.giveBack(room);            throw e;        }        return room;    }

Check-in is allowed on any day from the arrival date up to the day before departure, so a guest who arrives a night late still gets in. A booking that is not CONFIRMED is refused before it takes a room. FreeRooms.take hands out the free room of that type with the lowest number, under the lock of FreeRooms. It compares shorter numbers first, so room 99 comes before room 100. Then Booking.checkIn checks the status again and records the room. A cancel can still land between the first check and Booking.checkIn; then the catch gives the room back before the refusal goes on. Check-out moves the booking to CHECKED_OUT and gives the room back.

The final design

Hotel is the core. It owns one RoomTypeInventory per room type, one FreeRooms and every Booking, and it reaches rates, refunds and the bank only through interfaces. Each of the three classes it owns guards its own state with its own lock, and no lock is held while a rate plan, a refund policy or the bank runs. It reads today's date only from the Clock it is given, so the demo can move time forward by days.

The design we built
This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Hotel carries 5, 6 and 8. RoomTypeInventory carries 3 and 7, FreeRooms carries 2, Booking carries 1, and Quote carries 4. Purple tags mark the two Strategy interfaces, and the Decorator tag sits by RatePlan, whose note names PeakSeason.This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Hotel carries 5, 6 and 8. RoomTypeInventory carries 3 and 7, FreeRooms carries 2, Booking carries 1, and Quote carries 4. Purple tags mark the two Strategy interfaces, and the Decorator tag sits by RatePlan, whose note names PeakSeason.
Each decision lands on one class. Three interfaces carry a pattern. This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Hotel carries 5, 6 and 8. RoomTypeInventory carries 3 and 7, FreeRooms carries 2, Booking carries 1, and Quote carries 4. Purple tags mark the two Strategy interfaces, and the Decorator tag sits by RatePlan, whose note names PeakSeason.
S.No.The questionWhat we choseWhy
1Should a guest be a class?No: a guest is a name on the bookingNo rule reads anything else about a guest
2Does a booking hold a room or a room type?A room type; the room is given out at check-inFixed rooms refuse stays the counts can fit
3How do we know a night has a room left?A count of rooms sold, per room type, per nightOne number per night, however many bookings exist
4How is a stay priced?Night by night, and the lines are kept on the bookingWeekends and seasons come out right, and refunds use the price paid
5Hold the nights while the guest pays, or book in one call?One call: take the nights, charge the card, confirmThe card token comes with the request, so nothing waits
6The bank did not answer. Keep the nights or give them back?Keep the nights as PAYMENT_PENDING, and ask the bank with the same keyA guest who paid always has a room
7Where do the locks go?One lock per room type, held only while countingRoom types never wait for each other, and the bank is outside every lock
8Cancel first, or refund first?Cancel and give the nights back, then refund; a failed refund is kept to retryA guest can always cancel, and the same key makes a retry safe

Here is Esha's suite booking from the demo, end to end:

  1. Esha's phone calls Hotel.book for a SUITE on the nights of 24 and 25 December. quote asks RatePlan.nightlyCents once per night, and PeakSeason raises the two nights to $311.25 and $398.75.
  2. RoomTypeInventory.reserve takes the SUITE lock, checks both nights in one pass, and adds one to each in a second pass. This is the only lock held while counts change, and it is released before the bank is called.
  3. book stores B-4 as PAYMENT_PENDING and calls PaymentGateway.charge with its payment key. This is the outside call. The bank takes the money but the answer is lost, so the call throws.
  4. book adds B-4 to unansweredPayments and returns it. Both nights stay held, because the money may have moved.
  5. The payment job calls resolvePendingPayments, which asks PaymentGateway.lookup about the same key and gets CHARGED. Booking.settlePayment moves B-4 to CONFIRMED under the booking's lock.

A declined card would have ended at step 3 instead: settle gives both nights back, and book throws PaymentDeclinedException.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

hotelHotel.java
package hotel; import java.time.Clock;import java.time.LocalDate;import java.util.ArrayList;import java.util.EnumMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Set;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import cancellation.CancellationPolicy;import exception.NotAllowedException;import exception.PaymentDeclinedException;import payment.PaymentGateway;import payment.PaymentStatus;import pricing.Quote;import pricing.RatePlan;import room.Room;import room.RoomType;import stay.Stay; public class Hotel {    public static final int BOOKING_WINDOW_DAYS = 365;     private final Map<RoomType, RoomTypeInventory> inventory = new EnumMap<>(RoomType.class);    private final FreeRooms freeRooms;    private final RatePlan ratePlan;    private final CancellationPolicy cancellationPolicy;    private final PaymentGateway payments;    private final Clock clock;    private final Map<String, Booking> bookings = new ConcurrentHashMap<>();    private final Set<String> unansweredPayments = ConcurrentHashMap.newKeySet();    private final Map<String, Long> refundsToRetry = new ConcurrentHashMap<>();    private final AtomicLong nextId = new AtomicLong(1);     public Hotel(List<Room> rooms, RatePlan ratePlan, CancellationPolicy cancellationPolicy,            PaymentGateway payments, Clock clock) {        this.freeRooms = new FreeRooms(Objects.requireNonNull(rooms, "rooms"));        this.ratePlan = Objects.requireNonNull(ratePlan, "ratePlan");        this.cancellationPolicy = Objects.requireNonNull(cancellationPolicy, "cancellationPolicy");        this.payments = Objects.requireNonNull(payments, "payments");        this.clock = Objects.requireNonNull(clock, "clock");        for (RoomType type : RoomType.values()) {            inventory.put(type, new RoomTypeInventory(type, freeRooms.count(type)));        }    }     public Quote quote(Stay stay) {        List<Long> prices = new ArrayList<>();        for (LocalDate night : stay.nights()) {            prices.add(ratePlan.nightlyCents(stay.roomType(), night));        }        return new Quote(stay, prices);    }     public Booking book(String guestName, String cardToken, Stay stay) {        Objects.requireNonNull(guestName, "guestName");        Objects.requireNonNull(cardToken, "cardToken");        Objects.requireNonNull(stay, "stay");        if (guestName.isBlank() || cardToken.isBlank()) {            throw new IllegalArgumentException("A booking needs a guest name and a card");        }        LocalDate today = today();        LocalDate lastArrival = today.plusDays(BOOKING_WINDOW_DAYS);        if (stay.arrival().isBefore(today) || stay.arrival().isAfter(lastArrival)) {            throw new NotAllowedException("Arrival must be between " + today + " and " + lastArrival);        }        Quote quote = quote(stay);        inventory.get(stay.roomType()).reserve(stay);        Booking booking = new Booking("B-" + nextId.getAndIncrement(), guestName, quote, UUID.randomUUID().toString());        bookings.put(booking.id(), booking);         boolean approved;        boolean answered = false;        try {            approved = payments.charge(booking.paymentKey(), cardToken, quote.totalCents());            answered = true;        } catch (RuntimeException noAnswer) {            // A real system logs noAnswer with the booking id here.            return booking;        } finally {            if (!answered) {                // The money may have moved, so the nights stay taken until the bank says which.                unansweredPayments.add(booking.id());            }        }        settle(booking, approved);        if (!approved) {            throw new PaymentDeclinedException(booking.id());        }        return booking;    }     /** Run by a job: asks the bank about each charge that got no answer. Returns how many were settled. */    public int resolvePendingPayments() {        int settled = 0;        for (String bookingId : unansweredPayments) {            Booking booking = bookings.get(bookingId);            PaymentStatus status;            try {                status = payments.lookup(booking.paymentKey());            } catch (RuntimeException stillNoAnswer) {                continue;            }            if (status == null || status == PaymentStatus.UNKNOWN) {                continue;            }            if (settle(booking, status == PaymentStatus.CHARGED)) {                settled++;            }            unansweredPayments.remove(bookingId);        }        return settled;    }     /** Returns false if another answer settled the booking first. */    private boolean settle(Booking booking, boolean charged) {        boolean moved = booking.settlePayment(charged);        if (moved && !charged) {            inventory.get(booking.stay().roomType()).release(booking.stay());        }        return moved;    }     /** Cancels a confirmed booking, gives its nights back, and returns the refund in cents. */    public long cancel(String bookingId) {        Booking booking = booking(bookingId);        LocalDate today = today();        if (!today.isBefore(booking.stay().departure())) {            throw new NotAllowedException(bookingId + " ended on " + booking.stay().departure());        }        long refund = cancellationPolicy.refundCents(booking.quote(), today);        if (refund < 0 || refund > booking.quote().totalCents()) {            throw new IllegalStateException("The cancellation policy gave a refund of " + refund + " cents");        }        booking.cancel();        inventory.get(booking.stay().roomType()).release(booking.stay());        if (refund > 0) {            try {                payments.refund(booking.paymentKey(), refund);            } catch (RuntimeException bankDown) {                // The booking is cancelled either way. A job sends the refund again with the same key.                refundsToRetry.put(booking.paymentKey(), refund);            }        }        return refund;    }     /** Run by a job: sends each refund the bank did not take. Returns how many went through. */    public int retryRefunds() {        int sent = 0;        for (Map.Entry<String, Long> refund : refundsToRetry.entrySet()) {            try {                payments.refund(refund.getKey(), refund.getValue());            } catch (RuntimeException stillDown) {                continue;            }            refundsToRetry.remove(refund.getKey(), refund.getValue());            sent++;        }        return sent;    }     public Room checkIn(String bookingId) {        Booking booking = booking(bookingId);        Stay stay = booking.stay();        LocalDate today = today();        if (today.isBefore(stay.arrival()) || !today.isBefore(stay.departure())) {            throw new NotAllowedException(bookingId + " can check in from " + stay.arrival()                    + " until " + stay.departure().minusDays(1));        }        if (booking.status() != BookingStatus.CONFIRMED) {            throw new NotAllowedException(bookingId + " is " + booking.status() + " and cannot check in");        }        Room room = freeRooms.take(stay.roomType())                .orElseThrow(() -> new NotAllowedException("No " + stay.roomType() + " room is free yet"));        try {            // Checks the status again: a cancel can land between the check above and this line.            booking.checkIn(room);        } catch (RuntimeException e) {            freeRooms.giveBack(room);            throw e;        }        return room;    }     public Room checkOut(String bookingId) {        Room room = booking(bookingId).checkOut();        freeRooms.giveBack(room);        return room;    }     public Booking booking(String bookingId) {        Booking booking = bookings.get(Objects.requireNonNull(bookingId, "bookingId"));        if (booking == null) {            throw new NotAllowedException("No booking " + bookingId);        }        return booking;    }     public int roomsLeft(RoomType type, LocalDate night) {        return inventory.get(Objects.requireNonNull(type, "type")).roomsLeft(night);    }     public int pendingPayments() {        return unansweredPayments.size();    }     public int pendingRefunds() {        return refundsToRetry.size();    }     private LocalDate today() {        return LocalDate.now(clock);    }}
Click a class name in the code to open its fileJava · 220 lines · 1109 in the project

demo/Main.java runs a small hotel in Goa through December. It has two STANDARD rooms, two DELUXE and one suite. Asha and Ben take both DELUXE rooms for the same three nights, and Chen is refused. Dev's card is declined, and Esha's bank charges her but loses the answer. Ben cancels the day before arrival, Chen books again, and the guests check in:

$ java demo.Main
Today is 2026-12-01. Rooms: 101, 102 STANDARD; 201, 202 DELUXE; 301 SUITE
Quote for DELUXE:
  night of 2026-12-18 FRIDAY    $169.99
  night of 2026-12-19 SATURDAY  $169.99
  night of 2026-12-20 SUNDAY    $162.49
  total $502.47
Asha asks for DELUXE 2026-12-18 to 2026-12-21: B-1 CONFIRMED, $502.47
Ben asks for DELUXE 2026-12-18 to 2026-12-21: B-2 CONFIRMED, $502.47
Chen asks for DELUXE 2026-12-19 to 2026-12-22: refused. No DELUXE room left on 2026-12-19
  DELUXE rooms left on 2026-12-21: 2
Dev asks for STANDARD 2026-12-24 to 2026-12-26: refused. The card was declined for B-3. No nights are held
  STANDARD rooms left on 2026-12-24: 2
Esha asks for SUITE 2026-12-24 to 2026-12-26: B-4 PAYMENT_PENDING, $710.00
  SUITE rooms left on 2026-12-24: 0
Payment job: 1 settled. B-4 Esha SUITE 2026-12-24 to 2026-12-26 CONFIRMED

2026-12-17: Ben cancels B-2, refund $332.48
Chen asks for DELUXE 2026-12-19 to 2026-12-22: B-5 CONFIRMED, $494.97
  Asha is turned away: B-1 can check in from 2026-12-18 until 2026-12-20
2026-12-18:
  Asha checks in to room 201
2026-12-19:
  Chen checks in to room 202
2026-12-21:
  Asha checks out of room 201
The bank took $2,209.91 and refunded $332.48

Notice three things in the output. Chen's refusal names 19 December, and the DELUXE count for the 21st is still 2, so a refused stay took none of its free nights. After Esha's silent bank, the suite showed no rooms left, and the payment job then found the charge and confirmed B-4. And Ben's refund is $332.48, which is $502.47 less the first night's $169.99, because he cancelled 1 day before arrival.

Follow-up questions

After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Sell 5% more rooms than we have, because some guests never come."RoomTypeInventory takes a sell limit per type, above its room count. checkIn needs a plan for a guest with no room, such as a room at a partner hotel.Pricing, refunds and payment.
"Take a room out of order for repairs."The inventory takes a "rooms out" count per night, and reserve compares against rooms minus that. FreeRooms skips the broken room.Bookings already made, if the counts still fit.
"Let a guest ask for a high floor or a sea view."A note on Booking, read by checkIn, which picks a matching free room if there is one. A view that costs more becomes its own room type.The counts, pricing and payment.
"Charge a no-show the first night."A job at the end of each arrival day finds CONFIRMED bookings that did not check in, marks them NO_SHOW, gives back the nights after today with release, and refunds all but the first night. That ends today's rule that a guest may check in a night late, so the hotel picks one.RoomTypeInventory and RatePlan.
"Let a guest stay one more night."extend takes the extra night through reserve with a one-night Stay, charges for it, and gives it back on a decline. Booking holds a Quote per part of the stay.The lock and FreeRooms: the guest keeps their room.
"Refund the unused nights if a guest leaves early."checkOut gives back the nights after today with release, and a policy decides the refund.Booking and pricing.
"Add GST, which depends on the price per night."A tax line per night on Quote, worked out from each night's price. The refund policy decides whether tax comes back.The counts and the locks.
"Let the guest pay at a payment page."A hold with a deadline, as on the BookMyShow page, and a job that frees expired holds. book splits into hold and pay.Counting, pricing and check-in.
"Run a chain of 50 hotels."One Hotel per property, and a thin service above them that searches.Nothing inside a hotel.

In most rows the change lands in a new rule, a new field or a new job, and RoomTypeInventory.reserve stays as it is. Two rows are bigger: selling more rooms than exist breaks the promise that check-in always finds a room, and a payment page brings back holds with deadlines.

What the interviewer looks for

Mid-level

A mid-level candidate shows clear classes for rooms, bookings and room types, prices in integer cents, and a check that a stay fits before booking it. They say that two guests could take the last room at once and that some locking is needed, even if the lock covers more than it has to.

Senior

A senior candidate shows everything above and gives the reasons. They keep a count per type per night, take every night or none under one lock, and price each night on its own. They argue for giving out rooms at check-in. They say what happens to the nights on a decline and on a timeout, and they keep the bank call outside the lock.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They show why check-in always finds a room, and name the one case that breaks it, a guest who overstays. They explain why a hotel keeps the nights on a timeout while a cinema gives the seats back. They say what a bank that never answers costs, and who handles it.

Common mistakes

  • A list of bookings on every room. Every stay must then find one room free on all its nights, and the hotel refuses stays it has room for.
  • Taking nights one at a time and stopping at a full one. The nights taken before it are never given back, and the counts drift away from the bookings.
  • Checking every night, then taking them in a separate step. Another booking can fill a night in between.
  • Pricing a stay as the arrival night's rate times the number of nights. Weekends and seasons come out wrong.
  • Giving the nights back when the bank times out. If the money moved, a guest who paid has no room.
  • Holding a lock during the bank call. Every guest who wants that room type waits for one slow bank.
  • double for money. Sums drift by fractions of a cent, and the refund disagrees with the charge.

Summary

  • Ask first whether a guest books a room or a room type. Each answer leads to a different design.
  • A booking holds a room type. A count per type per night says whether a stay fits, and the room number comes at check-in.
  • reserve checks every night, then takes every night, under one lock per room type.
  • Price each night on its own with a RatePlan, keep the lines on the booking, and wrap the plan for a season.
  • A decline gives every night back. A timeout keeps them until the bank answers about the same key.
  • Cancel and give the nights back first, then refund, and keep a failed refund to retry with the same key.
  • Keep the bank call outside every lock.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.