Restaurant Booking System

Difficulty: Intermediate-Advanced Patterns: Strategy, State, Observer, Repository Asked at: Zomato, Swiggy, OpenTable, Amazon, Google

💡 Repository has no separate page here, so in one line: a repository is one interface per entity (TableRepository, BookingRepository) that hides where the data actually lives, so the booking logic never mentions a database.


Functional Requirements

  1. Table management — register tables with capacity and type (Indoor, Outdoor, VIP)
  2. Time-slot reservations — book tables with conflict detection for overlapping slots
  3. Waitlist management — FIFO waitlist per time slot when no tables available
    💡 FIFO = first in, first out: the queue hands people back in the exact order they joined, which is what makes the waitlist feel fair.
  4. Auto-promotion — cancellation triggers automatic waitlist-to-booking promotion
  5. Booking lifecycle — state machine: CONFIRMED → SEATED → COMPLETED (or CANCELLED)
    💡 A state machine is a fixed set of statuses plus the only legal moves between them — so “complete a booking nobody ever sat down at” is rejected by construction, not by a comment. Learn more →

Non-Functional Requirements

  1. Thread-safety — concurrent booking attempts cannot double-book a table
    💡 Thread-safe = correct even when several requests run the code at the same instant. Two diners clicking “book” on the last table in the same millisecond is the exact failure this guards against. Learn more →
  2. Conflict detection — overlap-based, not just exact time match
    💡 Overlap means any shared minute: a 7:00–9:00 booking conflicts with 8:00–10:00 even though neither start time matches, so the check is “ranges intersect”, not “times are equal”.
  3. Extensibility — swappable table assignment strategies at runtime
  4. State integrity — only valid state transitions allowed

Core Entities

Entity Description
TableType Enum — INDOOR, OUTDOOR, VIP
BookingStatus Enum — CONFIRMED, SEATED, COMPLETED, CANCELLED
TimeSlot Date + start/end time with overlap detection
Table Immutable — id, capacity, type
Booking Customer reservation with state machine transitions
WaitlistEntry FIFO queue entry — customer, party size, time slot, timestamp
TableAssignmentStrategy Interface — pick the best table from available list
FirstFitStrategy Assigns the first available table that fits the party
BestFitStrategy Assigns the smallest available table that fits (minimizes waste)
BookingService Orchestrates booking, cancellation, waitlist promotion with lock

💡 An enum (enumeration) is a type with a fixed set of named values. BookingStatus as an enum means a typo like "CONFIRMD" can’t exist — the only statuses are the four the compiler knows about.

💡 Immutable means the object never changes after construction. Table is immutable because a table’s id, capacity and type don’t move; only bookings move, so there’s nothing to lock on a Table.


Class Diagram

classDiagram
    class Restaurant {
        -String id
        -String name
        -List tables
        +addTable(int capacity, TableType type) Table
        +getTables() List
    }

    class Table {
        -String id
        -int capacity
        -TableType tableType
        +getId() String
        +getCapacity() int
        +getTableType() TableType
    }

    class TableType {
        <<enumeration>>
        INDOOR
        OUTDOOR
        VIP
    }

    class TimeSlot {
        -LocalDate date
        -LocalTime startTime
        -LocalTime endTime
        +overlapsWith(TimeSlot other) boolean
    }

    class Booking {
        -String id
        -String customerName
        -int partySize
        -Table table
        -TimeSlot timeSlot
        -BookingStatus status
        +confirm()
        +seat()
        +complete()
        +cancel()
    }

    class BookingStatus {
        <<enumeration>>
        CONFIRMED
        SEATED
        COMPLETED
        CANCELLED
    }

    class WaitlistEntry {
        -String customerName
        -int partySize
        -TimeSlot timeSlot
        -LocalDateTime addedAt
    }

    class TableAssignmentStrategy {
        <<interface>>
        +assignTable(List availableTables, int partySize) Table
    }

    class FirstFitStrategy {
        +assignTable(List availableTables, int partySize) Table
    }

    class BestFitStrategy {
        +assignTable(List availableTables, int partySize) Table
    }

    class BookingService {
        -TableRepository tableRepo
        -BookingRepository bookingRepo
        -WaitlistRepository waitlistRepo
        -TableAssignmentStrategy strategy
        -ReentrantLock lock
        +bookTable(String customer, int partySize, TimeSlot slot) BookingResult
        +cancelBooking(String bookingId)
        +getAvailableTables(TimeSlot slot, int partySize) List
        +seatGuests(String bookingId)
        +completeBooking(String bookingId)
        +getWaitlist(TimeSlot slot) List
    }

    class TableRepository {
        <<interface>>
        +save(Table)
        +findById(String) Table
        +findAll() List
    }

    class BookingRepository {
        <<interface>>
        +save(Booking)
        +findById(String) Booking
        +findByTableAndSlot(String tableId, TimeSlot slot) List
    }

    class WaitlistRepository {
        <<interface>>
        +add(WaitlistEntry)
        +getBySlot(TimeSlot) List
        +removeFirst(TimeSlot) WaitlistEntry
    }

    BookingService --> TableRepository
    BookingService --> BookingRepository
    BookingService --> WaitlistRepository
    BookingService --> TableAssignmentStrategy
    TableAssignmentStrategy <|.. FirstFitStrategy
    TableAssignmentStrategy <|.. BestFitStrategy
    Restaurant --> Table
    Table --> TableType
    Booking --> Table
    Booking --> TimeSlot
    Booking --> BookingStatus
    BookingRepository --> Booking
    WaitlistRepository --> WaitlistEntry
    WaitlistEntry --> TimeSlot

💡 Reading the arrows: <|.. (dashed, hollow head) means “implements this interface”, and --> means “holds a reference to”. So BookingService --> TableRepository is a field it was handed, while FirstFitStrategy is one of two classes fulfilling the strategy contract. Learn more →

Key classes:

  • BookingService — the only place that coordinates. It holds the three repositories, the current assignment strategy and the lock, and it is where “find candidates → pick one → write the booking” happens as one protected sequence.
  • TimeSlot — a date plus a start and end time. It exists so that overlapsWith() lives in one method; every conflict question in the system is answered by that single comparison.
  • Booking — one reservation, and the owner of its own lifecycle. confirm()/seat()/complete()/cancel() are the only ways status changes, and each refuses an illegal jump.
  • Table — id, capacity, type. Deliberately dumb: it knows nothing about who booked it, so availability is always derived from bookings rather than from a mutable flag on the table.
  • TableAssignmentStrategy — the contract for “given these free tables and this party size, pick one”. FirstFitStrategy takes the first that fits; BestFitStrategy takes the smallest that fits so big tables stay free for big parties.
  • WaitlistEntry — a customer waiting for a specific slot, stamped with when they joined. The timestamp is what makes FIFO promotion possible.
  • TableRepository / BookingRepository / WaitlistRepository — storage contracts. In-memory maps in the demo, a database in production; BookingService can’t tell the difference.

Design Patterns

Pattern Where Why
Strategy TableAssignmentStrategy with FirstFit/BestFit Swap table selection algorithm at runtime without changing BookingService
State Booking lifecycle transitions Strict state machine — CONFIRMED → SEATED → COMPLETED or CANCELLED. Invalid transitions throw exceptions
Observer Waitlist auto-promotion on cancellation Cancellation implicitly “notifies” the waitlist, promoting the next eligible party
Repository Table/Booking/Waitlist repositories Abstract storage behind interfaces — swap InMemory for database-backed without touching business logic

💡 Strategy pattern = each interchangeable algorithm sits behind a common interface so the caller can swap it at runtime. Table selection is the algorithm here. Learn more →