LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 33 OF 42

Design a Hotel Booking System: LLD in Java

The hotel booking machine coding question, solved end to end: hotels, room types and rooms, date-range search with half-open stays, holds that expire on a fake clock, a lock per room so the last room is never sold twice, booking states, pricing by season and weekend as stacked strategies, cancellation and refund policies, and a full Java 17 solution.

Patterns usedStrategyDecoratorStateObserver

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 21

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 392 lines, with a small main() demo. Save it as HotelBooking.java, then run javac HotelBooking.java && java HotelBooking.

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** A hotel booking system: date-range search, holds that expire, no double booking, pricing and refunds. */
public class HotelBooking {

    // ---------- the model ----------
    record RoomType(String code, String name, int capacity, long baseNightCents) {}

    record Stay(LocalDate checkIn, LocalDate checkOut) {
        Stay {
            if (!checkIn.isBefore(checkOut)) {
                throw new IllegalArgumentException("check-out must be after check-in");
            }
        }

        /** Half-open ranges: leaving on the 21st and arriving on the 21st do not clash. */
        boolean overlaps(Stay o) { return checkIn.isBefore(o.checkOut) && o.checkIn.isBefore(checkOut); }

        List<LocalDate> nights() { return checkIn.datesUntil(checkOut).toList(); }
    }

    enum Status {
        HELD, CONFIRMED, EXPIRED, CANCELLED, CHECKED_IN, CHECKED_OUT;

        boolean canMoveTo(Status next) {
            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;
            };
        }
    }

    static final class Hotel {
        final String id;
        final String name;
        final String city;
        final ZoneId zone;
        final List<Room> rooms = new ArrayList<>();

        Hotel(String id, String name, String city, ZoneId zone) {
            this.id = id;
            this.name = name;
            this.city = city;
            this.zone = zone;
        }

        Hotel room(String number, RoomType type) {
            rooms.add(new Room(number, type, this));
            return this;
        }
    }

    /** The room is the unit of locking: its bookings list and their states are guarded by the room. */
    static final class Room {
        final String number;
        final RoomType type;
        final Hotel hotel;
        private final List<Booking> bookings = new ArrayList<>();

        Room(String number, RoomType type, Hotel hotel) {
            this.number = number;
            this.type = type;
            this.hotel = hotel;
        }

        /** Call with the room lock held. Expired holds no longer block anybody. */
        boolean isFree(Stay stay, Instant now) {
            for (Booking b : bookings) if (b.blocks(now) && b.stay.overlaps(stay)) return false;
            return true;
        }
    }

    static final class Booking {
        final String id;
        final String guest;
        final Room room;
        final Stay stay;
        final long totalCents;
        final CancellationPolicy policy;           // fixed at booking time, later policy changes do not apply
        final Instant holdExpiresAt;
        private Status status = Status.HELD;
        private long refundedCents;               // kept for the receipt and the audit trail
        private final List<String> history = new ArrayList<>(List.of("HELD"));

        Booking(String id, String guest, Room room, Stay stay, long totalCents, CancellationPolicy policy,
                Instant holdExpiresAt) {
            this.id = id;
            this.guest = guest;
            this.room = room;
            this.stay = stay;
            this.totalCents = totalCents;
            this.policy = policy;
            this.holdExpiresAt = holdExpiresAt;
        }

        boolean blocks(Instant now) {
            return status == Status.CONFIRMED || status == Status.CHECKED_IN
                    || (status == Status.HELD && now.isBefore(holdExpiresAt));
        }

        void move(Status next) {
            if (!status.canMoveTo(next)) {
                throw new IllegalStateException(id + ": cannot go " + status + " -> " + next);
            }
            status = next;
            history.add(next.name());
        }

        /** Check-in is at 14:00 in the hotel's own time zone. */
        Instant checkInAt() {
            return stay.checkIn().atTime(LocalTime.of(14, 0)).atZone(room.hotel.zone).toInstant();
        }

        Status status() { synchronized (room) { return status; } }

        List<String> history() { synchronized (room) { return List.copyOf(history); } }
    }

    record Offer(String hotel, String roomType, int freeRooms, long totalCents) {
        @Override
        public String toString() {
            return hotel + " " + roomType + ": " + freeRooms + " free, " + money(totalCents);
        }
    }

    // ---------- pricing (Strategy, stacked with decorators) ----------
    interface PricingStrategy { long nightCents(RoomType type, LocalDate night); }

    static final class BaseRate implements PricingStrategy {
        @Override public long nightCents(RoomType type, LocalDate night) { return type.baseNightCents(); }
    }

    /** Friday and Saturday nights cost more. */
    record WeekendSurcharge(PricingStrategy inner, int percent) implements PricingStrategy {
        @Override
        public long nightCents(RoomType type, LocalDate night) {
            long base = inner.nightCents(type, night);
            DayOfWeek d = night.getDayOfWeek();
            boolean weekend = d == DayOfWeek.FRIDAY || d == DayOfWeek.SATURDAY;
            return weekend ? base * (100 + percent) / 100 : base;
        }
    }

    /** A season such as 20 Dec to 5 Jan, which may wrap around the new year. */
    record Season(PricingStrategy inner, MonthDay from, MonthDay to, int percent) implements PricingStrategy {
        @Override
        public long nightCents(RoomType type, LocalDate night) {
            long base = inner.nightCents(type, night);
            MonthDay d = MonthDay.from(night);
            boolean in = from.isBefore(to)
                    ? !d.isBefore(from) && !d.isAfter(to)
                    : !d.isBefore(from) || !d.isAfter(to);            // wraps past 31 Dec
            return in ? base * (100 + percent) / 100 : base;
        }
    }

    // ---------- cancellation (Strategy) ----------
    interface CancellationPolicy { long refundCents(Booking b, Instant now); }

    /** Full refund up to 48 hours before check-in, half after that, nothing once check-in time has passed. */
    static final class Flexible implements CancellationPolicy {
        @Override
        public long refundCents(Booking b, Instant now) {
            Duration before = Duration.between(now, b.checkInAt());
            if (before.toHours() >= 48) return b.totalCents;
            if (!before.isNegative()) return b.totalCents / 2;
            return 0;
        }
    }

    static final class NonRefundable implements CancellationPolicy {
        @Override public long refundCents(Booking b, Instant now) { return 0; }
    }

    // ---------- the service ----------
    private final Map<String, Hotel> hotels = new ConcurrentHashMap<>();
    private final Map<String, Booking> bookings = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong();
    private final PricingStrategy pricing;
    private final Supplier<Instant> clock;
    private final Duration holdFor;

    HotelBooking(PricingStrategy pricing, Supplier<Instant> clock, Duration holdFor) {
        this.pricing = pricing;
        this.clock = clock;
        this.holdFor = holdFor;
    }

    void add(Hotel h) { hotels.put(h.id, h); }

    long price(RoomType type, Stay stay) {
        long sum = 0;
        for (LocalDate night : stay.nights()) sum += pricing.nightCents(type, night);
        return sum;
    }

    /** Search is a read: the counts may change a moment later, so hold() checks again under the lock. */
    List<Offer> search(String city, Stay stay, int guests) {
        Instant now = clock.get();
        List<Offer> out = new ArrayList<>();
        for (Hotel h : hotels.values()) {
            if (!h.city.equals(city)) continue;
            Map<RoomType, Integer> free = new LinkedHashMap<>();
            for (Room r : h.rooms) {
                if (r.type.capacity() < guests) continue;
                boolean ok;
                synchronized (r) { ok = r.isFree(stay, now); }
                free.merge(r.type, ok ? 1 : 0, Integer::sum);
            }
            free.forEach((t, n) -> out.add(new Offer(h.name, t.name(), n, price(t, stay))));
        }
        return out;
    }

    /** Hold one room of the type for a few minutes while the guest pays. */
    Booking hold(String guest, String hotelId, String typeCode, Stay stay, CancellationPolicy policy) {
        Hotel h = hotels.get(hotelId);
        if (h == null) throw new IllegalArgumentException("no hotel " + hotelId);
        Instant now = clock.get();
        for (Room r : h.rooms) {
            if (!r.type.code().equals(typeCode)) continue;
            synchronized (r) {                         // check and claim under one lock: no double booking
                if (!r.isFree(stay, now)) continue;
                String id = "B" + ids.incrementAndGet();
                Booking b = new Booking(id, guest, r, stay, price(r.type, stay), policy, now.plus(holdFor));
                r.bookings.add(b);
                bookings.put(b.id, b);
                return b;
            }
        }
        throw new IllegalStateException("no " + typeCode + " room free for " + stay);
    }

    /** Payment succeeded: turn the hold into a booking, unless the hold already ran out. */
    Booking confirm(String bookingId) {
        Booking b = find(bookingId);
        synchronized (b.room) {
            if (b.status == Status.HELD && !clock.get().isBefore(b.holdExpiresAt)) {
                b.move(Status.EXPIRED);
                throw new IllegalStateException(bookingId + ": hold expired, please search again");
            }
            b.move(Status.CONFIRMED);
            return b;
        }
    }

    /** Returns the refund in cents. A hold has taken no money, so it refunds nothing. */
    long cancel(String bookingId) {
        Booking b = find(bookingId);
        synchronized (b.room) {
            long refund = b.status == Status.CONFIRMED ? b.policy.refundCents(b, clock.get()) : 0;
            b.move(Status.CANCELLED);
            b.refundedCents = refund;
            return refund;
        }
    }

    void checkIn(String bookingId) {
        Booking b = find(bookingId);
        synchronized (b.room) { b.move(Status.CHECKED_IN); }
    }

    /** A background sweeper: expired holds already stop blocking, this just tidies their status. */
    int expireHolds() {
        Instant now = clock.get();
        int n = 0;
        for (Booking b : bookings.values()) {
            synchronized (b.room) {
                if (b.status == Status.HELD && !now.isBefore(b.holdExpiresAt)) {
                    b.move(Status.EXPIRED);
                    n++;
                }
            }
        }
        return n;
    }

    private Booking find(String id) {
        Booking b = bookings.get(id);
        if (b == null) throw new IllegalArgumentException("no booking " + id);
        return b;
    }

    static String money(long cents) { return String.format("%,d.%02d", cents / 100, cents % 100); }

    // ---------- demo ----------
    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-12-01T04:30:00Z"));
        RoomType standard = new RoomType("STD", "Standard", 2, 3_000_00);
        RoomType deluxe = new RoomType("DLX", "Deluxe sea view", 3, 5_000_00);
        PricingStrategy pricing = new Season(new WeekendSurcharge(new BaseRate(), 20),
                MonthDay.of(12, 20), MonthDay.of(1, 5), 50);
        HotelBooking app = new HotelBooking(pricing, now::get, Duration.ofMinutes(10));
        ZoneId ist = ZoneId.of("Asia/Kolkata");
        app.add(new Hotel("H1", "Palm Shore", "Goa", ist).room("101", standard).room("102", standard)
                .room("201", deluxe));
        app.add(new Hotel("H2", "Hill Nest", "Ooty", ist).room("11", standard));

        Stay xmas = new Stay(LocalDate.of(2026, 12, 18), LocalDate.of(2026, 12, 21));
        for (LocalDate night : xmas.nights()) {
            System.out.println("  " + night + " " + night.getDayOfWeek() + ": deluxe "
                    + money(pricing.nightCents(deluxe, night)));
        }
        System.out.println("search: " + app.search("Goa", xmas, 2));

        Booking slow = app.hold("guest-a", "H1", "DLX", xmas, new Flexible());
        System.out.println("held " + slow.id + " room " + slow.room.number + " for " + money(slow.totalCents)
                + ", deluxe left: " + app.search("Goa", xmas, 3));
        now.set(now.get().plus(Duration.ofMinutes(11)));          // the guest wandered off
        System.out.println("11 minutes later: " + app.search("Goa", xmas, 3));
        try {
            app.confirm(slow.id);
        } catch (IllegalStateException e) {
            System.out.println("confirm: " + e.getMessage());
        }

        // Eight guests race for the one deluxe room on the same dates: exactly one hold wins.
        AtomicInteger won = new AtomicInteger(), lost = new AtomicInteger();
        AtomicReference<Booking> winner = new AtomicReference<>();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch go = new CountDownLatch(1);
        for (int i = 0; i < 8; i++) {
            String guest = "racer-" + i;
            pool.submit(() -> {
                try {
                    go.await();
                    winner.set(app.hold(guest, "H1", "DLX", xmas, new Flexible()));
                    won.incrementAndGet();
                } catch (IllegalStateException e) {
                    lost.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        go.countDown();
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("race for 1 deluxe room: " + won.get() + " held, " + lost.get() + " turned away");
        if (won.get() != 1) throw new AssertionError("double booking");
        Booking b = app.confirm(winner.get().id);
        System.out.println(b.guest + " confirmed " + b.id + ", paid " + money(b.totalCents));

        try {
            app.hold("guest-c", "H1", "DLX", new Stay(LocalDate.of(2026, 12, 20), LocalDate.of(2026, 12, 22)),
                    new Flexible());
        } catch (IllegalStateException e) {
            System.out.println("overlap 20-22 Dec: " + e.getMessage());
        }
        Booking next = app.hold("guest-d", "H1", "DLX",
                new Stay(LocalDate.of(2026, 12, 21), LocalDate.of(2026, 12, 23)), new NonRefundable());
        app.confirm(next.id);
        System.out.println("back to back 21-23 Dec: " + next.id + " " + next.status());

        now.set(Instant.parse("2026-12-17T04:30:00Z"));          // 10:00 in Goa, 28 hours before check-in
        System.out.println("cancel " + b.id + " (flexible, 28h before): refund " + money(app.cancel(b.id))
                + " of " + money(b.totalCents));
        System.out.println("cancel " + next.id + " (non-refundable): refund " + money(app.cancel(next.id)));
        System.out.println("room free again: " + app.search("Goa", xmas, 3));
        try {
            app.checkIn(b.id);
        } catch (IllegalStateException e) {
            System.out.println("illegal: " + e.getMessage());
        }
        app.hold("guest-e", "H1", "STD", xmas, new Flexible());
        now.set(now.get().plus(Duration.ofMinutes(15)));
        System.out.println("sweeper tidied " + app.expireHolds() + " old holds");
        System.out.println("history of " + slow.id + ": " + slow.history());
        System.out.println("history of " + b.id + ": " + b.history());
    }
}

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.

Requirements
  • 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
Clarify first
  • 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.

Types
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.

Stay.overlaps()
// 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.

search(city, stay, guests)
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.

Why hold first
  • 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
Expiry without timers
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.

Status.canMoveTo()
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.

hold(guest, hotel, type, stay)
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.

No double 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
In a database
  • 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.

PricingStrategy
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.

CancellationPolicy
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.

Thread safety checklist
  • 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.

Extension points
  • 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.

Run it
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.

Follow-ups to expect
  • 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.

In the interview
  • "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."

Interview questions

How do you check whether two bookings overlap?

Treat stays as half-open ranges where the check-out day is not a night. Two stays overlap when each check-in is before the other check-out. This lets one guest leave and another arrive on the same day without a false clash.

How do you stop two guests from booking the last room?

Make checking availability and adding the booking one atomic step: here a lock per room, in a database a unique key on room and night or a row lock on the room. The second guest then sees the first booking and is turned away or offered another room.

Why hold a room before payment instead of booking after payment?

Payment takes minutes, and without a hold two guests can both pay for one room, forcing a refund. A hold blocks the room for a short time, and confirm turns it into a booking only if payment finishes before the hold expires.

How do holds expire without a timer for every booking?

Store an expiry time on the hold and treat it as blocking only while the current time is before that. Expired holds stop counting immediately; a background sweeper just updates their status. Inject the clock so tests can move time without sleeping.

Why lock per room instead of per hotel?

Two bookings only conflict when they are for the same room, so a room lock protects exactly what needs protecting. A hotel-wide lock is also correct but makes every guest wait for every other guest during peak demand.

How would you design seasonal and weekend pricing?

A PricingStrategy that prices one night of one room type, with the stay total as the sum of nights. Rules such as a weekend surcharge or a peak season wrap the base rate as decorators, so new rules are new classes and stays crossing a boundary are priced correctly.

Where should the cancellation policy live?

Behind a CancellationPolicy interface, with the chosen policy stored on the booking when it is made. The guest keeps the terms they agreed to even if the hotel changes its rules later, and deadlines are computed in the hotel's time zone.

What states does a booking have?

Held, confirmed, expired, cancelled, checked in and checked out. A table or switch of legal moves, checked in one method, prevents bugs such as confirming an expired hold or checking in a cancelled booking.

What happens if payment succeeds just after the hold expired?

Try to claim the room again under the lock. If it is still free, confirm a new booking at the quoted price; if someone else took it, refund the payment automatically and tell the guest. Never confirm an expired hold blindly.