LLD

Full Designs

Meeting Room Scheduler

A weak answer keeps a list of meetings and loops over it. We build one that holds up when the interviewer pushes: why a meeting can end at 11:00 when the next one starts at 11:00, how to find a clash without reading every meeting, what happens when two people grab the same room at once, and how to move a meeting without losing it.

"Design a meeting room booking system" sounds small. A weak answer gives each Room a list of meetings, loops over the list to look for a clash, and stops. The loop is not wrong, but it leaves every hard question open.

The interviewer is checking a few precise things. Can a meeting that ends at 11:00 sit next to one that starts at 11:00? Can the code find a clash without reading every meeting in the room? Two people book the last free room for 10:00 at the same moment, so who gets it? What happens to a meeting when someone moves it and the new time is taken? And what does "10:00" mean when one office is in Bengaluru and another is in London?

This article walks through the question the way a 45 minute interview goes. 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.

Booking at a glance
Asha's laptop asks the RoomScheduler for a room for 4 people with a screen at 10:00 (1). The scheduler asks the RoomChooser which rooms to try first (2), then tries Ganga's calendar under that room's own lock (3). Moving a meeting from Ganga to Narmada holds both rooms' locks at once (4). Each calendar reads the Clock under its lock, to refuse a time that has passed (5).Asha's laptop asks the RoomScheduler for a room for 4 people with a screen at 10:00 (1). The scheduler asks the RoomChooser which rooms to try first (2), then tries Ganga's calendar under that room's own lock (3). Moving a meeting from Ganga to Narmada holds both rooms' locks at once (4). Each calendar reads the Clock under its lock, to refuse a time that has passed (5).
Each room guards its own day. The scheduler only decides which room to try. Asha's laptop asks the RoomScheduler for a room for 4 people with a screen at 10:00 (1). The scheduler asks the RoomChooser which rooms to try first (2), then tries Ganga's calendar under that room's own lock (3). Moving a meeting from Ganga to Narmada holds both rooms' locks at once (4). Each calendar reads the Clock under its lock, to refuse a time that has passed (5).

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 the system book rooms, or also check that people are free?Rooms only. People's calendars are a separate serviceNo attendee calendars; a request carries a head count
Does the user pick the room, or does the system?BothbookRoom for a named room, and book, which chooses one
How is a room chosen?Enough seats, the equipment asked for, the smallest room firstA rule behind an interface, with a second rule to compare
Can a meeting start when another ends?Yes, at the same minuteA slot leaves out its end, and the clash test uses strict comparisons
How many offices?Several, in different time zonesTimes are stored as instants, and each office has a time zone
How long can a meeting be?Up to 10 hours, in whole minutesA limit checked when a slot is made
How far ahead can people book?Up to 365 daysA horizon checked under the room's lock
Can people cancel or move a meeting?Yes, until it startsA cancel and a move that read the clock under the room's lock
What if the new slot of a move is taken?The meeting stays where it wasA move that checks everything before it changes anything
Do many people book at once?Yes, from many laptops and phonesEvery method is safe from many threads, with one lock per room

The question about people's calendars matters most. If the scheduler had to check that all six people invited are free, one booking would touch six calendars and a room, all at once. Most of the design would then be about that. We keep room booking on its own, and come back to people's calendars at the end.

Requirements

Functional:

  1. A person asks for a room in an office, for a number of people, some equipment and a time. The scheduler books a room with enough seats and that equipment, free for the whole time, and tries the smallest room first.
  2. A person can also book a room they name. If it is in another office, too small, lacks the equipment or is taken, nothing is booked.
  3. No room ever holds two meetings at the same moment. A meeting that starts as another ends is not a clash.
  4. A meeting can be cancelled, or moved to another time or room, until it starts. A move whose new slot is taken leaves the meeting where it was.
  5. Every refusal says why, and a refused request changes nothing.
  6. People type times as they read them on the office's wall clock. A wall-clock time that does not exist, on the night the clocks go forward, is refused.
  7. A meeting starts and ends on whole minutes, lasts at most 10 hours, and starts now or later but less than 365 days ahead.

Out of scope: people's calendars, recurring meetings, reminders, who may cancel a meeting, and floors and buildings. We come back to these at the end, because each is a natural follow-up, and a design that bends towards them is part of the answer.

Everything lives in memory, as is normal for a low-level design interview. Keeping bookings in a database so that many servers can share them is a follow-up at the end.

What the code itself must handle:

  • Many people at once. book, reschedule and cancel are called from many threads, often on the same room.
  • Time. "Has this meeting started?" must be testable, so the code takes a Clock and never reads the system time itself.
  • A rule that will change. Which room to try first is a choice each company makes differently.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
Office, room, time slot, request and booking become records, and equipment an enum. A room's day and the scheduler become classes, because their state changes. The choice of room becomes an interface. Four nouns are dropped. Each person's calendar is a separate service, the organiser is a name on the booking, floors and buildings are not needed once the office is known, and reminders are a follow-up.Office, room, time slot, request and booking become records, and equipment an enum. A room's day and the scheduler become classes, because their state changes. The choice of room becomes an interface. Four nouns are dropped. Each person's calendar is a separate service, the organiser is a name on the booking, floors and buildings are not needed once the office is known, and reminders are a follow-up.
Most nouns become classes. People's calendars do not. Office, room, time slot, request and booking become records, and equipment an enum. A room's day and the scheduler become classes, because their state changes. The choice of room becomes an interface. Four nouns are dropped. Each person's calendar is a separate service, the organiser is a name on the booking, floors and buildings are not needed once the office is known, and reminders are a follow-up.

Each person's calendar needs the most thought. Booking a meeting usually means finding a time when everyone is free, and it is tempting to fold that into the same design.

Decision

Should the scheduler check each person's calendar?

Yes: book the room only if everyone invited is free

This matches what people want from a calendar app. But one booking now touches the room and every attendee's calendar, all or nothing. A meeting of six takes seven locks in a fixed order, and a calendar owned by another service cannot be locked from here at all.

No: book rooms only, and carry a head countOur pick

A request says how many people are coming, which is all a room needs to know. Whether those people are free is the calendar service's question, asked before the request reaches us. The cost is that a room can be booked for a meeting that half its people cannot attend.

Data or behaviour?

Some classes only carry data and never change once created: an office, a room, a time slot, a request, a booking. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.

room/Room.javalines 7–27 of 28
public record Room(String id, String name, Office office, int capacity, Set<Equipment> equipment) {    public static final int MAX_CAPACITY = 500;     public Room {        Objects.requireNonNull(id, "id");        Objects.requireNonNull(name, "name");        Objects.requireNonNull(office, "office");        Objects.requireNonNull(equipment, "equipment");        if (id.isBlank() || name.isBlank()) {            throw new IllegalArgumentException("a room needs an id and a name");        }        if (capacity < 1 || capacity > MAX_CAPACITY) {            throw new IllegalArgumentException("a room seats 1 to " + MAX_CAPACITY + " people, not " + capacity);        }        equipment = Set.copyOf(equipment);    }     /** Whether the meeting fits: enough seats, and everything it needs. */    public boolean fits(int attendees, Set<Equipment> needs) {        return capacity >= attendees && equipment.containsAll(needs);    }

A room refuses a capacity outside 1 to 500, and it copies its equipment with Set.copyOf, so a caller who changes their own set later cannot change the room. fits is the one rule a room knows: enough seats, and every piece of equipment the meeting needs. A Booking is a record too. A move does not change a booking; movedTo makes a new one with the same id.

The class diagram

The classes and how they connect
RoomScheduler owns one RoomCalendar per room, and an index from booking id to room id. It uses a RoomChooser, which sees each room only through RoomView, the interface RoomCalendar implements. Each RoomCalendar owns its bookings, sorted by start time. SmallestFitChooser and LeastBookedChooser implement RoomChooser. Booking, TimeSlot, MeetingRequest, Room and Office are records, and Equipment is an enum. BookingResult and Outcome, the answers the scheduler gives, are not drawn.RoomScheduler owns one RoomCalendar per room, and an index from booking id to room id. It uses a RoomChooser, which sees each room only through RoomView, the interface RoomCalendar implements. Each RoomCalendar owns its bookings, sorted by start time. SmallestFitChooser and LeastBookedChooser implement RoomChooser. Booking, TimeSlot, MeetingRequest, Room and Office are records, and Equipment is an enum. BookingResult and Outcome, the answers the scheduler gives, are not drawn.
RoomScheduler routes requests. Each RoomCalendar owns one room's day and its lock. RoomScheduler owns one RoomCalendar per room, and an index from booking id to room id. It uses a RoomChooser, which sees each room only through RoomView, the interface RoomCalendar implements. Each RoomCalendar owns its bookings, sorted by start time. SmallestFitChooser and LeastBookedChooser implement RoomChooser. Booking, TimeSlot, MeetingRequest, Room and Office are records, and Equipment is an enum. BookingResult and Outcome, the answers the scheduler gives, are not drawn.

The classes fall into three groups:

  • Data: Office, Room, TimeSlot, MeetingRequest and Booking are records, and Equipment and Outcome are enums. BookingResult pairs an outcome with the booking it is about.
  • The core: RoomScheduler and RoomCalendar. They hold the state that changes and keep it correct under many threads.
  • Rules and outside systems: RoomChooser with its two implementations, and the Clock. The core depends on the interface and never on a particular rule.

The rest of the article builds these one at a time.

Building it

A slot is [start, end)

A meeting from 10:00 to 11:00 and one from 11:00 to 12:00 should both fit in Ganga. If the minute 11:00 belonged to both, they would clash. So a slot includes its start and leaves out its end:

booking/TimeSlot.javalines 15–35 of 55
public record TimeSlot(Instant start, Instant end) {    public static final Duration LONGEST = Duration.ofHours(10);     public TimeSlot {        Objects.requireNonNull(start, "start");        Objects.requireNonNull(end, "end");        if (!start.isBefore(end)) {            throw new IllegalArgumentException("a slot must end after it starts");        }        if (!start.equals(start.truncatedTo(ChronoUnit.MINUTES)) || !end.equals(end.truncatedTo(ChronoUnit.MINUTES))) {            throw new IllegalArgumentException("a slot starts and ends on whole minutes");        }        if (Duration.between(start, end).compareTo(LONGEST) > 0) {            throw new IllegalArgumentException("a meeting can last at most " + LONGEST.toHours() + " hours");        }    }     /** Two slots clash if each starts before the other ends. */    public boolean overlaps(TimeSlot other) {        return start.isBefore(other.end) && other.start.isBefore(end);    }

The constructor refuses a slot that ends before it starts, or ends when it starts, a slot whose ends are not whole minutes, and a slot longer than 10 hours. Whole minutes keep the minute counts exact, and they rule out a one-nanosecond meeting. overlaps holds when each slot starts before the other one ends. Both comparisons are strict, so a slot that ends at 11:00 and one that starts at 11:00 do not overlap.

When two meetings clash
Asha holds Ganga from 10:00 to 11:00. A slot that ends as hers starts, or starts as hers ends, fits. A slot that overlaps her start or her end, sits inside hers or covers it is refused. All four clashes pass the same test: each one starts before the other ends.Asha holds Ganga from 10:00 to 11:00. A slot that ends as hers starts, or starts as hers ends, fits. A slot that overlaps her start or her end, sits inside hers or covers it is refused. All four clashes pass the same test: each one starts before the other ends.
Four shapes of clash, two shapes of fit, and one test for all six. Asha holds Ganga from 10:00 to 11:00. A slot that ends as hers starts, or starts as hers ends, fits. A slot that overlaps her start or her end, sits inside hers or covers it is refused. All four clashes pass the same test: each one starts before the other ends.
Decision

Should a slot include its end minute?

[start, end]: both ends belong to the slot

Then 10:00 to 11:00 and 11:00 to 12:00 clash. People work around it by booking 10:00 to 10:59, which looks odd on every screen and makes an hour-long meeting 59 minutes long in the code.

[start, end): the end does not belong to the slotOur pick

Meetings that touch do not clash, a slot's length is its end minus its start, and the clash test is two strict comparisons. The cost is a rule that everyone writing code against TimeSlot has to know, which is why the record's comment states it.

Instants, not wall-clock times

The company has offices in Bengaluru and London. "10:00" in each is a different moment, and Asha in Bengaluru may book a London room for a call. So every slot stores two Instants, points on one timeline that every office shares. An Office record holds the office's ZoneId, which is used only when a person types a time or reads one.

Decision

Store wall-clock times or instants?

A LocalDateTime and the room's time zone

It matches what people type. But every comparison must first turn both times into moments, two rooms in different zones cannot be compared directly, and on the night the clocks go back one wall-clock time means two moments.

An Instant in every slot, and time zones only at the edgesOur pick

Clashes, durations and "has it started?" are plain comparisons of instants, the same in every office. The cost is at the edges: the screen turns typed times into instants, and any code that prints a slot must be given the office's zone.

The edge is where the clocks change. London moves its clocks forward on the last Sunday of March and back on the last Sunday of October. TimeSlot.ofLocal turns wall-clock times into instants:

booking/TimeSlot.javalines 41–54 of 55
    /** A slot typed as wall-clock times in an office's time zone. */    public static TimeSlot ofLocal(LocalDateTime start, LocalDateTime end, ZoneId zone) {        Objects.requireNonNull(zone, "zone");        return new TimeSlot(toInstant(start, zone), toInstant(end, zone));    }     private static Instant toInstant(LocalDateTime local, ZoneId zone) {        Objects.requireNonNull(local, "local time");        if (zone.getRules().getValidOffsets(local).isEmpty()) {            throw new IllegalArgumentException(local + " does not exist in " + zone + ": the clocks skip it");        }        // When the clocks go back, this hour happens twice. atZone takes the earlier offset: the first time round.        return local.atZone(zone).toInstant();    }

getValidOffsets lists the offsets from Coordinated Universal Time (UTC) that a wall-clock time can have in that zone. On the night the clocks go forward, the skipped hour has none, so the method throws. Otherwise atZone turns the time into a moment. On the night the clocks go back, the repeated hour has two offsets, and atZone is documented to take the earlier one, the first time round.

The nights the clocks change
On 29 March, London clocks jump from 01:00 to 02:00. Priya's meeting from 00:30 to 03:30 on the wall starts at 00:30 UTC and ends at 02:30 UTC, so it lasts 2 hours, and a slot typed from 01:30 is refused because no clock shows 01:30. On 25 October the hour from 01:00 to 02:00 happens twice. A slot typed from 01:30 to 02:30 starts at the first 01:30, which is 00:30 UTC, and ends at 02:30 UTC, so it also lasts 2 hours.On 29 March, London clocks jump from 01:00 to 02:00. Priya's meeting from 00:30 to 03:30 on the wall starts at 00:30 UTC and ends at 02:30 UTC, so it lasts 2 hours, and a slot typed from 01:30 is refused because no clock shows 01:30. On 25 October the hour from 01:00 to 02:00 happens twice. A slot typed from 01:30 to 02:30 starts at the first 01:30, which is 00:30 UTC, and ends at 02:30 UTC, so it also lasts 2 hours.
A wall-clock hour can be missing or doubled. Instants never are. On 29 March, London clocks jump from 01:00 to 02:00. Priya's meeting from 00:30 to 03:30 on the wall starts at 00:30 UTC and ends at 02:30 UTC, so it lasts 2 hours, and a slot typed from 01:30 is refused because no clock shows 01:30. On 25 October the hour from 01:00 to 02:00 happens twice. A slot typed from 01:30 to 02:30 starts at the first 01:30, which is 00:30 UTC, and ends at 02:30 UTC, so it also lasts 2 hours.
Decision

What should a wall-clock time that does not exist, or happens twice, mean?

Let Java decide both

ZonedDateTime.of takes the earlier of two repeated times, which is what we want. But it moves a missing time forward by the length of the gap without saying so. A meeting typed for 01:30 becomes 02:30, which the person never asked for.

Refuse both

This is safe, but the repeated hour is a real hour that people use. Refusing every time in it surprises them for no gain.

Refuse a time that does not exist, and take the first of twoOur pick

A time no clock shows is a typo, so the person is told and can type another. For a repeated time, we keep Java's rule and take the first one: it is the first 01:30 people live through, and Java's default. The screen can show the offset to make the choice visible. The cost is that a slot typed from 01:30 to 02:30 that night lasts 2 hours, not 1.

TimeSlot refuses bad input with an IllegalArgumentException whose message the screen can show, because a slot is made before any request reaches the scheduler. The scheduler itself never throws for something a person did. It answers with an Outcome, as the next sections show.

One room's calendar

Each room keeps its own bookings in a RoomCalendar:

scheduler/RoomCalendar.javalines 26–40 of 183
final class RoomCalendar implements RoomView {    /** How far ahead a meeting may start. */    static final Duration HORIZON = Duration.ofDays(365);     private final Room room;    private final Clock clock;    // Shared by all calendars: booking id to room id. A calendar writes it only under its own lock.    private final Map<String, String> roomOfBooking;    private final Supplier<String> nextId;    // A private lock, so code outside the calendar cannot hold it.    private final Object lock = new Object();    // Guarded by lock. No two bookings in a room overlap.    private final TreeMap<Instant, Booking> byStart = new TreeMap<>();    private final Map<String, Booking> byId = new HashMap<>();    private long minutesBooked;

byStart is a TreeMap, which keeps its keys sorted, so the bookings are in time order. byId finds a booking from its id. Both maps, and the running total minutesBooked, are guarded by lock, a private object, so code outside the calendar cannot hold it. roomOfBooking is shared by every calendar and maps a booking id to its room. Each calendar writes it only under its own lock. HORIZON is how far ahead a meeting may start: 365 days.

Bookings in one room never overlap. So a new slot can clash only with two bookings: the one that starts at or before the slot's start, and the first one that starts at or after it. Any booking further away is blocked by one of those two:

scheduler/RoomCalendar.javalines 150–169 of 183
    /**     * The booking that overlaps the slot, if any, ignoring the one being moved.     * Bookings in a room never overlap, so only the two neighbours of the     * slot's start can clash with it.     */    private Optional<Booking> clash(TimeSlot slot, String movingId) {        Map.Entry<Instant, Booking> before = byStart.floorEntry(slot.start());        if (before != null && !before.getValue().id().equals(movingId)                && before.getValue().slot().overlaps(slot)) {            return Optional.of(before.getValue());        }        Map.Entry<Instant, Booking> after = byStart.ceilingEntry(slot.start());        if (after != null && after.getValue().id().equals(movingId)) {            after = byStart.higherEntry(after.getKey());        }        if (after != null && after.getValue().slot().overlaps(slot)) {            return Optional.of(after.getValue());        }        return Optional.empty();    }

floorEntry finds the booking that starts at or before the slot, and ceilingEntry the first one that starts at or after it. Each lookup walks down a sorted tree, so it takes O(log n) steps for a room with n bookings. movingId matters only when a meeting moves within its own room, and we come back to it there.

Decision

Find a clash by reading every booking, or by looking at two neighbours?

A list, and compare the slot with every booking

It is simple and correct, and for a room with ten meetings a day it is fast enough. But it reads every booking the room has ever had, the agenda needs a separate sort, and an interviewer will ask what happens with a year of bookings.

A TreeMap by start time, and compare with the two neighboursOur pick

A clash check is two lookups of O(log n) each, and the agenda is already in time order. The cost is a second map by id that must stay in step with the first, and an argument that rests on one rule: no write may ever leave two bookings overlapping.

Adding a meeting

add checks the time, checks for a clash and writes, all under the room's lock:

scheduler/RoomCalendar.javalines 61–74 of 183
    BookingResult add(MeetingRequest request) {        synchronized (lock) {            Optional<Outcome> badTime = badTime(request.slot(), clock.instant());            if (badTime.isPresent()) {                return BookingResult.refused(badTime.get());            }            if (clash(request.slot(), null).isPresent()) {                return BookingResult.refused(Outcome.ROOM_TAKEN);            }            Booking booking = Booking.of(nextId.get(), room.id(), request);            put(booking);            return BookingResult.done(Outcome.BOOKED, booking);        }    }
scheduler/RoomCalendar.javalines 139–148 of 183
    /** A slot may start now or later, and less than 365 days from now. */    private static Optional<Outcome> badTime(TimeSlot slot, Instant now) {        if (slot.start().isBefore(now)) {            return Optional.of(Outcome.IN_THE_PAST);        }        if (!slot.start().isBefore(now.plus(HORIZON))) {            return Optional.of(Outcome.TOO_FAR_AHEAD);        }        return Optional.empty();    }

The calendar reads the clock only after it has the lock, so "now" is the moment it acts, not the moment the request arrived. badTime allows a slot that starts exactly now, answers IN_THE_PAST for one that started a minute ago, and TOO_FAR_AHEAD for one that starts 365 days or more from now. The booking id comes from nextId only after both checks have passed, so a refused request uses no id. put then writes both maps, the total and the shared index:

scheduler/RoomCalendar.javalines 171–182 of 183
    private void put(Booking booking) {        byStart.put(booking.slot().start(), booking);        byId.put(booking.id(), booking);        minutesBooked += booking.slot().length().toMinutes();        roomOfBooking.put(booking.id(), room.id());    }     private void removeEntries(Booking booking) {        byStart.remove(booking.slot().start());        byId.remove(booking.id());        minutesBooked -= booking.slot().length().toMinutes();    }

Choosing a room

book lets the scheduler choose. roomsThatFit first lists the rooms in the meeting's office with enough seats and the equipment asked for, sorted by room id. Which of those to try first is a rule that will change. One company wants the smallest room, so big rooms stay free for big meetings. Another wants the rooms used evenly. So the rule sits behind an interface:

choice/RoomChooser.javalines 8–14 of 14
/** * Puts the rooms that fit a meeting in the order the scheduler should try * them. It may leave rooms out. It must not add rooms that were not offered. */public interface RoomChooser {    List<Room> rank(List<RoomView> fitting, MeetingRequest request);}
choice/SmallestFitChooser.javalines 10–19 of 20
public final class SmallestFitChooser implements RoomChooser {    private static final Comparator<Room> SMALLEST_FIRST = Comparator            .comparingInt(Room::capacity)            .thenComparingInt(room -> room.equipment().size())            .thenComparing(Room::id);     @Override    public List<Room> rank(List<RoomView> fitting, MeetingRequest request) {        return fitting.stream().map(RoomView::room).sorted(SMALLEST_FIRST).toList();    }

A chooser sees each room through RoomView, which offers the Room and minutesBooked and nothing that changes a booking. LeastBookedChooser puts the room with the fewest booked minutes first:

choice/LeastBookedChooser.javalines 13–24 of 25
public final class LeastBookedChooser implements RoomChooser {    @Override    public List<Room> rank(List<RoomView> fitting, MeetingRequest request) {        // Read each count once: a count that changed mid-sort would break the sort.        Map<Room, Long> minutes = fitting.stream()                .collect(Collectors.toMap(RoomView::room, RoomView::minutesBooked));        Comparator<Room> leastBooked = Comparator                .comparing((Function<Room, Long>) minutes::get)                .thenComparingInt(Room::capacity)                .thenComparing(Room::id);        return minutes.keySet().stream().sorted(leastBooked).toList();    }

Each call to minutesBooked takes that room's lock for a moment, and another thread can change the count straight after. So the chooser reads every count once, into a map, before it sorts. A count that changed in the middle of a sort could leave the sort with no consistent order, and Java's sort may then throw.

Decision

Is an interface worth it for choosing a room?

A sort inside book

For one rule this is less code. But every new rule edits RoomScheduler and its tests, and the rule cannot be tested without a scheduler full of rooms.

RoomChooser, with two implementationsOur pick

A new rule is a new class, tested on its own with a few fake views. The cost is one more interface, and the scheduler must not trust the list a chooser returns, which the next snippet handles.

Here is book, and the check on the chooser's answer:

scheduler/RoomScheduler.javalines 64–78 of 185
    /** Books the first room, in the chooser's order, that is free for the whole slot. */    public BookingResult book(MeetingRequest request) {        List<RoomView> fitting = roomsThatFit(request);        List<RoomCalendar> order = inChosenOrder(fitting, request);        if (order.isEmpty()) {            return BookingResult.refused(Outcome.NO_ROOM_FITS);        }        for (RoomCalendar calendar : order) {            BookingResult result = calendar.add(request);            if (result.outcome() != Outcome.ROOM_TAKEN) {                return result;            }        }        return BookingResult.refused(Outcome.ALL_ROOMS_TAKEN);    }
scheduler/RoomScheduler.javalines 160–180 of 185
    /** The chooser's order, checked: it may leave rooms out, but not add or repeat one. */    private List<RoomCalendar> inChosenOrder(List<RoomView> fitting, MeetingRequest request) {        if (fitting.isEmpty()) {            return List.of();        }        List<Room> ranked = chooser.rank(fitting, request);        if (ranked == null) {            throw new IllegalStateException("the room chooser returned no list");        }        Set<String> offered = new HashSet<>();        fitting.forEach(view -> offered.add(view.room().id()));        Set<String> seen = new HashSet<>();        List<RoomCalendar> order = new ArrayList<>();        for (Room room : ranked) {            if (room == null || !offered.contains(room.id()) || !seen.add(room.id())) {                throw new IllegalStateException("the room chooser returned a room it was not offered, or twice: " + room);            }            order.add(calendars.get(room.id()));        }        return order;    }

The scheduler holds no lock while the chooser runs. It then tries each room's add, which checks and writes under that room's lock. A taken room answers ROOM_TAKEN, and the loop moves on. Any other answer, such as BOOKED or IN_THE_PAST, ends the loop. ALL_ROOMS_TAKEN means each room was taken at the moment it was tried; a room tried early can free up while a later one is being tried. A chooser that returns a room it was not offered, or the same room twice, is a bug in our code, so inChosenOrder throws IllegalStateException before anything is booked. A chooser may leave rooms out, and if it leaves out all of them the answer is NO_ROOM_FITS.

Decision

Check which rooms are free and then book one, or rank the rooms and try each?

Ask every room whether it is free, then book the first free one

This reads naturally. But it is two steps, and between them another person can take the room, so the booking step must handle "taken" anyway. The first step adds nothing except a moment in which its answer goes stale.

Rank the rooms, then try each one under its own lockOur pick

The "is it free?" check and the write happen in one locked step per room, so the answer cannot go stale. A taken room moves the loop on to the next room. The cost is that the chooser ranks without knowing which rooms are free, so a busy room can be tried first and refused.

Cancelling

A meeting can be cancelled until it starts:

scheduler/RoomCalendar.javalines 76–89 of 183
    BookingResult cancel(String bookingId) {        synchronized (lock) {            Booking booking = byId.get(bookingId);            if (booking == null) {                return BookingResult.refused(Outcome.NO_SUCH_BOOKING);            }            if (!clock.instant().isBefore(booking.slot().start())) {                return BookingResult.refused(Outcome.ALREADY_STARTED);            }            removeEntries(booking);            roomOfBooking.remove(booking.id(), room.id());            return BookingResult.done(Outcome.CANCELLED, booking);        }    }

At the exact minute a meeting starts, it has started, so a cancel then is ALREADY_STARTED and the booking stays. A cancel removes the booking from both maps and the total, and then its entry from the shared index. Under the room's lock the entry always names this room, so remove(id, room) is a guard against a bug elsewhere, not a case that happens.

Moving a meeting

Weak answers lose meetings when they move them. The obvious version cancels the old booking and books the new slot. If the new slot is taken, the meeting is gone, and the old slot may already belong to someone else.

scheduler/RoomCalendar.javalines 91–125 of 183
    /** Moves a booking to a slot in this room or another, or leaves it exactly where it was. */    static BookingResult move(RoomCalendar from, RoomCalendar to, String bookingId, TimeSlot slot) {        // Every move takes the two locks in room id order, so two moves in opposite directions cannot deadlock.        RoomCalendar first = from.room.id().compareTo(to.room.id()) <= 0 ? from : to;        RoomCalendar second = first == from ? to : from;        synchronized (first.lock) {            synchronized (second.lock) {                Booking old = from.byId.get(bookingId);                if (old == null) {                    return BookingResult.refused(Outcome.NO_SUCH_BOOKING);                }                Instant now = from.clock.instant();                if (!now.isBefore(old.slot().start())) {                    return BookingResult.refused(Outcome.ALREADY_STARTED);                }                Optional<Outcome> badTime = badTime(slot, now);                if (badTime.isPresent()) {                    return BookingResult.refused(badTime.get());                }                if (!to.room.office().equals(from.room.office())) {                    return BookingResult.refused(Outcome.WRONG_OFFICE);                }                if (!to.room.fits(old.attendees(), old.needs())) {                    return BookingResult.refused(Outcome.DOES_NOT_FIT);                }                if (to.clash(slot, old.id()).isPresent()) {                    return BookingResult.refused(Outcome.ROOM_TAKEN);                }                Booking moved = old.movedTo(to.room.id(), slot);                from.removeEntries(old);                to.put(moved);                return BookingResult.done(Outcome.MOVED, moved);            }        }    }

move takes both rooms' locks, then checks everything before it changes anything. The booking must still be here and not yet started. The new slot must be neither in the past nor 365 days or more away, the new room must be in the same office and fit, and the new slot must be free. A room in another office is refused as WRONG_OFFICE rather than DOES_NOT_FIT, so the person knows why, and bookRoom does the same. Only then does it remove the old entries and put the moved booking. A refusal at any check leaves the booking exactly as it was. A move within one room passes the same calendar as from and to. Java's synchronized lock is reentrant, so taking it a second time on the same thread is fine.

Inside its own room, the meeting must not clash with its own old slot. Moving 10:00 to 11:00 half an hour later overlaps the meeting's own old time, so clash skips the entry whose id is movingId. When that entry is the one at or before the new start, any booking before it ends by the meeting's old start, so it cannot clash either.

Decision

Cancel and book again, or move in one step?

Cancel the old booking, then book the new slot

It reuses two methods we already have. But if the new slot is taken, the meeting is lost, and putting it back can fail too, because someone may have taken the old slot in between.

Move in one step, holding both rooms' locksOur pick

Every check runs before any change, so a refused move leaves the meeting where it was, and the booking keeps its id. The cost is that a move takes two locks at once, so the order in which it takes them matters, as the next section shows.

A cancel or a move starts from a booking id, so the scheduler first looks up the booking's room in roomOfBooking. It reads the index without a lock, so the booking may move before the room's lock is taken:

scheduler/RoomScheduler.javalines 136–158 of 185
    /**     * Runs an action on the room that holds the booking. The index is read     * without a lock, so the booking may have moved before the action has the     * room's lock. Then the room answers NO_SUCH_BOOKING, and we read the index again.     */    private BookingResult atBooking(String bookingId, Function<RoomCalendar, BookingResult> action) {        String roomId = roomOfBooking.get(bookingId);        for (int round = 1; roomId != null; round++) {            BookingResult result = action.apply(calendars.get(roomId));            if (result.outcome() != Outcome.NO_SUCH_BOOKING) {                return result;            }            checkRounds(round, bookingId);            roomId = roomOfBooking.get(bookingId);        }        return BookingResult.refused(Outcome.NO_SUCH_BOOKING);    }     private static void checkRounds(int round, String bookingId) {        if (round >= MAX_LOOKUPS) {            throw new IllegalStateException("the index and the rooms disagree about " + bookingId);        }    }

A calendar changes the index only under its own lock, in the same step as its own maps. A move writes the index once, from the old room to the new one, while it holds both locks. So if the scheduler holds a room's lock and the booking is not there, the index has already moved on. The room answers NO_SUCH_BOOKING, the scheduler reads the index again and tries the room it names. If the index has no entry, the booking was cancelled, and the answer stands. A booking that keeps moving can send the lookup round a few times, but a thousand rounds would almost certainly mean the index and the rooms disagree, which is a bug. So checkRounds throws IllegalStateException rather than looping for ever.

Many people, many rooms

When a team's planning week opens, many people book at the same moment, often the same rooms.

Two people, one slot
On the left, there is no lock. Asha checks Ganga at 10:00 and finds it free. Before she adds her meeting, Ravi checks too and finds it free. Both add, and Ganga now holds two meetings at 10:00. On the right, the check and the add run under Ganga's lock, so Ravi waits until Asha has added hers. He then finds 10:00 taken and gets ROOM_TAKEN.On the left, there is no lock. Asha checks Ganga at 10:00 and finds it free. Before she adds her meeting, Ravi checks too and finds it free. Both add, and Ganga now holds two meetings at 10:00. On the right, the check and the add run under Ganga's lock, so Ravi waits until Asha has added hers. He then finds 10:00 taken and gets ROOM_TAKEN.
Without a lock, checking a room and booking it are two steps that can interleave. On the left, there is no lock. Asha checks Ganga at 10:00 and finds it free. Before she adds her meeting, Ravi checks too and finds it free. Both add, and Ganga now holds two meetings at 10:00. On the right, the check and the add run under Ganga's lock, so Ravi waits until Asha has added hers. He then finds 10:00 taken and gets ROOM_TAKEN.

Each room has its own lock, and every method that reads or changes a room's bookings takes it. The lock is held for a few map lookups and writes, except in bookings, which copies the room's whole list. The chooser runs before any lock is taken, and the only outside call under a lock is the clock read. Bookings in different rooms do not wait for each other's locks, with three exceptions: a move holds two rooms, book tries rooms one after another, and LeastBookedChooser takes each fitting room's lock for a moment to read its count.

A move needs two locks, and that is where a deadlock can hide. Suppose one thread moves a meeting from Ganga to Kaveri while another moves one from Kaveri to Ganga, and each takes its source room's lock first:

Two moves in opposite directions
On the left, each move locks its source room first. Thread 1 holds Ganga and waits for Kaveri, while thread 2 holds Kaveri and waits for Ganga, and neither ever moves on. On the right, every move locks the room with the lower id first. Ganga is BLR-1 and Kaveri is BLR-2, so both threads want Ganga first, so thread 2 waits until thread 1 has finished, then takes both locks and moves its meeting.On the left, each move locks its source room first. Thread 1 holds Ganga and waits for Kaveri, while thread 2 holds Kaveri and waits for Ganga, and neither ever moves on. On the right, every move locks the room with the lower id first. Ganga is BLR-1 and Kaveri is BLR-2, so both threads want Ganga first, so thread 2 waits until thread 1 has finished, then takes both locks and moves its meeting.
Taking locks in the order the caller names them can stop both moves for good. On the left, each move locks its source room first. Thread 1 holds Ganga and waits for Kaveri, while thread 2 holds Kaveri and waits for Ganga, and neither ever moves on. On the right, every move locks the room with the lower id first. Ganga is BLR-1 and Kaveri is BLR-2, so both threads want Ganga first, so thread 2 waits until thread 1 has finished, then takes both locks and moves its meeting.

So move sorts the two calendars by room id before it locks them, at lines 94 and 95. Every move takes Ganga's lock, BLR-1, before Kaveri's, BLR-2, whichever way the meeting is going, and no two moves can each hold the lock the other wants.

The project includes a check, demo/RaceCheck.java. Sixteen threads make 10,000 calls each on four rooms: booking a named room, letting the scheduler choose, cancelling, and moving meetings to random rooms and slots. Then two threads move 200 meetings between two rooms in opposite directions, 20,000 times each.

$ java demo.RaceCheck
Calls: 160,000 from 16 threads, on 4 rooms
Threads still running after a minute: 0
Calls that crashed: 0
Times one room holds two meetings at once: 0
Bookings the index points to that their room does not list: 0
Moves between R-1 and R-2 in both directions at once: 40,000, all finished: yes

No call crashed and no thread got stuck, no room held two meetings at once, every booking the index points to is listed by its room, and the opposite moves finished. We also ran the same check with every room lock removed, and every run broke. In some runs, threads were still running after a minute, stuck inside a TreeMap that two threads had changed at once. In others, the index ended up naming rooms that did not hold the booking, and checkRounds stopped the run with an IllegalStateException. Where the opposite moves ran, they either hung or stopped with an exception, from the broken maps or from checkRounds. With the locks back but taken in the order the caller names the rooms, the opposite moves never finished.

Decision

Where does the lock go?

One lock for the whole scheduler

It is correct, and moves need no ordering. But a booking in Bengaluru would wait for every booking in London, although nothing in one room depends on another.

A concurrent sorted map per room, with no lock

ConcurrentSkipListMap makes each lookup and each insert safe on its own. But a booking is a check of two neighbours followed by an insert, and two threads can both pass the check before either inserts.

One lock per room, and two in room id order for a moveOur pick

Everything that must stay consistent, one room's bookings, sits under one lock, so the check and the write are one step. A booking in one room does not wait for a booking in another. The cost is the ordering rule for moves, which one line enforces.

The final design

RoomScheduler routes every request and keeps the index from booking id to room. Each RoomCalendar owns one room's bookings and the lock that guards them. The scheduler reaches the rule for ordering rooms only through RoomChooser, and every calendar reads the time from an injected Clock.

The design we built
The classes from the class diagram, laid out the same way, with names only. Amber badges number the decisions in the table below. MeetingRequest carries 1, TimeSlot carries 2, 3 and 4, RoomCalendar carries 5, 8 and 9, RoomChooser carries 6, and RoomScheduler carries 7. RoomChooser carries a Strategy tag.The classes from the class diagram, laid out the same way, with names only. Amber badges number the decisions in the table below. MeetingRequest carries 1, TimeSlot carries 2, 3 and 4, RoomCalendar carries 5, 8 and 9, RoomChooser carries 6, and RoomScheduler carries 7. RoomChooser carries a Strategy tag.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, laid out the same way, with names only. Amber badges number the decisions in the table below. MeetingRequest carries 1, TimeSlot carries 2, 3 and 4, RoomCalendar carries 5, 8 and 9, RoomChooser carries 6, and RoomScheduler carries 7. RoomChooser carries a Strategy tag.
S.No.The questionWhat we choseWhy
1Should the scheduler check each person's calendar?No: book rooms only, and carry a head countA room needs only the head count; people's calendars belong to another service
2Should a slot include its end minute?[start, end): the end does not belong to the slotMeetings that touch do not clash, and the test is two strict comparisons
3Store wall-clock times or instants?An Instant in every slot, and time zones only at the edgesClashes and "has it started?" are the same comparison in every office
4What should a wall-clock time that does not exist, or happens twice, mean?Refuse a time that does not exist, and take the first of twoA missing time is a typo; the first of two is the first that happens
5Find a clash by reading every booking, or by looking at two neighbours?A TreeMap by start time, and compare with the two neighboursTwo O(log n) lookups, and the agenda is already in time order
6Is an interface worth it for choosing a room?RoomChooser, with two implementationsA new rule is a new class, tested on its own
7Check which rooms are free and then book one, or rank the rooms and try each?Rank the rooms, then try each one under its own lockThe free check and the write are one locked step, so the answer cannot go stale
8Cancel and book again, or move in one step?Move in one step, holding both rooms' locksA refused move leaves the meeting where it was
9Where does the lock go?One lock per room, and two in room id order for a moveOne room's bookings stay consistent, and opposite moves cannot deadlock

Here is Ravi's request for 4 people with a screen at 10:30, end to end, after Asha has taken Ganga at 10:00:

  1. His laptop calls RoomScheduler.book. roomsThatFit lists Ganga, Kaveri and Narmada, the Bengaluru rooms with at least 4 seats and a screen, with no lock held.
  2. book calls inChosenOrder, which calls RoomChooser.rank. This is the outside call, a rule the scheduler does not control, and it runs with no lock held. inChosenOrder then checks that the chooser added no room and repeated none.
  3. book calls Ganga's add. It takes Ganga's lock, reads the clock, and clash finds Asha's meeting through floorEntry. It answers ROOM_TAKEN and releases the lock.
  4. book calls Kaveri's add. It takes Kaveri's lock, finds no clash, gets the id B-2 from nextId, and put writes both maps, the minutes and the index. It releases the lock as it returns.
  5. book hands back BOOKED with booking B-2 in Kaveri, and Ravi's laptop shows it.

A move takes a slightly different path. atBooking first finds the booking's room in the index, and RoomCalendar.move then holds both rooms' locks, taken in room id order, while it runs every check and writes the moved booking.

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.

schedulerRoomScheduler.java
package scheduler; import java.time.Clock;import java.util.ArrayList;import java.util.Comparator;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;import java.util.function.Function; import booking.Booking;import booking.BookingResult;import booking.MeetingRequest;import booking.Outcome;import booking.TimeSlot;import choice.RoomChooser;import choice.RoomView;import room.Room; /** * Books, moves and cancels meetings across every room. It holds no lock of * its own: each room's calendar guards that room's bookings. Things a person * can get wrong come back as an Outcome; a null argument throws. */public final class RoomScheduler {    // A booking that keeps moving can send a lookup round again; this many rounds almost certainly means a bug.    private static final int MAX_LOOKUPS = 1_000;     private final Clock clock;    private final RoomChooser chooser;    private final Map<String, RoomCalendar> calendars = new ConcurrentHashMap<>();    private final Map<String, String> roomOfBooking = new ConcurrentHashMap<>();    private final AtomicLong bookingsMade = new AtomicLong();     public RoomScheduler(Clock clock, RoomChooser chooser) {        this.clock = Objects.requireNonNull(clock, "clock");        this.chooser = Objects.requireNonNull(chooser, "chooser");    }     public void addRoom(Room room) {        Objects.requireNonNull(room, "room");        RoomCalendar calendar = new RoomCalendar(room, clock, roomOfBooking, this::nextBookingId);        if (calendars.putIfAbsent(room.id(), calendar) != null) {            throw new IllegalArgumentException("there is already a room " + room.id());        }    }     /** The rooms in the meeting's office with enough seats and everything it needs, by room id. */    public List<RoomView> roomsThatFit(MeetingRequest request) {        Objects.requireNonNull(request, "request");        return calendars.values().stream()                .filter(calendar -> calendar.room().office().equals(request.office()))                .filter(calendar -> calendar.room().fits(request.attendees(), request.needs()))                .sorted(Comparator.comparing(calendar -> calendar.room().id()))                .map(calendar -> (RoomView) calendar)                .toList();    }     /** Books the first room, in the chooser's order, that is free for the whole slot. */    public BookingResult book(MeetingRequest request) {        List<RoomView> fitting = roomsThatFit(request);        List<RoomCalendar> order = inChosenOrder(fitting, request);        if (order.isEmpty()) {            return BookingResult.refused(Outcome.NO_ROOM_FITS);        }        for (RoomCalendar calendar : order) {            BookingResult result = calendar.add(request);            if (result.outcome() != Outcome.ROOM_TAKEN) {                return result;            }        }        return BookingResult.refused(Outcome.ALL_ROOMS_TAKEN);    }     /** Books one named room, for someone who picked it themselves. */    public BookingResult bookRoom(String roomId, MeetingRequest request) {        Objects.requireNonNull(roomId, "roomId");        Objects.requireNonNull(request, "request");        RoomCalendar calendar = calendars.get(roomId);        if (calendar == null) {            return BookingResult.refused(Outcome.NO_SUCH_ROOM);        }        Room room = calendar.room();        if (!room.office().equals(request.office())) {            return BookingResult.refused(Outcome.WRONG_OFFICE);        }        if (!room.fits(request.attendees(), request.needs())) {            return BookingResult.refused(Outcome.DOES_NOT_FIT);        }        return calendar.add(request);    }     public BookingResult cancel(String bookingId) {        Objects.requireNonNull(bookingId, "bookingId");        return atBooking(bookingId, calendar -> calendar.cancel(bookingId));    }     /** Moves a booking to a new slot, in the same room or another. If the move fails, nothing changes. */    public BookingResult reschedule(String bookingId, String roomId, TimeSlot slot) {        Objects.requireNonNull(bookingId, "bookingId");        Objects.requireNonNull(roomId, "roomId");        Objects.requireNonNull(slot, "slot");        RoomCalendar target = calendars.get(roomId);        if (target == null) {            return BookingResult.refused(Outcome.NO_SUCH_ROOM);        }        return atBooking(bookingId, from -> RoomCalendar.move(from, target, bookingId, slot));    }     public Optional<Booking> find(String bookingId) {        Objects.requireNonNull(bookingId, "bookingId");        String roomId = roomOfBooking.get(bookingId);        for (int round = 1; roomId != null; round++) {            Optional<Booking> booking = calendars.get(roomId).find(bookingId);            if (booking.isPresent()) {                return booking;            }            checkRounds(round, bookingId);            roomId = roomOfBooking.get(bookingId);        }        return Optional.empty();    }     /** A room's bookings in time order, or empty for a room id that does not exist. */    public Optional<List<Booking>> agenda(String roomId) {        Objects.requireNonNull(roomId, "roomId");        RoomCalendar calendar = calendars.get(roomId);        return calendar == null ? Optional.empty() : Optional.of(calendar.bookings());    }     /**     * Runs an action on the room that holds the booking. The index is read     * without a lock, so the booking may have moved before the action has the     * room's lock. Then the room answers NO_SUCH_BOOKING, and we read the index again.     */    private BookingResult atBooking(String bookingId, Function<RoomCalendar, BookingResult> action) {        String roomId = roomOfBooking.get(bookingId);        for (int round = 1; roomId != null; round++) {            BookingResult result = action.apply(calendars.get(roomId));            if (result.outcome() != Outcome.NO_SUCH_BOOKING) {                return result;            }            checkRounds(round, bookingId);            roomId = roomOfBooking.get(bookingId);        }        return BookingResult.refused(Outcome.NO_SUCH_BOOKING);    }     private static void checkRounds(int round, String bookingId) {        if (round >= MAX_LOOKUPS) {            throw new IllegalStateException("the index and the rooms disagree about " + bookingId);        }    }     /** The chooser's order, checked: it may leave rooms out, but not add or repeat one. */    private List<RoomCalendar> inChosenOrder(List<RoomView> fitting, MeetingRequest request) {        if (fitting.isEmpty()) {            return List.of();        }        List<Room> ranked = chooser.rank(fitting, request);        if (ranked == null) {            throw new IllegalStateException("the room chooser returned no list");        }        Set<String> offered = new HashSet<>();        fitting.forEach(view -> offered.add(view.room().id()));        Set<String> seen = new HashSet<>();        List<RoomCalendar> order = new ArrayList<>();        for (Room room : ranked) {            if (room == null || !offered.contains(room.id()) || !seen.add(room.id())) {                throw new IllegalStateException("the room chooser returned a room it was not offered, or twice: " + room);            }            order.add(calendars.get(room.id()));        }        return order;    }     private String nextBookingId() {        return "B-" + bookingsMade.incrementAndGet();    }}
Click a class name in the code to open its fileJava · 185 lines · 1045 in the project

demo/Main.java runs a Friday morning in the Bengaluru office from 09:00, then two nights in London when the clocks change. It ends with the clock moved on to 11:05:

$ java demo.Main
It is 09:00 IST on Friday 27 March in Bengaluru.
Asha, 4 people with a screen, 10:00 to 11:00: BOOKED B-1 in Ganga
Ravi, 4 people with a screen, 10:30 to 11:30: BOOKED B-2 in Kaveri
Meera picks Ganga, 11:00 to 12:00: BOOKED B-3 in Ganga
Kabir picks Ganga, 09:30 to 10:15: ROOM_TAKEN
Zoya, 20 people: NO_ROOM_FITS
Dev, 08:30 to 09:30: IN_THE_PAST
Asha moves B-1 to 10:30 to 11:30 in Ganga: ROOM_TAKEN. It is still 10:00 IST to 11:00 IST in Ganga
Asha moves B-1 to 10:30 to 11:30 in Narmada: MOVED B-1 in Narmada
Ravi cancels B-2: CANCELLED B-2
Ravi cancels B-2 again: NO_SUCH_BOOKING
A meeting of 3 with a screen fits: Ganga, Kaveri, Narmada
  Ganga has 60 minutes booked
  Kaveri has 0 minutes booked
  Narmada has 60 minutes booked
Smallest fit tries: Ganga, Kaveri, Narmada
Least booked tries: Kaveri, Ganga, Narmada
Ganga's day:
  B-3 11:00 IST to 12:00 IST, Meera
Priya picks Thames, 00:30 to 03:30 London time on Sunday 29 March: BOOKED B-4
  It runs 00:30 GMT to 03:30 BST, 2 hours
A slot from 01:30 London time that night: refused, 2026-03-29T01:30 does not exist in Europe/London: the clocks skip it
01:30 on Sunday 25 October happens twice in London. The slot starts at 01:30 BST (2026-10-25T00:30:00Z) and is 2 hours
It is 11:05 IST.
Meera cancels B-3: ALREADY_STARTED
Asha moves B-1 to 16:00 to 17:00: ALREADY_STARTED

Notice four things in the output. Ravi's meeting clashed with Asha's in Ganga, so it went to Kaveri, the next smallest room, while Meera's meeting from 11:00 fitted right after Asha's. Asha's first move ran into Meera's meeting and changed nothing, so B-1 was still 10:00 to 11:00 in Ganga, and her second move took it to Narmada. With Ravi's meeting cancelled, Kaveri had 0 minutes booked, so the least-booked rule tried it first while the smallest-fit rule tried Ganga first. Priya's meeting across the night the clocks went forward lasted 2 hours, and a slot from 01:30 that night was refused.

Follow-up questions

After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Check that everyone invited is free."MeetingRequest gains a list of people, and a new interface to the calendar service holds their time while the room is booked, then confirms both or releases both, as the BookMyShow page does with seats.RoomCalendar, TimeSlot, the choosers.
"Book every Monday at 10:00."A recurrence on the request expands into slots in the office's zone, so 10:00 stays 10:00 after the clocks change, and a new method books every slot in the room or none.The clash check, TimeSlot.
"Run on many servers."Bookings move to a database: a row per booking, with a constraint that refuses two overlapping rows for one room, such as an exclusion constraint in PostgreSQL. Booking ids come from the database, and the index becomes a column.The choosers, TimeSlot, the outcomes.
"Only the organiser can cancel or move a meeting."cancel and reschedule take who is asking, so their signatures change, and the calendar compares it with the booking's organiser under the lock.The clash check, the choosers.
"Free a room nobody walked into."A check-in method on RoomCalendar, and a job that removes a meeting with no check-in 10 minutes after its start. cancel refuses a started meeting, so this needs its own method.Booking, the choosers.
"Suggest the next free time."A method on RoomCalendar that walks byStart from a given time to the first gap long enough, and a scheduler method that asks every fitting room.The clash check, the locks.
"Prefer a room on my floor."Room gains a floor, MeetingRequest carries the person's floor, and a new chooser ranks rooms on that floor first.RoomScheduler, RoomCalendar.
"Tell people when a meeting moves."A list of listeners on the scheduler, called after the room's lock is released. This is the Observer pattern.Booking, moving, the choosers.

In most rows the change lands in one class or behind one interface. The row about many servers is the big one: the bookings move out of memory, and the clash rule becomes a constraint the database keeps.

What the interviewer looks for

Mid-level

A mid-level candidate shows clear classes for a room, a booking and a time slot, a check that a new meeting does not overlap an existing one, and refusals for a room that is too small. They notice that two people can book at once, and they add a lock.

Senior

A senior candidate shows everything above and gives the reasons. They make slots half-open so that meetings can touch, and they sort a room's bookings so a clash check looks at two neighbours. They put the choice of room behind an interface. They move a meeting in one step, so a refused move loses nothing, and they take a clock so "has it started?" can be tested.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They store instants and handle the nights the clocks change. They point out that a move holds two locks and take them in a fixed order. They explain why the index can be stale and how the scheduler recovers, and they describe how the clash rule becomes a database constraint when there is more than one server.

Common mistakes

  • Letting a slot include its end. Then 10:00 to 11:00 and 11:00 to 12:00 clash, and people start booking 10:00 to 10:59.
  • Comparing a new meeting with every booking. It works, but it reads the room's whole history on every booking, and the agenda still needs sorting.
  • Checking that a room is free, then booking it in a second step. Two people both see the room free, and both get it.
  • Moving a meeting by cancelling it and booking again. If the new slot is taken, the meeting is gone, and the old slot may already be someone else's.
  • Taking two locks in the order the caller names the rooms. Two moves in opposite directions can each hold the lock the other needs, for ever.
  • Storing wall-clock times. On the nights the clocks change, one typed time means no moment or two.
  • Trusting whatever the chooser returns. A buggy rule could book a room in the wrong office, or one too small for the meeting.

Summary

  • Ask before designing. Whether people's calendars are part of the question changes the whole design.
  • Make slots half-open, [start, end), so meetings can touch, and test a clash as "each starts before the other ends".
  • Store instants, and use an office's time zone only when people type or read a time. Refuse a time the clocks skip.
  • Keep each room's bookings in a TreeMap by start, so a clash check compares only two neighbours.
  • Put the order of rooms behind RoomChooser, and check the list it returns. That is the Strategy pattern.
  • Move a meeting in one step, checking everything before changing anything, with both rooms locked in room id order.
  • Give each room its own lock, read the clock under it, and let the scheduler retry when a booking has moved.

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.