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.
- 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
- 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.
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.
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.
// 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.
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.
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.
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.
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.
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.
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.
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.
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.
- 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.
- 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.
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.
- 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.
- "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."