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

Design a Restaurant Management System: LLD

The restaurant machine coding question, solved end to end: tables with time-slot reservations, a walk-in waitlist, two hosts racing for one table, orders with modifiers fired to grill and bar stations as commands, a kitchen ticket state machine, stock deducted all or nothing with low-stock observers, bill splitting strategies with tips, staff permissions and a full Java 17 solution.

Reported atCitiZomato

Patterns usedObserverStrategyCommandState

  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 / 22

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, 600 lines, with a small main() demo. Save it as RestaurantManagement.java, then run javac RestaurantManagement.java && java RestaurantManagement.

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** A restaurant: reservations, walk-ins and a waitlist, orders fired to kitchen stations, stock and bills. */
public class RestaurantManagement {

    // ---------- staff, roles and permissions ----------
    enum Permission { RESERVE, SEAT, TAKE_ORDER, COOK, VOID_FIRED, CLOSE_BILL }

    enum Role {
        HOST(EnumSet.of(Permission.RESERVE, Permission.SEAT)),
        WAITER(EnumSet.of(Permission.SEAT, Permission.TAKE_ORDER, Permission.CLOSE_BILL)),
        CHEF(EnumSet.of(Permission.COOK)),
        MANAGER(EnumSet.allOf(Permission.class));

        private final Set<Permission> allowed;
        Role(Set<Permission> allowed) { this.allowed = allowed; }
        boolean can(Permission p) { return allowed.contains(p); }
    }

    record Staff(String name, Role role) {
        void require(Permission p) {
            if (!role.can(p)) throw new SecurityException(name + " (" + role + ") may not " + p);
        }
    }

    // ---------- menu and order lines ----------
    enum Station { GRILL, BAR }

    record Modifier(String code, long priceCents, Map<String, Integer> ingredients) {}

    record MenuItem(String id, long priceCents, Station station, Map<String, Integer> recipe,
                    Map<String, Modifier> modifiers) {}

    /** One line of an order. guest 0 means the line is shared by the whole table. */
    record OrderItem(int line, MenuItem item, int qty, List<Modifier> mods, int guest) {
        long totalCents() {
            long unit = item.priceCents();
            for (Modifier m : mods) unit += m.priceCents();
            return unit * qty;
        }

        Map<String, Integer> ingredients() {
            Map<String, Integer> need = new TreeMap<>();
            item.recipe().forEach((k, v) -> need.merge(k, v * qty, Integer::sum));
            for (Modifier m : mods) {
                m.ingredients().forEach((k, v) -> need.merge(k, v * qty, Integer::sum));
            }
            return need;
        }

        String label() {
            StringBuilder sb = new StringBuilder(qty + "x " + item.id());
            for (Modifier m : mods) sb.append(" +").append(m.code());
            return sb.toString();
        }
    }

    // ---------- inventory (Observer for low stock) ----------
    interface StockListener { void lowStock(String ingredient, long left); }

    static final class Inventory {
        private final Map<String, Long> stock = new TreeMap<>();     // guarded by this
        private final Map<String, Long> lowAt = new TreeMap<>();     // guarded by this
        private final List<StockListener> listeners = new CopyOnWriteArrayList<>();

        synchronized void add(String ingredient, long qty, long alertAt) {
            stock.merge(ingredient, qty, Long::sum);
            lowAt.put(ingredient, alertAt);
        }

        void subscribe(StockListener l) { listeners.add(l); }

        /** All or nothing: every ingredient is taken, or none is. Alerts go out after the lock. */
        void consume(Map<String, Integer> need) {
            Map<String, Long> crossed = new TreeMap<>();
            synchronized (this) {
                for (Map.Entry<String, Integer> e : need.entrySet()) {
                    if (stock.getOrDefault(e.getKey(), 0L) < e.getValue()) {
                        throw new IllegalStateException("out of " + e.getKey());
                    }
                }
                for (Map.Entry<String, Integer> e : need.entrySet()) {
                    long before = stock.get(e.getKey());
                    long after = before - e.getValue();
                    stock.put(e.getKey(), after);
                    long limit = lowAt.getOrDefault(e.getKey(), 0L);
                    if (before > limit && after <= limit) crossed.put(e.getKey(), after);   // alert once
                }
            }
            crossed.forEach((k, left) -> listeners.forEach(l -> l.lowStock(k, left)));
        }

        synchronized void restock(Map<String, Integer> back) {
            back.forEach((k, v) -> stock.merge(k, (long) v, Long::sum));
        }

        synchronized long left(String ingredient) { return stock.getOrDefault(ingredient, 0L); }
    }

    // ---------- kitchen tickets (State) and stations ----------
    enum TicketStatus {
        QUEUED, COOKING, READY, SERVED, VOIDED;

        boolean canMoveTo(TicketStatus next) {
            return switch (this) {
                case QUEUED -> next == COOKING || next == VOIDED;
                case COOKING -> next == READY;
                case READY -> next == SERVED;
                case SERVED, VOIDED -> false;
            };
        }
    }

    static final class KitchenTicket {
        final String id;
        final int table;
        final OrderItem item;
        private final AtomicReference<TicketStatus> status = new AtomicReference<>(TicketStatus.QUEUED);

        KitchenTicket(String id, int table, OrderItem item) {
            this.id = id;
            this.table = table;
            this.item = item;
        }

        /** Compare-and-set: a chef starting and a manager voiding the same ticket cannot both win. */
        boolean move(TicketStatus from, TicketStatus to) {
            if (!from.canMoveTo(to)) throw new IllegalStateException(id + ": " + from + " -> " + to);
            return status.compareAndSet(from, to);
        }

        void advance(TicketStatus from, TicketStatus to) {
            if (!move(from, to)) throw new IllegalStateException(id + " is " + status.get());
        }

        TicketStatus status() { return status.get(); }

        @Override
        public String toString() { return id + " T" + table + " " + item.label() + " " + status.get(); }
    }

    static final class KitchenStation {
        private final Queue<KitchenTicket> queue = new ConcurrentLinkedQueue<>();

        void enqueue(KitchenTicket t) { queue.add(t); }
        /** The chef takes the oldest ticket that is still queued; voided tickets are skipped. */
        Optional<KitchenTicket> next() {
            for (KitchenTicket t = queue.poll(); t != null; t = queue.poll()) {
                if (t.move(TicketStatus.QUEUED, TicketStatus.COOKING)) return Optional.of(t);
            }
            return Optional.empty();
        }

        long waiting() { return queue.stream().filter(t -> t.status() == TicketStatus.QUEUED).count(); }
    }

    // ---------- Command: fire one line to the kitchen, or take it back ----------
    interface KitchenCommand {
        void execute();
        boolean undo();
    }

    record FireLine(KitchenTicket ticket, Inventory inventory, KitchenStation station)
            implements KitchenCommand {
        @Override
        public void execute() {
            inventory.consume(ticket.item.ingredients());   // throws when stock is short: nothing is queued
            station.enqueue(ticket);
        }

        /** Only a ticket nobody has started can be taken back; its ingredients return to stock. */
        @Override
        public boolean undo() {
            if (!ticket.move(TicketStatus.QUEUED, TicketStatus.VOIDED)) return false;
            inventory.restock(ticket.item.ingredients());
            return true;
        }
    }

    // ---------- tables, reservations, orders, bills ----------
    record Reservation(String id, String party, int size, int table, LocalDateTime start, LocalDateTime end) {
        /** Half-open slots: a sitting that ends at 20:00 does not clash with a booking at 20:00. */
        boolean overlaps(LocalDateTime from, LocalDateTime to) {
            return start.isBefore(to) && from.isBefore(end);
        }
    }

    record WaitingParty(String party, int size, LocalDateTime since) {}

    /** The unit of locking for seating: the seated party and the reservations are guarded by the table. */
    static final class Table {
        final int number;
        final int seats;
        private String seatedParty;
        private final List<Reservation> reservations = new ArrayList<>();

        Table(int number, int seats) {
            this.number = number;
            this.seats = seats;
        }

        /** Call with the lock held. A party may sit over its own reservation, not over someone else's. */
        boolean blocked(LocalDateTime from, LocalDateTime to, String party) {
            return reservations.stream().anyMatch(r -> !r.party().equals(party) && r.overlaps(from, to));
        }
    }

    static final class Order {
        final String id;
        final int table;
        private final List<OrderItem> items = new ArrayList<>();          // all fields guarded by this
        private final Map<Integer, FireLine> fired = new HashMap<>();
        private final Set<Integer> voided = new HashSet<>();
        private boolean paid;

        Order(String id, int table) {
            this.id = id;
            this.table = table;
        }
    }

    record FireResult(List<KitchenTicket> sent, List<String> rejected) {}

    record Bill(String order, long subtotalCents, long taxCents, long tipCents, List<Long> shares) {
        long totalCents() { return subtotalCents + taxCents + tipCents; }

        @Override
        public String toString() {
            List<String> each = shares.stream().map(RestaurantManagement::money).toList();
            return order + " subtotal " + money(subtotalCents) + ", tax " + money(taxCents) + ", tip "
                    + money(tipCents) + ", total " + money(totalCents()) + ", shares " + each;
        }
    }

    // ---------- bill splitting (Strategy) ----------
    interface SplitStrategy {
        List<Long> shares(List<OrderItem> items, long subtotal, long total, int guests);
    }

    /** Divide exactly: the leftover paise go to the first guests, so the shares always add up. */
    static List<Long> spread(long amount, int ways) {
        List<Long> out = new ArrayList<>();
        for (int i = 0; i < ways; i++) out.add(amount / ways + (i < amount % ways ? 1 : 0));
        return out;
    }

    static final class EqualSplit implements SplitStrategy {
        @Override
        public List<Long> shares(List<OrderItem> items, long subtotal, long total, int guests) {
            return spread(total, guests);
        }
    }

    /** Each guest pays their own lines, an even part of shared lines, and tax and tip in proportion. */
    static final class ByItemSplit implements SplitStrategy {
        @Override
        public List<Long> shares(List<OrderItem> items, long subtotal, long total, int guests) {
            long[] own = new long[guests];
            for (OrderItem it : items) {
                if (it.guest() == 0) {
                    List<Long> part = spread(it.totalCents(), guests);
                    for (int g = 0; g < guests; g++) own[g] += part.get(g);
                } else {
                    own[it.guest() - 1] += it.totalCents();
                }
            }
            long extra = total - subtotal;                              // tax plus tip
            List<Long> out = new ArrayList<>();
            long sum = 0;
            for (int g = 0; g < guests; g++) {
                long share = own[g] + (subtotal == 0 ? 0 : extra * own[g] / subtotal);
                out.add(share);
                sum += share;
            }
            out.set(0, out.get(0) + total - sum);                       // rounding leftover to guest 1
            return out;
        }
    }

    // ---------- the service ----------
    private static final int TAX_PERCENT = 5;
    private final Map<Integer, Table> tables = new LinkedHashMap<>();          // smallest first, fixed
    private final Map<String, MenuItem> menu = new HashMap<>();                // fixed after start
    private final Map<Station, KitchenStation> stations = new EnumMap<>(Station.class);
    private final Map<Integer, Order> openOrders = new ConcurrentHashMap<>();
    private final Deque<WaitingParty> waitlist = new ArrayDeque<>();           // guarded by itself
    private final AtomicLong ids = new AtomicLong();
    private final Supplier<LocalDateTime> clock;
    private final Duration sitting;
    final Inventory inventory = new Inventory();

    RestaurantManagement(List<Table> tableList, List<MenuItem> items, Supplier<LocalDateTime> clock,
                         Duration sitting) {
        List<Table> sorted = new ArrayList<>(tableList);
        sorted.sort(Comparator.comparingInt((Table t) -> t.seats).thenComparingInt(t -> t.number));
        for (Table t : sorted) tables.put(t.number, t);
        for (MenuItem m : items) menu.put(m.id(), m);
        for (Station s : Station.values()) stations.put(s, new KitchenStation());
        this.clock = clock;
        this.sitting = sitting;
    }

    /** Book the smallest table that fits and is free for the whole slot. */
    Reservation reserve(Staff by, String party, int size, LocalDateTime start) {
        by.require(Permission.RESERVE);
        LocalDateTime end = start.plus(sitting);
        for (Table t : tables.values()) {
            if (t.seats < size) continue;
            synchronized (t) {
                if (t.blocked(start, end, party)) continue;
                String id = "R" + ids.incrementAndGet();
                Reservation r = new Reservation(id, party, size, t.number, start, end);
                t.reservations.add(r);
                return r;
            }
        }
        throw new IllegalStateException("no table for " + size + " at " + start.toLocalTime());
    }

    /** Seat a party at one given table: the host picked it on the floor plan. */
    Optional<Order> seatAt(Staff by, int tableNo, String party, int size) {
        by.require(Permission.SEAT);
        return claim(table(tableNo), party, size);
    }

    /** A walk-in sits at the smallest free table that fits, or joins the waitlist. */
    Optional<Order> walkIn(Staff by, String party, int size) {
        by.require(Permission.SEAT);
        for (Table t : tables.values()) {
            Optional<Order> o = claim(t, party, size);
            if (o.isPresent()) return o;
        }
        synchronized (waitlist) { waitlist.addLast(new WaitingParty(party, size, clock.get())); }
        return Optional.empty();
    }

    /** Check and claim under the table lock: two hosts can never seat the same table twice. */
    private Optional<Order> claim(Table t, String party, int size) {
        LocalDateTime now = clock.get();
        synchronized (t) {
            if (t.seatedParty != null || t.seats < size || t.blocked(now, now.plus(sitting), party)) {
                return Optional.empty();
            }
            t.seatedParty = party;
            Order o = new Order("O" + ids.incrementAndGet(), t.number);
            openOrders.put(t.number, o);
            return Optional.of(o);
        }
    }

    int addItem(Staff by, int tableNo, int guest, String itemId, int qty, String... modCodes) {
        by.require(Permission.TAKE_ORDER);
        MenuItem m = menu.get(itemId);
        if (m == null) throw new IllegalArgumentException("not on the menu: " + itemId);
        List<Modifier> mods = new ArrayList<>();
        for (String code : modCodes) {
            Modifier mod = m.modifiers().get(code);
            if (mod == null) throw new IllegalArgumentException(code + " is not allowed on " + itemId);
            mods.add(mod);
        }
        Order o = openOrder(tableNo);
        synchronized (o) {
            int line = o.items.size() + 1;
            o.items.add(new OrderItem(line, m, qty, List.copyOf(mods), guest));
            return line;
        }
    }

    /** Send every new line to its station. Each line is a command: take the stock, then queue a ticket. */
    FireResult fire(Staff by, int tableNo) {
        by.require(Permission.TAKE_ORDER);
        Order o = openOrder(tableNo);
        List<KitchenTicket> sent = new ArrayList<>();
        List<String> rejected = new ArrayList<>();
        synchronized (o) {                          // lock order: order, then inventory, never the reverse
            for (OrderItem it : o.items) {
                if (o.fired.containsKey(it.line()) || o.voided.contains(it.line())) continue;
                KitchenTicket t = new KitchenTicket("K" + ids.incrementAndGet(), tableNo, it);
                FireLine cmd = new FireLine(t, inventory, stations.get(it.item().station()));
                try {
                    cmd.execute();
                    o.fired.put(it.line(), cmd);
                    sent.add(t);
                } catch (IllegalStateException e) {
                    o.voided.add(it.line());        // the waiter tells the guest; the line is never billed
                    rejected.add(it.label() + ": " + e.getMessage());
                }
            }
        }
        return new FireResult(sent, rejected);
    }

    /** Take a line back. Managers only, and a fired line only while no chef has started it. */
    boolean voidLine(Staff by, int tableNo, int line) {
        by.require(Permission.VOID_FIRED);
        Order o = openOrder(tableNo);
        synchronized (o) {
            FireLine cmd = o.fired.get(line);
            if (cmd != null && !cmd.undo()) return false;   // already cooking: too late
            o.voided.add(line);
            return true;
        }
    }

    Optional<KitchenTicket> startNext(Staff chef, Station station) {
        chef.require(Permission.COOK);
        return stations.get(station).next();
    }

    void markReady(Staff chef, KitchenTicket t) {
        chef.require(Permission.COOK);
        t.advance(TicketStatus.COOKING, TicketStatus.READY);
    }

    void serve(Staff waiter, KitchenTicket t) {
        waiter.require(Permission.TAKE_ORDER);
        t.advance(TicketStatus.READY, TicketStatus.SERVED);
    }

    /** Bill the table, mark it paid once, free the table and offer it to the waitlist. */
    Bill closeBill(Staff by, int tableNo, int tipPercent, SplitStrategy split, int guests) {
        by.require(Permission.CLOSE_BILL);
        Order o = openOrder(tableNo);
        Bill bill;
        synchronized (o) {
            if (o.paid) throw new IllegalStateException(o.id + " is already paid");
            List<OrderItem> billable = new ArrayList<>();
            long subtotal = 0;
            for (OrderItem it : o.items) {
                if (o.voided.contains(it.line())) continue;
                if (it.guest() > guests) throw new IllegalArgumentException("no guest for line " + it.line());
                billable.add(it);
                subtotal += it.totalCents();
            }
            long tax = (subtotal * TAX_PERCENT + 50) / 100;            // half up, to the paisa
            long tip = (subtotal * tipPercent + 50) / 100;             // tip on the food, not on the tax
            long total = subtotal + tax + tip;
            bill = new Bill(o.id, subtotal, tax, tip, split.shares(billable, subtotal, total, guests));
            o.paid = true;
        }
        openOrders.remove(tableNo);
        Table t = table(tableNo);
        synchronized (t) { t.seatedParty = null; }
        seatFromWaitlist(t);
        return bill;
    }

    /** A table just freed: give it to the first waiting party that fits. */
    private void seatFromWaitlist(Table t) {
        WaitingParty next = null;
        synchronized (waitlist) {
            for (Iterator<WaitingParty> it = waitlist.iterator(); it.hasNext(); ) {
                WaitingParty w = it.next();
                if (w.size() <= t.seats) {
                    it.remove();
                    next = w;
                    break;
                }
            }
        }
        if (next == null) return;
        if (claim(t, next.party(), next.size()).isPresent()) {
            System.out.println("  [host stand] " + next.party() + " seated at T" + t.number);
        } else {
            synchronized (waitlist) { waitlist.addFirst(next); }   // someone was faster: keep their place
        }
    }

    List<String> waitlist() {
        synchronized (waitlist) {
            return waitlist.stream().map(w -> w.party() + " (" + w.size() + ")").toList();
        }
    }

    long waiting(Station s) { return stations.get(s).waiting(); }

    private Table table(int n) {
        Table t = tables.get(n);
        if (t == null) throw new IllegalArgumentException("no table " + n);
        return t;
    }

    private Order openOrder(int tableNo) {
        Order o = openOrders.get(tableNo);
        if (o == null) throw new IllegalStateException("no open order at T" + tableNo);
        return o;
    }

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

    // ---------- demo ----------
    public static void main(String[] args) throws InterruptedException {
        AtomicReference<LocalDateTime> now = new AtomicReference<>(LocalDateTime.of(2026, 12, 12, 18, 30));
        MenuItem burger = new MenuItem("BURGER", 320_00, Station.GRILL, Map.of("patty", 1, "bun", 1), Map.of(
                "CHEESE", new Modifier("CHEESE", 40_00, Map.of("cheese", 1)),
                "NO_ONION", new Modifier("NO_ONION", 0, Map.of())));
        MenuItem fries = new MenuItem("FRIES", 150_00, Station.GRILL, Map.of("potato", 2), Map.of());
        MenuItem mojito = new MenuItem("MOJITO", 220_00, Station.BAR, Map.of("lime", 2, "mint", 1),
                Map.of("EXTRA_MINT", new Modifier("EXTRA_MINT", 20_00, Map.of("mint", 1))));
        MenuItem soda = new MenuItem("LIME_SODA", 90_00, Station.BAR, Map.of("lime", 1), Map.of());
        RestaurantManagement r = new RestaurantManagement(
                List.of(new Table(1, 2), new Table(2, 4), new Table(3, 4), new Table(4, 6)),
                List.of(burger, fries, mojito, soda), now::get, Duration.ofMinutes(90));
        r.inventory.add("patty", 10, 3);
        r.inventory.add("bun", 20, 5);
        r.inventory.add("cheese", 6, 2);
        r.inventory.add("potato", 12, 4);
        r.inventory.add("lime", 8, 3);
        r.inventory.add("mint", 6, 2);
        r.inventory.subscribe((item, left) -> System.out.println("  [alert] low stock: " + item + ", " + left
                + " left"));

        Staff host = new Staff("host-1", Role.HOST);
        Staff waiter = new Staff("waiter-1", Role.WAITER);
        Staff chef = new Staff("chef-1", Role.CHEF);
        Staff manager = new Staff("manager-1", Role.MANAGER);
        Reservation office = r.reserve(host, "office team", 6, LocalDateTime.of(2026, 12, 12, 19, 30));
        Reservation couple = r.reserve(host, "anniversary", 2, LocalDateTime.of(2026, 12, 12, 20, 0));
        System.out.println("reserved: " + office.party() + " T" + office.table() + " 19:30, "
                + couple.party() + " T" + couple.table() + " 20:00");
        System.out.println("walkin-a (6): " + r.walkIn(host, "walkin-a", 6).map(o -> "T" + o.table)
                .orElse("waitlist, T4 is booked at 19:30"));
        System.out.println("walkin-b (2): T" + r.walkIn(host, "walkin-b", 2).orElseThrow().table
                + " (leaves before the 20:00 booking)");

        // Eight hosts tap "seat" on table 2 at the same moment: exactly one party gets it.
        AtomicInteger seated = new AtomicInteger(), refused = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch go = new CountDownLatch(1);
        for (int i = 0; i < 8; i++) {
            String party = "racer-" + i;
            pool.submit(() -> {
                try {
                    go.await();
                    if (r.seatAt(host, 2, party, 4).isPresent()) seated.incrementAndGet();
                    else refused.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        go.countDown();
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("race for T2: " + seated.get() + " seated, " + refused.get() + " refused");
        if (seated.get() != 1) throw new AssertionError("two parties at one table");
        System.out.println("walkin-c (4): T" + r.walkIn(host, "walkin-c", 4).orElseThrow().table);
        r.walkIn(host, "walkin-d", 3);
        System.out.println("waitlist: " + r.waitlist());

        r.addItem(waiter, 2, 1, "BURGER", 1, "CHEESE");
        r.addItem(waiter, 2, 1, "MOJITO", 1);
        r.addItem(waiter, 2, 2, "BURGER", 1, "NO_ONION");
        int sodaLine = r.addItem(waiter, 2, 2, "LIME_SODA", 1);
        r.addItem(waiter, 2, 0, "FRIES", 2);
        try {
            r.addItem(waiter, 2, 1, "FRIES", 1, "CHEESE");
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
        System.out.println("fired: " + r.fire(waiter, 2).sent());
        System.out.println("queues: grill " + r.waiting(Station.GRILL) + ", bar " + r.waiting(Station.BAR)
                + ", lime left " + r.inventory.left("lime"));
        try {
            r.voidLine(waiter, 2, sodaLine);
        } catch (SecurityException e) {
            System.out.println("waiter void: " + e.getMessage());
        }
        System.out.println("manager voids line " + sodaLine + ": " + r.voidLine(manager, 2, sodaLine)
                + ", lime left " + r.inventory.left("lime"));
        KitchenTicket first = r.startNext(chef, Station.GRILL).orElseThrow();
        System.out.println("manager voids line 1 while cooking: " + r.voidLine(manager, 2, 1));
        r.markReady(chef, first);
        r.serve(waiter, first);
        System.out.println("kitchen: " + first);
        r.addItem(waiter, 3, 0, "BURGER", 6);
        r.addItem(waiter, 3, 0, "LIME_SODA", 1);
        System.out.println("T3 fired " + r.fire(waiter, 3).sent().size() + " lines, patty left "
                + r.inventory.left("patty"));
        r.addItem(waiter, 3, 0, "BURGER", 3);
        System.out.println("T3 rejected: " + r.fire(waiter, 3).rejected());
        Bill b2 = r.closeBill(waiter, 2, 10, new ByItemSplit(), 2);
        System.out.println("T2 by item: " + b2);
        Bill b3 = r.closeBill(waiter, 3, 0, new EqualSplit(), 4);
        System.out.println("T3 equal:   " + b3);
        long sum = b3.shares().stream().mapToLong(Long::longValue).sum();
        if (sum != b3.totalCents()) throw new AssertionError("shares do not add up");

        now.set(LocalDateTime.of(2026, 12, 12, 19, 30));
        Order late = r.seatAt(host, office.table(), office.party(), office.size()).orElseThrow();
        System.out.println("19:30 " + office.party() + " at T" + late.table + ", waiting: " + r.waitlist());
    }
}

Notes

Requirements

Fix the scope. The restaurant has tables of two, four and six seats. Guests reserve a ninety minute slot or walk in, and join a waitlist when nothing fits. A waiter takes orders per table, with modifiers like extra cheese. Each line goes to the grill or the bar as a ticket with a status. Every dish uses ingredients from stock, with an alert when something runs low. Bills can be split and carry a tip, and staff roles decide who may do what.

Ask the questions that change the code. How long does a table stay busy? Ninety minutes. Can a walk-in sit at a table reserved for later? Only if their sitting ends before the booking starts. When does stock go down: when the waiter types the order, or when it is sent to the kitchen? When it is sent, which we call firing. Who can cancel a dish already sent? Only a manager, and only before a chef starts it.

Requirements
  • tables of 2, 4 and 6 seats
  • reservations in 90 minute slots
  • walk-ins, else a waitlist
  • orders per table, with modifiers
  • lines go to grill or bar
  • kitchen tickets with a status
  • stock deducted per recipe
  • alert when an item runs low
  • split bills, add a tip
  • roles decide who can do what
  • out of scope: payroll, delivery
Clarify first
  • how long is a sitting?
  • 90 minutes, fixed for now
  • walk-in on a reserved table?
  • only if they leave in time
  • when is stock taken?
  • when the line is fired
  • can a fired dish be voided?
  • manager only, before cooking
  • tax and tip?
  • tax 5%, tip on the food only

Entities

Underline the nouns. A table has seats and at most one seated party, and it carries its reservations. A reservation books a table for a party and a time slot. Staff members have a role. A menu item has a price, a recipe and allowed modifiers. A seated table has one open order made of lines, and each line, once fired, becomes a kitchen ticket. Notice that the waitlist is just a queue of parties, not a table of its own.

Class diagram

Turn them into types. A modifier, a menu item, an order line and a reservation never change after creation, so they are Java records. An order line remembers which guest ordered it, with zero meaning shared by the table, which we need later for splitting. Only three things change during service: who sits at a table, what an order contains, and the status of a kitchen ticket. Money is a long number of paise.

Types
record Modifier(code, long priceCents,
    Map<String, Integer> ingredients)
record MenuItem(id, long priceCents,
    Station station, Map recipe, Map mods)
record OrderItem(int line, MenuItem item,
    int qty, List<Modifier> mods, int guest)
record Reservation(id, party, size,
    int table, LocalDateTime start, end)
class Table { seats; seatedParty;
  List<Reservation> reservations }

Roles

Roles first, because every action checks one. Instead of if statements like, is this a waiter or a manager, each role carries a set of permissions: reserve, seat, take order, cook, void a fired dish, close a bill. Every service method starts with one line that requires a permission. A host can seat but not take orders, a chef can only cook, and a manager can do everything. A new role is one new line in the enum.

Role and Permission
enum Role {
  HOST(EnumSet.of(RESERVE, SEAT)),
  WAITER(EnumSet.of(SEAT, TAKE_ORDER,
                    CLOSE_BILL)),
  CHEF(EnumSet.of(COOK)),
  MANAGER(EnumSet.allOf(Permission.class));
}
void require(Permission p) {
  if (!role.can(p)) throw
    new SecurityException(..);
}

Reservations

A reservation books a time slot: from the start time to ninety minutes later, as a half-open range. A table is blocked for some window if any reservation of another party overlaps it. So a couple walking in at six thirty can use a two-seat table booked for eight, because they will leave by eight. But a party of six cannot take the six-seat table booked for seven thirty. Reserving picks the smallest table that fits and is not blocked.

Table.blocked()
// a sitting is [start, start + 90 min)
boolean overlaps(from, to) {
  return start.isBefore(to)
      && from.isBefore(end);
}
blocked(from, to, party):
  any reservation of another party
  that overlaps [from, to)

18:30 walk-in vs 20:00 booking: ok
18:30 walk-in vs 19:30 booking: no

Flow: walk-in

A walk-in arrives. The service tries tables from the smallest that fits, so a couple never takes a six-seat table while one for two is free. Claiming a table checks three things: nobody sits there, the party fits, and no other reservation overlaps the next ninety minutes. If every table says no, the party joins the waitlist. Here a party of six waits, because the only big table is booked at seven thirty.

walkIn(host, party, size)
host.require(SEAT);
for (Table t : tablesBySeats) {
  Optional<Order> o = claim(t, party,
                            size);
  if (o.isPresent()) return o;
}
synchronized (waitlist) {
  waitlist.addLast(new WaitingParty(..));
}
return Optional.empty();

Concurrency

Now the race the interviewer is waiting for. Two hosts at two tablets both see table two as free and both tap seat. If checking and seating were separate steps, two parties would be sent to the same table. So the check, the claim and opening the order all happen inside one lock on that table. The first host wins; the second sees it occupied and picks another table. The lock is per table, so other tables are never slowed down.

claim(table, party, size)
synchronized (t) {
  if (t.seatedParty != null
      || t.seats < size
      || t.blocked(now, now + 90m, party))
    return Optional.empty();
  t.seatedParty = party;
  Order o = new Order(..);
  openOrders.put(t.number, o);
  return Optional.of(o);
}

Menu and orders

A waiter adds lines to the table's open order. Each menu item lists the modifiers it allows, so extra cheese on a burger is fine and cheese on a lime soda is rejected at the tablet. A modifier changes two things: the price, and the ingredients the kitchen will use. The order line works out both itself: its total in paise, and the full ingredient list for its quantity. That keeps the kitchen and the bill reading the same truth.

OrderItem
long totalCents() {
  long unit = item.priceCents();
  for (Modifier m : mods)
    unit += m.priceCents();
  return unit * qty;
}
Map ingredients(): recipe x qty
  plus each modifier x qty

BURGER + CHEESE = 320 + 40 = 360
FRIES + CHEESE: not allowed

Command: firing

Firing sends the new lines to the kitchen, and each line becomes a command object: the Command pattern. Executing it takes the ingredients from stock and puts a ticket in the right station's queue, grill for burgers and fries, bar for drinks. Because the request is an object, it can wait in a queue, be logged, and be undone. Undo voids the ticket and puts the ingredients back. If stock is short, execute fails and nothing is queued.

KitchenCommand
interface KitchenCommand {
  void execute();
  boolean undo();
}
FireLine.execute():
  inventory.consume(ingredients);
  station.enqueue(ticket);
FireLine.undo():
  if QUEUED to VOIDED wins:
    inventory.restock(ingredients)

State: tickets

Each kitchen ticket has a small life. Queued can become cooking or voided. Cooking becomes ready, and ready becomes served when the waiter carries it out. Served and voided are final. Each station keeps its own first in, first out queue, so the bar never waits behind a slow steak. A chef asks the station for the next ticket; voided tickets are skipped, and the one returned has just moved to cooking.

TicketStatus.canMoveTo()
return switch (this) {
  case QUEUED -> next == COOKING
             || next == VOIDED;
  case COOKING -> next == READY;
  case READY -> next == SERVED;
  case SERVED, VOIDED -> false;
};

station.next(): poll the queue,
  skip voided, CAS QUEUED to COOKING

Concurrency: void

A guest changes their mind just as the chef reaches for the ticket. The manager voids, the chef starts, at the same instant. Both are moves out of the queued status, so the ticket status is an atomic reference and each move is a compare-and-set from queued. Exactly one wins. If the chef won, the void returns false, the ingredients stay used and the dish stays on the bill. If the void won, the stock comes back and the chef skips it.

move(from, to)
AtomicReference<TicketStatus> status

boolean move(TicketStatus from,
             TicketStatus to) {
  if (!from.canMoveTo(to)) throw ..;
  return status.compareAndSet(from, to);
}

void after cooking starts: false,
  stock stays used, dish is billed

Observer: stock

Stock is deducted all or nothing: first check every ingredient, then take them all, inside one lock, so two waiters can never take the last patty twice. When a level crosses its low-stock line, the inventory remembers it, and after releasing the lock it tells every listener: the Observer pattern. The kitchen screen, the manager's phone and the purchasing system just subscribe. The alert fires once, when the line is crossed, not on every later order.

Inventory.consume(need)
synchronized (this) {
  for each ingredient: enough?
    else throw: out of patty
  for each: stock -= need
    if before > lowAt and
       after <= lowAt: remember
}
for each remembered alert:
  listeners.forEach(l -> l.lowStock())

alert once, when the line is crossed

Strategy: split

Splitting is a strategy, because groups argue about it. Equal split divides the total, and gives the leftover paise to the first guests so the shares add up exactly. Split by item charges each guest for their own lines, divides shared lines like fries evenly, and spreads tax and tip in proportion to what each guest ate. Voided lines are never billed. Tax is five percent rounded half up, and the tip is a percent of the food, not of the tax.

Table 2, tip 10%
guest 1: burger+cheese 360, mojito 220
guest 2: burger 320 (soda voided)
shared:  fries x2 300
subtotal 1,200.00 tax 60.00
tip 120.00 total 1,380.00

ByItem: own items + half of shared
  + tax and tip in proportion
  guest 1: 839.50  guest 2: 540.50
Equal: total / n, leftover paise
  to the first guests

Flow: close the bill

Closing the bill builds it under the order lock, marks the order paid so it can never be paid twice, and frees the table. Then the freed table is offered to the waitlist: the first party that fits. The party of six is skipped because table two seats four, and the party of three is seated at once. If another host grabbed the table in between, the party goes back to the front of the line, so nobody loses their place.

Concurrency

Check every shared field. A table's party and reservations are guarded by the table lock. An order's lines by the order lock. Firing holds the order lock and then takes the inventory lock, and nothing ever takes them in the other order, so there is no deadlock. Ticket status is atomic, station queues are concurrent queues, open orders sit in a concurrent map, and alerts are sent outside any lock, so a slow listener never stalls the kitchen.

Thread safety checklist
  • table: party + reservations
  • guarded by the table lock
  • order lines: order lock
  • lock order: order, then
  • inventory; never reversed
  • ticket status: AtomicReference
  • station queue: concurrent queue
  • open orders: ConcurrentHashMap
  • waitlist: its own small lock
  • listeners: CopyOnWriteArrayList
  • records: immutable, shared freely

Extensibility

Now the stretches. A no-show releases its reservation fifteen minutes after the start. A big group needs two tables joined, which means claiming both, in table number order to avoid deadlock. Courses mean firing starters now and mains later, which the command design already supports. Happy hour prices are a pricing strategy. A dessert station is one more enum value. And items whose ingredients ran out can be hidden from the menu automatically.

Extension points
  • no-shows: release a reservation
  • 15 minutes after its start
  • joining tables for big groups
  • courses: fire starters now,
  • mains later, per line
  • happy hour: a PricingStrategy
  • ready alerts: Observer on tickets
  • priority waitlist: VIP first
  • more stations: add to the enum
  • menu 86: hide items with no stock

Testing

The full code is below the player. The demo books two reservations and turns away a party of six because the big table is booked. Eight hosts race to seat table two and exactly one wins. A waiter is refused a void, a manager voids a drink and the lime goes back to stock, and a void after cooking fails. The patty alert fires once, a later order is rejected, and two split bills add up to the paisa.

Run it
walkin-a (6): waitlist, T4 booked
race for T2: 1 seated, 7 refused
waiter voids: not allowed
manager voids line 4: true
void after cooking: false
[alert] low stock: patty, 2 left
3x BURGER: out of patty
T2 split by item: 839.50, 540.50
[host stand] walkin-d seated at T2
T3 split 4 ways: shares add up

Follow-ups

Expect follow-ups. Why a lock per table and not one for the whole host stand? Hosts only clash when they want the same table. Why take stock on fire rather than on order? Because orders change until they are sent. Is first fit fair to the party of six? Not always, so cap how many times a party can be skipped. And which patterns did you use? Command for tickets, a state machine, Observer for stock and Strategy for splitting.

Follow-ups to expect
  • why lock per table?
  • hosts only clash on one table
  • why take stock on fire?
  • typed orders can still change
  • fairness of first fit?
  • cap how often one is skipped
  • kitchen screen offline?
  • persist tickets, replay queue
  • which patterns? Command, State,
  • Observer, Strategy

Say it like this

Here is the short version to say out loud. Each table owns its seated party and its reservations, guarded by a lock, so two hosts never seat one table. Walk-ins take the smallest free table or join the waitlist. A fired line is a command that takes stock and queues a ticket at its station, and tickets follow a state machine. Low stock is published to observers, and bill splits are strategies.

In the interview
  • "Tables own their party and
  • reservations, under a lock.
  • Walk-ins take the smallest
  • free table or wait. A fired
  • line is a command that takes
  • stock and queues a ticket;
  • tickets are a state machine.
  • Low stock is observed. Splits
  • are strategies."

Interview questions

How do you stop two hosts from seating two parties at the same table?

Make the check and the claim one atomic step. Here each table is a lock: under it we check that nobody is seated, the party fits and no reservation overlaps, then set the party and open the order. The second host sees the table occupied and picks another.

How do reservations and walk-ins share the same tables?

Each reservation covers a half-open slot from its start to the end of a sitting. A walk-in may take a table only if no other party has a reservation overlapping the next sitting, so a quick table before a later booking is allowed and a clash is not.

Where does the Command pattern fit in a restaurant system?

Each fired order line becomes a command object. Execute takes the ingredients and queues a ticket at the right station; undo voids the ticket and restocks. Because the request is an object it can be queued, logged, retried and undone without the order knowing how the kitchen works.

How do you route items to the grill and the bar?

Each menu item names its station, and the service keeps one ticket queue per station in an EnumMap. Firing puts each line on its own station queue, so drinks are never stuck behind slow grill orders, and a new station is one more enum value.

What happens if a manager voids a dish just as the chef starts it?

Both are transitions out of QUEUED, done with compareAndSet on the ticket status, so exactly one wins. If the chef won, the void fails and the dish is billed; if the void won, the ingredients go back to stock and the chef skips that ticket.

How do you deduct inventory safely and raise low-stock alerts?

Check all ingredients, then deduct them all, inside one inventory lock, so stock never goes negative and an order never takes half its ingredients. Record any level that crossed its threshold, and notify the listeners after releasing the lock so a slow listener cannot block the kitchen.

How would you split a bill by item fairly?

Charge each guest their own lines, divide shared lines evenly, and spread tax and tip in proportion to each guest's share. Compute in paise with integer maths and give any rounding leftover to one guest, so the shares always add up to the exact total.

How do you model staff roles and permissions?

A Role enum where each role holds an EnumSet of permissions, and every service method starts by requiring one permission. Adding a role or moving a permission is a one-line change, with no scattered if statements on job titles.

How is the waitlist served when a table frees up?

When a bill closes, the table is freed and offered to the first waiting party that fits its seats. If someone else claimed the table first, the party goes back to the front. To be fair to big groups, cap how often a party may be skipped.