Restaurant Table Inventory and Booking Platform

Hard · System Design · Software Engineer · Technical Screen

Prompt

Architect an online seating and reservation platform for restaurants. Guests look up open dining times by group size, calendar date, and preferred hour, claim a reservation, and can later reschedule or cancel it. Venue staff configure their floor layout and operating hours, monitor the daily reservation sheet, and seat walk-in parties or phone-in bookings at those same physical tables.

Your design must serve availability searches with low latency while enforcing a strict correctness rule: two parties must never be assigned to the same table during overlapping dining windows, even when multiple guests submit concurrent requests for the final eligible table at the exact same instant.

Operational assumptions & scope questions to clarify:

  • Every booking covers a specified group count starting at a chosen timestamp and occupies its assigned table(s) for a venue-configured dining duration.
  • Walk-in guests and staff-entered reservations share the exact same physical table inventory as online diners.
  • State your assumptions around single-venue vs. multi-restaurant platform scale, backend-assigned tables vs. guest-picked seats, duration variations by party size or meal period, joining adjacent tables for larger parties, deposit and cancellation-fee rules, and whether controlled overbooking is permitted.

Scope & Expectations

  • Inventory & Time-Window Representation: Modeling physical table capacities, dining durations, cleanup buffers, and approved multi-table combinations so non-overlapping occupancy is well-defined.
  • Concurrency Control & Mutual Exclusion: Guaranteeing zero double-booked tables across simultaneous online checkouts, temporary holds, reservation edits, and host-stand walk-ins.
  • Read/Write Path Separation: Scaling high-volume availability browsing independently from strongly consistent reservation transactions.
  • Partitioning, Hot Drops & Resilience: Handling viral reservation releases, floor-plan modifications, idempotent payment/deposit flows, restaurant-based sharding, and database failovers.

Step-by-step walkthrough

  1. Clarify requirements, assumptions, and the core invariant

    Designing a restaurant reservation platform revolves around three central engineering questions: 1. How do we represent physical seating capacity over time? (So zero overlapping assignments becomes a hard rule enforced by storage, not wishful thinking.) 2. Which layer arbitrates when concurrent checkouts race for the final eligible table? 3. How do we decouple high-QPS slot browsing from strongly consistent reservation writes?

    Functional requirements - Diners search availability for a single restaurant (or across a whole city) by party size, date, and target time; place a short hold (a temporary 5-minute reservation during checkout); confirm, modify, or cancel bookings; and receive asynchronous SMS/email confirmations. - Restaurant staff configure their floor plan (table capacities and allowed multi-table combinations), opening hours, seating durations, and deposit rules; view the live day sheet; enter phone bookings; seat walk-in guests; move parties between tables; and mark bookings seated, finished, or no-show.

    Non-functional requirements - Zero double-booking invariant: Two active bookings—whether online, phone, or walk-in—must never occupy the same physical table during overlapping time windows. - Latency: Availability search p99 (slowest 1% of requests) < 200 ms; hold/booking p99 < 500 ms. - Freshness split: Search results may lag reality by 1–2 seconds; the booking decision itself must be strongly consistent (always reflecting the latest committed state). - Durability & isolation: Zero lost confirmed bookings on hardware failure, and one viral restaurant drop must not degrade the other 49,999 restaurants.

    Assumptions from clarifying questions - Multi-tenant platform: 50,000 restaurants, 2M bookings/day, 50M single-restaurant page views/day, and 10M city-wide searches/day. - System assigns tables, not diners: Diners pick a party size (4 guests) and start time (19:00); the backend assigns a concrete table or staff-approved table combination (T5 + T6) at booking time to prove the party physically fits, while hiding table IDs from diners so staff can reshuffle equivalent tables later. - Duration stored at booking time: Seating length depends on party size and day/time (e.g., 2 guests = 90 min, 3–4 = 105 min, 5+ = 120 min) plus a 15-minute cleaning/turnover buffer. We compute end_at when creating the booking so a future rule edit never silently shifts existing reservations. - Booking window & policies: Up to 30 days ahead by default; optional deposits (e.g., $25/person for parties of 6+); overbooking is off by default (with an opt-in table-less buffer explained later).

  2. Back-of-the-envelope numbers

    Scale & Inventory
      50,000 restaurants x ~30 tables each              = 1.5 million tables
    
    Write traffic (bookings, holds, edits, walk-ins)
      Confirmed bookings: 2,000,000 / 86,400 s/day      = ~23 bookings/s avg (~120/s at 5x dinner peak)
      Holds (1.5 holds per confirmed booking): 3M/day   = ~35 holds/s avg    (~175/s at peak)
      Modifications + cancellations (~30% of bookings)  = ~7/s avg           (~35/s at peak)
    
    Read traffic (availability searches — ~100x higher than writes!)
      Restaurant page: 50M/day                          = ~580/s avg  (~3,000/s peak)
      City search: 10M queries/day x 20 restaurants/page = 200M restaurant-day lookups/day
        (~116 city queries/s avg, ~580 MGET calls/s peak = ~12,000 Redis key reads/s peak)
    
    Database storage
      Per booking: ~600 B booking row + ~300 B table assignments + ~1 KB change event
      Daily growth (with B-tree & GiST indexes)         = ~5 GB/day (~1.8 TB/year; archive after 1 year)
      Active future window (<= 30 days ahead):
        Average ~6-day lead time -> ~12M active (~12 GB); worst-case 30 days -> 60M (~60 GB total)
    
    Availability cache in Redis
      50,000 restaurants x 31 bookable days             = 1.55 million keys
      A 24-hour day has 24 x 4 = 96 quarter-hours (100 on a 25-hour daylight-saving fall-back day),
      so each of 12 party sizes uses a 128-bit (16-byte) bitmask:
        12 party sizes x 16 B = 192 B + ~108 B key/metadata = ~300 B per restaurant-day
        1.55M keys x 300 B                              = ~465 MB total across Redis!
    
    Hot-spot stress case (1 popular restaurant releasing 30 days of tables at 10:00 AM)
      Supply: 20 tables x 2.5 turns/night x 30 days     = 1,500 bookable seatings
      Demand: 20,000 diners refreshing every 2 seconds  = 10,000 reads/s + thousands of concurrent holds
    

    What these numbers tell us: Platform-wide write throughput (~330 total transactions/s at dinner peak) and active data (< 60 GB) are tiny—so we do not need an exotic eventually consistent store for bookings; sharded PostgreSQL handles writes with ease and gives us rock-solid transactions. Conversely, reads are ~100× larger and extremely spiky (10,000 reads/s on a single famous restaurant), so search must be served from a compact ~465 MB precomputed cache without touching PostgreSQL.

  3. Model what a reservation consumes

    Before sketching microservices, pin down the exact resource each reservation claims. Compare the three candidate models:

    Why "counting free seats" fails:
      Floor plan:  [ Table A: 2 seats ]   [ Table B: 2 seats ]   [ Table C: 4 seats ]  (Total = 8 seats)
      19:00 state: Party #1 (4 guests) books Table C -> 4 seats remain free (Tables A and B).
      Bug:         Party #2 (4 guests) asks for 19:00. A seat counter sees "4 seats left >= 4" and says YES!
                   When Party #2 arrives, Tables A and B are on opposite sides of the room and cannot combine.
    
    1. Seat count per time slot ("40 seats at 19:00"): Fast to decrement, completely broken in practice. It ignores table geometry (two separate 2-tops do not make a 4-top) and ignores multi-slot duration.
    2. Discrete (table_id, 15_min_bucket) grid rows: A 105-minute seating inserts 7 bucket rows with UNIQUE (table_id, bucket_start). Works on any database with unique indexes, but multiplies row writes 6–8× and forces every custom duration onto fixed 15-minute boundaries.
    3. A concrete table reserved over a half-open time interval [start_at, end_at): One row per assigned table per booking, exact to the minute.

    Our choice: Model 3—half-open intervals [start_at, end_at) per physical table. A half-open interval [a, b) includes its start timestamp a and excludes its end timestamp b. Look at why half-open intervals make back-to-back seatings effortless:

    Table T12 timeline:
      18:00                     19:30                     21:00
        |==== Booking 1 (2p) ====>|==== Booking 2 (2p) ====>|
             [18:00, 19:30)            [19:30, 21:00)
                   ^
             19:30 is excluded from Booking 1 and included in Booking 2 -> ZERO overlap!
    

    With end_at = start_at + seating_duration + turnover_minutes, two bookings on the same table overlap if and only if start_1 < end_2 AND start_2 < end_1.

  4. Design the diner and staff APIs

    Before reading the endpoints, note three reliability mechanisms built into the HTTP contract: - Two-step Hold -> Confirm: Placing a 5-minute hold claims a concrete table immediately so the diner isn't sniped while typing their phone number or credit card. (Restaurants without deposits can invoke hold-and-confirm in one step.) - Idempotency key (Idempotency-Key header): A client-generated UUID sent with every write request so that if a mobile connection drops and retries, the server returns the original booking/charge result instead of creating a duplicate. - Optimistic concurrency (If-Match version header): Each edit passes the booking's last seen version integer; if staff and the diner edit the same booking simultaneously, the second writer gets 412 Precondition Failed instead of silently overwriting the first.

    Diner Endpoints
      GET    /v1/restaurants/{rid}/availability?date=2026-12-12&party=4&time=19:00
             -> 200 {"slots": [{"time": "18:45"}, {"time": "19:30"}], "deposit_cents": 0, "as_of": "..."}
    
      GET    /v1/search/availability?city=nyc&date=2026-12-12&party=4&time=19:00&cuisine=italian
             -> 200 {"restaurants": [{"restaurant_id": "r-81", "slots": [...]}], "next_cursor": "..."}
    
      POST   /v1/restaurants/{rid}/holds                (Header: Idempotency-Key: <uuid>)
             Body: {"party_size": 4, "start_at": "2026-12-12T19:00:00-05:00"}
             -> 201 {"booking_id": "b-91f", "status": "HELD", "expires_at": "...+5m"}
             -> 409 SLOT_TAKEN {"alternatives": [{"time": "18:45"}, {"time": "19:30"}]}
             -> 429 TOO_MANY_HOLDS (max 1 active hold per restaurant, 3 across platform per diner)
    
      POST   /v1/bookings/{id}/confirm                  (Header: Idempotency-Key: <uuid>)
             Body: {"guest": {"name": "...", "phone": "..."}, "payment_method_id": "pm_123"}
             -> 200 {"booking_id": "b-91f", "status": "CONFIRMED", "code": "K7Q2M"}
             -> 402 PAYMENT_DECLINED (hold stays alive until expires_at so diner can retry card)
             -> 410 HOLD_EXPIRED
    
      PATCH  /v1/bookings/{id}                          (Header: If-Match: 3)
      DELETE /v1/bookings/{id}                          -> 200 {"status": "CANCELLED", "fee_cents": 0}
    
    Staff (Host Tablet) Endpoints
      GET    /v1/restaurants/{rid}/day-sheet?date=2026-12-12   (strong read from primary DB)
      POST   /v1/restaurants/{rid}/walk-ins             Body: {"party_size": 2, "table_ids": ["t-12"]}
      POST   /v1/bookings/{id}/move                     Body: {"table_ids": ["t-14"]}
      POST   /v1/bookings/{id}/seat | /finish | /no-show
      PUT    /v1/restaurants/{rid}/floor-plan           (effective-dated table & combo updates)
    

    Notice that diner responses never expose table_id (preserving staff flexibility to move parties), and 409 SLOT_TAKEN returns live alternative slots computed right inside the database fallback path so a diner who loses a race can pick 18:45 in one tap.

  5. Data model and database-enforced no-overlap

    All rows belonging to a single restaurant live on the same PostgreSQL shard. Timestamps use timestamptz (UTC instants) paired with the restaurant's IANA timezone ('America/New_York') so daylight-saving transitions never shift a 19:00 local dinner to 18:00 or 20:00.

    Three PostgreSQL features make this schema rock-solid: - GiST index (Generalized Search Tree): an index structure capable of indexing 2D shapes and time ranges (tstzrange) to test range overlap (&&) in logarithmic time. - Exclusion constraint (EXCLUDE USING gist): a declarative table rule stating that no two active rows may simultaneously have equal table_id (=) and overlapping during ranges (&&). - Transactional outbox (outbox table): an event queue table written inside the exact same ACID transaction as the booking, guaranteeing we never commit a booking while dropping its cache-invalidation or SMS event.

    CREATE EXTENSION IF NOT EXISTS btree_gist;
    
    CREATE TABLE restaurant (
      id                  bigint PRIMARY KEY,
      timezone            text NOT NULL,                  -- e.g. 'America/New_York'
      turnover_minutes    smallint NOT NULL DEFAULT 15,
      booking_window_days smallint NOT NULL DEFAULT 30,
      hold_seconds        int NOT NULL DEFAULT 300,
      deposit_policy      jsonb
    );
    
    CREATE TABLE dining_table (
      id              bigint PRIMARY KEY,
      restaurant_id   bigint NOT NULL REFERENCES restaurant(id),
      label           text NOT NULL,                      -- 'T12'
      min_party       smallint NOT NULL,
      max_party       smallint NOT NULL,
      online_bookable boolean NOT NULL DEFAULT true,      -- false = walk-in / VIP bar tables
      active_from     date NOT NULL,                      -- inclusive local start date
      active_until    date                                -- exclusive local end date when removed
    );
    
    CREATE TABLE table_combo (                            -- physically adjacent tables staff allow combining
      id            bigint PRIMARY KEY,
      restaurant_id bigint NOT NULL REFERENCES restaurant(id),
      min_party     smallint NOT NULL,
      max_party     smallint NOT NULL
    );
    
    CREATE TABLE table_combo_member (
      combo_id bigint NOT NULL REFERENCES table_combo(id),
      table_id bigint NOT NULL REFERENCES dining_table(id),
      PRIMARY KEY (combo_id, table_id)
    );
    
    CREATE TABLE booking (
      id              bigint PRIMARY KEY,
      restaurant_id   bigint NOT NULL REFERENCES restaurant(id),
      diner_id        bigint,                             -- NULL for anonymous walk-ins
      party_size      smallint NOT NULL,
      start_at        timestamptz NOT NULL,
      end_at          timestamptz NOT NULL,               -- fixed at creation: start + duration + turnover
      status          text NOT NULL,                      -- HELD, CONFIRMED, SEATED, FINISHED, CANCELLED, EXPIRED
      source          text NOT NULL,                      -- ONLINE, PHONE, WALK_IN
      hold_expires_at timestamptz,
      deposit_status  text NOT NULL DEFAULT 'NONE',       -- NONE, PENDING, AUTHORIZED, CAPTURED, VOIDED
      version         int NOT NULL DEFAULT 0
    );
    CREATE INDEX booking_by_day ON booking (restaurant_id, start_at);
    
    CREATE TABLE table_assignment (
      id              bigserial PRIMARY KEY,              -- surrogate key so a moved booking can revisit a table
      booking_id      bigint NOT NULL REFERENCES booking(id),
      restaurant_id   bigint NOT NULL,
      table_id        bigint NOT NULL REFERENCES dining_table(id),
      during          tstzrange NOT NULL,                 -- half-open '[start_at, end_at)'
      hold_expires_at timestamptz,                        -- NULL once confirmed
      active          boolean NOT NULL DEFAULT true,      -- set false on cancel, expiry, or table move
      CONSTRAINT no_double_booking
        EXCLUDE USING gist (table_id WITH =, during WITH &&) WHERE (active)
    );
    CREATE INDEX assignment_by_booking ON table_assignment (booking_id);
    
    CREATE TABLE idempotency_key (
      scope        text PRIMARY KEY,                      -- diner_id || ':' || client_uuid
      request_hash bytea NOT NULL,
      response     jsonb,
      created_at   timestamptz NOT NULL DEFAULT now()
    );
    
    CREATE TABLE outbox (
      id            bigserial PRIMARY KEY,
      restaurant_id bigint NOT NULL,
      local_date    date NOT NULL,
      event         jsonb NOT NULL
    );
    

    Notice two subtle schema choices: 1. Multi-table combinations need zero special constraint logic: Booking combo T5 + T6 simply inserts two rows into table_assignment (one for T5, one for T6) in the same transaction, so no_double_booking protects each individual table automatically. 2. Soft deactivation (active = false) instead of DELETE: Keeping historical assignment rows lets us audit staff table moves, and using a bigserial id primary key (rather than (booking_id, table_id)) lets a diner shift a reservation from 19:00 to 19:15 on the same table T12 cleanly.

  6. High-level architecture: separating search from booking

    Because diners browse roughly 100 times for every booking they complete, we separate the read path (fast, cached, tolerates 1–2 seconds of staleness) from the write path (authoritative PostgreSQL primary, zero staleness):

       Diner Mobile / Web                                        Restaurant Host Tablet
               |                                                            |
       CDN (1-2 s edge cache on viral restaurants)                          |
               |                                                            |
       +----------------------------------------------------+               |
       | API Gateway: auth, per-user rate limits,           |               |
       | virtual waiting-room tokens for hot drops          |               |
       +----------------------------------------------------+               |
               |                              |                             |
         search|                        holds &|bookings                    |live ops
               v                              v                             v
      +------------------+          +------------------+          +------------------+
      | Availability Svc |          | Booking Service  |<---------| Staff Service    |
      | (stateless)      |          | (stateless)      |          | (walk-ins, moves)|
      +------------------+          +------------------+          +------------------+
         |            |                |            |                      |
         v            v                |            v                      |
     +-------+  +------------+         |     +--------------+              |
     | Redis |  | Geo/Filter |         |     | Payment API  |              |
     | masks |  | Search Idx |         |     | (Stripe etc.)|              |
     +-------+  +------------+         v     +--------------+              v
         ^                  +---------------------------------------------------+
         |                  | PostgreSQL Shards (partitioned by restaurant_id)  |
         |                  | Primary + Sync Standby + Async Read Replicas      |
         |                  +---------------------------------------------------+
         |                                    | Outbox Relay
         |                                    v
         |                         +----------------------+---> SMS / Email Notifications
         +--- Availability --------| Kafka (partitioned   |---> Host WebSocket Push Gateway
              Worker (recomputes   | by restaurant_id)    |---> Diner "My Bookings" Index
              128-bit day masks)   +----------------------+
                                                                Hold Sweeper (every 15 s) -> Primary DB
    
    • Search path: Single-restaurant searches fetch one 300-byte Redis entry (avail:{rid}:{date}). City searches query the geo/cuisine search index for the top 20 matching restaurant_ids, then issue a single batched MGET of 20 keys from Redis. On a cold cache miss, the service computes the mask from a PostgreSQL read replica and writes to Redis with SET NX ("set only if key does not exist") so a slightly lagging replica never overwrites a fresher mask written by the event worker.
    • Booking path: Never touches Redis! It reads and locks candidate tables directly on the restaurant's PostgreSQL shard primary, commits the booking + assignments + outbox event atomically, and lets the asynchronous Kafka pipeline refresh Redis within hundreds of milliseconds.
  7. Deep dive 1: Preventing double-booking under simultaneous clicks

    Suppose Table T8 is the very last 4-top open at 19:30, and Maya and Noah both tap "Book" at 19:30:00.050. Let's compare why naive concurrency approaches fail before tracing our solution: - Application check-then-insert (SELECT free tables, then INSERT): Both Maya and Noah run SELECT at .050, both see T8 free, and without a constraint both insert—double-booked! - External Redis distributed lock (SET lock:T8 NX EX 5): If Maya's JVM or network pauses for 6 seconds, her Redis lock expires, Noah acquires the lock and books T8, and Maya's delayed SQL statement wakes up and also writes—plus staff tools writing PostgreSQL directly might forget the Redis lock. - Locking the entire restaurant row: Correct, but forces a party of 2 booking 17:30 to wait in a single-file line behind 500 people fighting over 20:00 on Valentine's Day.

    The authoritative solution: per-table row locks (SELECT ... FOR UPDATE) backed by the GiST exclusion constraint. Why use both FOR UPDATE on dining_table and the exclusion constraint on table_assignment? Without FOR UPDATE, two simultaneous inserts into table_assignment wait on each other inside PostgreSQL's GiST index check until deadlock_timeout (1,000 ms default!) before aborting one. Locking the dining_table row(s) in ascending id order turns that 1-second deadlock stall into an orderly 2 ms queue!

    Millisecond race on Table T8 (last 4-top at 19:30):
    
      Maya's Tx                                      Noah's Tx
      ---------                                      ---------
      1. SELECT ... FROM dining_table
         WHERE id IN (8) FOR UPDATE; (acquires lock)
                                                     1. SELECT ... FROM dining_table
                                                        WHERE id IN (8) FOR UPDATE; (waits ~2 ms)
      2. Deactivate any expired holds on T8
      3. Overlap check on T8 -> 0 rows!
      4. INSERT booking + table_assignment + outbox
      5. COMMIT; (releases lock on T8)
                                                     2. Wakes up! Deactivates expired holds on T8
                                                     3. Overlap check on T8 -> sees Maya's row!
                                                     4. ROLLBACK; tries next candidate table -> none left
                                                     5. Returns 409 SLOT_TAKEN + [17:45, 21:15] options
    

    Here is the exact SQL transaction for claiming one candidate option ($table_ids is [8] for a single table or [5, 6] for a combo):

    BEGIN;  -- Standard READ COMMITTED isolation is sufficient because FOR UPDATE serializes per table
    
    -- 1. Lock candidate tables in ascending ID order (prevents deadlocks across overlapping combos like T5+T6 vs T6+T7)
    --    and verify none of the tables was removed from the floor plan on or before $local_date.
    SELECT id FROM dining_table
    WHERE id = ANY($table_ids)
      AND active_from <= $local_date
      AND (active_until IS NULL OR $local_date < active_until)
    ORDER BY id
    FOR UPDATE;
    -- (If returned row count < length($table_ids), a table is inactive -> ROLLBACK and try next candidate.)
    
    -- 2. Lazily release any hold on these tables whose expiration timestamp has already passed.
    UPDATE table_assignment
    SET active = false
    WHERE table_id = ANY($table_ids)
      AND active = true
      AND hold_expires_at < now()
      AND during && tstzrange($start_at, $end_at, '[)');
    
    -- 3. Check whether any active confirmed booking or unexpired hold still overlaps [start_at, end_at).
    SELECT 1 FROM table_assignment
    WHERE table_id = ANY($table_ids)
      AND active = true
      AND during && tstzrange($start_at, $end_at, '[)')
    LIMIT 1;
    -- (If 1 row returned -> option is taken! ROLLBACK and try next candidate.)
    
    -- 4. Claim the table(s), record outbox event, and persist idempotency response atomically.
    INSERT INTO booking (id, restaurant_id, diner_id, party_size, start_at, end_at, status, source, hold_expires_at)
    VALUES ($booking_id, $rid, $diner_id, $party, $start_at, $end_at, 'HELD', 'ONLINE', now() + interval '5 minutes');
    
    INSERT INTO table_assignment (booking_id, restaurant_id, table_id, during, hold_expires_at)
    SELECT $booking_id, $rid, t_id, tstzrange($start_at, $end_at, '[)'), now() + interval '5 minutes'
    FROM unnest($table_ids) AS t_id;
    
    INSERT INTO outbox (restaurant_id, local_date, event) VALUES ($rid, $local_date, $event_json);
    INSERT INTO idempotency_key (scope, request_hash, response) VALUES ($scope, $hash, $response_json);
    COMMIT;
    

    In the Booking Service, we rank candidate options in best-fit order—single tables before multi-table combinations, smallest fitting capacity first (never put 2 guests at a 6-top if a 2-top is free), and tightest gap next to existing bookings (minimizing wasted 30-minute orphan gaps):

    def place_hold(db, restaurant_id, party_size, start_at, end_at):
        # Fetch today's tables & active assignments from the shard primary and sort best-fit first:
        # 1) single tables before combos, 2) smallest max_party that fits, 3) smallest idle gap created
        candidates = rank_candidate_options(db, restaurant_id, party_size, start_at, end_at)
    
        for option in candidates:
            # Runs the short SQL transaction above; returns None if another diner just took this option
            booking_id = try_claim_option(db, restaurant_id, option.table_ids, party_size, start_at, end_at)
            if booking_id is not None:
                return booking_id
    
        # Every candidate was taken -> caller returns HTTP 409 with nearby open times
        return None
    

    Golden rule for transaction speed: Never call Stripe, Twilio, or any external network API inside BEGIN ... COMMIT. Keeping the transaction strictly local to one PostgreSQL shard means locks are held for 1–3 ms, allowing hundreds of concurrent holds per second on a single restaurant.

  8. Deep dive 2: Precomputing fast availability in Redis

    Why not patch individual bits in Redis when a booking happens? Because one booking on T5 can simultaneously block single-table party sizes 3–4 and combo T5+T6 for party sizes 6–8 across seven overlapping 15-minute start slots! Instead, recomputing the entire restaurant-day from scratch is both simpler and tiny: - Service hours have ~40–60 quarter-hour start slots (11:00 to 22:00). - Party sizes 1..12 = 12 sizes. - ~30 single tables + ~10 combos = 40 options. - Checking 50 slots × 12 sizes × 40 options against 2–3 sorted bookings per table is < 50,000 integer comparisons—taking under 1 millisecond in Go, Rust, or Java!

    def is_interval_free(booked_intervals, slot_start, slot_end):
        # Half-open intervals [a, b) and [c, d) overlap if and only if a < d and c < b.
        # Back-to-back seatings like [18:00, 19:30) and [19:30, 21:00) return True (free!).
        for taken_start, taken_end in booked_intervals:
            if taken_start < slot_end and slot_start < taken_end:
                return False
        return True
    
    
    def has_any_open_option(tables, combos, busy_by_table, party_size, slot_start, slot_end):
        # 1. Check single online-bookable tables first
        for table in tables:
            if table.min_party <= party_size <= table.max_party:
                if is_interval_free(busy_by_table[table.id], slot_start, slot_end):
                    return True
    
        # 2. Fall back to staff-approved multi-table combinations
        for combo in combos:
            if combo.min_party <= party_size <= combo.max_party:
                all_members_free = True
                for member_table_id in combo.table_ids:
                    if not is_interval_free(busy_by_table[member_table_id], slot_start, slot_end):
                        all_members_free = False
                        break
                if all_members_free:
                    return True
    
        return False
    

    Keeping the Redis cache fresh without race conditions: 1. Every hold, confirm, move, walk-in, or cancel writes an outbox row for (restaurant_id, local_date). 2. The Outbox Relay publishes to Kafka partitioned by restaurant_id, so a single Availability Worker processes each restaurant's events in order. 3. During spikes, the worker coalesces (batches) events for the same (restaurant_id, local_date) over a 200 ms window—turning 50 rapid bookings into 1 recomputation! 4. Critical detail: The worker reads that day's ~100 assignment rows from the shard primary, never an asynchronous read replica (reading a replica lagging by 2 seconds could overwrite Redis with stale availability!). It writes the 12 × 128-bit bitmasks alongside the highest outbox.id processed (SET avail:81:2026-12-12 <payload> EX 3600).

    Contract comparison:
      Property            Search Path (Availability Svc)       Booking Path (Booking Svc)
      ------------------  -----------------------------------  ------------------------------------
      Data source         Redis 128-bit bitmasks (1-2 s old)   PostgreSQL shard primary + row locks
      Can be slightly     Yes (may show a slot taken 1 s ago)  NEVER (enforced by GiST constraint)
      stale?
      Worst-case outcome  HTTP 409 + fresh alternative times   Impossible to double-book
    
  9. Deep dive 3: Holds, edits, walk-ins, and deadlock-free lock ordering

    Real restaurants constantly mutate existing bookings: diners confirm holds or shift times, a background sweeper expires abandoned holds, and hosts seat walk-ins or slide parties between tables. Whenever multiple transactions lock booking, dining_table, and table_assignment, inconsistent lock order causes deadlocks. We enforce one strict global lock hierarchy across every transaction in the codebase:

    Strict Lock Order (top to bottom — never lock upward!):
      1. Existing `booking` row       (SELECT ... FROM booking WHERE id = $id FOR UPDATE)
      2. `dining_table` row(s)        (SELECT ... FROM dining_table WHERE id = ANY(...) ORDER BY id FOR UPDATE)
      3. `table_assignment` row(s)    (UPDATE / INSERT table_assignment ...)
    

    Notice how place_hold skips step 1 (its booking row does not exist yet!) and goes 2 -> 3, while confirm, sweeper, change_booking, and move all start at 1 and move strictly downward—making cross-transaction deadlocks impossible!

    • Confirming a hold vs. hold expiration: Holds expire in two complementary ways: lazily (step 2 of place_hold frees an expired hold immediately if another diner wants that exact table) and actively (every 15 s, the Hold Sweeper queries SELECT id FROM booking WHERE status = 'HELD' AND hold_expires_at < now() FOR UPDATE SKIP LOCKED, marks booking.status = 'EXPIRED', sets table_assignment.active = false, and writes an outbox event so Redis re-opens the slot). When a diner confirms, confirm locks booking (FOR UPDATE), checks status = 'HELD', and runs: sql UPDATE table_assignment SET hold_expires_at = NULL WHERE booking_id = $id AND active = true; If lazy release already deactivated any member table of the booking, the updated row count is smaller than expected, so confirm rolls back and returns 410 HOLD_EXPIRED. Otherwise, even a diner clicking Confirm at 5m 03s graciously succeeds if nobody else needed the table yet!
    • Modifying a booking (19:00 -> 19:15): Lock booking, lock both old and new candidate dining_table rows in ascending id order, set old table_assignment.active = false first (otherwise 19:15 on the same table T12 would collide with the diner's own 19:00 row!), verify no overlap, and insert the new assignment. If no table fits 19:15, ROLLBACK leaves the 19:00 booking completely intact.
    • Walk-ins and lingering tables: Hosts seat walk-ins through the exact same SQL transaction (source = 'WALK_IN'). If a walk-in arrives at 18:15 wanting T12 (which has a 19:30 online booking), 18:15 + 90m + 15m turnover = 20:00 fails the overlap check, and the tablet immediately prompts: "T12 is booked at 19:30—seat walk-in with a 60-min turn ([18:15, 19:30)) or pick T14?" Similarly, if an 18:00 table lingers past 19:30, extending its end_at flags the 19:30 conflict and lets the host one-tap reassign the incoming 19:30 party to another free 4-top.
  10. Scaling, hot restaurant drops, failure modes, and trade-offs

    Sharding strategy - Partition all restaurant-owned tables into 64 logical PostgreSQL schemas/shards (hash(restaurant_id) mod 64) hosted across 4 physical PostgreSQL clusters initially. Because every reservation happens inside a single restaurant, 100% of booking transactions stay single-shard (zero slow two-phase commits!). - Cross-restaurant queries like a diner's "My Upcoming Reservations" screen read from a lightweight diner_bookings lookup table populated asynchronously from Kafka; tapping into one reservation routes directly to restaurant_id's shard for strongly consistent edits.

    Handling a viral monthly release (10,000 reads/s + thousands of concurrent writers) - Edge read shield: Put a 1–2 second CDN cache in front of /availability for hot restaurants, collapsing 10,000 user refreshes/s into ~1 origin cache lookup/s per party size and date. - Virtual waiting room & anti-bot fairness: Everyone present before 10:00:00 enters a pre-drop lobby and receives a randomized queue position at 10:00:00 (eliminating any incentive for millisecond-scraping bots!), admitting ~100 diners/s into the hold endpoint. - Tighter hold rules & shard isolation: Shorten hold TTL from 5 min to 3 min, cap at 1 hold per diner, and live-migrate a notoriously viral restaurant's logical shard onto a dedicated PostgreSQL cluster before its scheduled drop.

    Failure handling - Primary DB crash: Each shard replicates to a synchronous standby (a replica in a second AZ that must write every transaction log entry to disk before the primary acknowledges COMMIT). Automatic failover promotes the standby in 15–30 s with zero lost confirmed bookings; clients retrying during failover pass the same Idempotency-Key and get clean responses while search stays online from Redis. - Redis cluster failure: Bookings continue uninterrupted; Availability Service falls back to rate-limited recomputation from PostgreSQL read replicas and repopulates Redis. - Restaurant Wi-Fi outage: Host tablets cache today's sheet locally on device; offline walk-ins queue locally and replay through the standard transaction on reconnect, surfacing any overlap on the host screen for manual table swap. - Continuous invariant audit: Run an hourly read-replica query checking for any overlapping active = true intervals per table_id (must always return 0 rows) and alert if the oldest expired HELD row exceeds 2 minutes.

Intuition & how it works

Think of a restaurant's daily schedule like a physical pegboard behind the host stand: each horizontal row is one real table (T1, T2, T3), the horizontal axis is time from opening to closing, and every reservation snaps a wooden block onto a specific table's lane spanning [start_time, start_time + dining_duration + cleanup_buffer). Two blocks in the same lane can touch cleanly end-to-end—such as [18:00, 19:30) followed immediately by [19:30, 21:00)—because we model time as half-open intervals (intervals that include their start instant and exclude their end instant), and two blocks may never overlap on the same lane.

The naive approach fails on both correctness and scale. First, tracking a simple counter like "40 empty seats at 19:00" double-books the room whenever 4 empty seats are split across two separate 2-person tables that cannot be pushed together, and checking free tables in application code before inserting lets two simultaneous clicks claim the last table twice. Second, running live overlap queries on the booking database for every search page would hammer the database with roughly 100 search reads for every 1 actual booking, stalling real checkouts whenever a popular restaurant goes viral.

Walk through a tiny concrete trace at a 3-table bistro (T1: 2-top, T2: 2-top, T8: 4-top) for 19:30 (90-min meal + 15-min cleanup = [19:30, 21:15)): 1. 500 diners browse 19:30 for 4 guests: Their apps read a precomputed 128-bit quarter-hour availability bitmask from Redis (< 5 ms), never touching PostgreSQL. 2. Maya and Noah click "Book 19:30 for 4" at the exact same millisecond: Both requests bypass Redis and run a short transaction on the restaurant's PostgreSQL primary shard, executing SELECT id FROM dining_table WHERE id IN (8) FOR UPDATE to lock T8 (T1 and T2 are ignored because neither seats 4). 3. Database arbitrates in 2 milliseconds: Maya's lock wins first, verifies zero overlapping active ranges in table_assignment (backed by a PostgreSQL GiST exclusion constraint—a database index rule that physically rejects overlapping ranges on the same table_id), inserts a 5-minute HELD booking plus an outbox event, and commits. 4. Clean rejection + instant cache update: Noah's waiting FOR UPDATE wakes up, sees Maya's [19:30, 21:15) interval on T8, rolls back, and immediately returns HTTP 409 with nearby open times (17:45, 21:15), while an asynchronous worker reads the outbox event and flips the 19:30 party-of-4 bit to 0 in Redis within half a second.

Key trade-offs

  • Table-time intervals vs. seat counters as inventory. Seat counters are trivial to store and decrement, but they cannot prove a party physically fits onto real tables or spans multiple hours; modeling half-open [start, end) intervals per table requires assigning a concrete table at booking time, and in return turns "never double-book" into an unbreakable database constraint.
  • PostgreSQL GiST exclusion constraint vs. discrete 15-minute slot rows. A GiST (Generalized Search Tree) exclusion constraint stores a single row per assigned table per booking and supports arbitrary durations to the minute, whereas splitting a 2-hour dinner into eight (table_id, 15_min_slot) rows with a standard UNIQUE index multiplies write amplification 8×—though the discrete-grid approach remains a solid fallback if your company runs MySQL or DynamoDB instead of PostgreSQL.
  • Per-table row locks (FOR UPDATE) vs. restaurant-wide lock vs. Redis lock. Locking one restaurant row serializes unrelated bookings (17:30 patio vs. 21:00 bar), while an external Redis distributed lock can expire during a garbage-collection pause and split-brain from the database; locking only the candidate dining_table rows in PostgreSQL lets non-overlapping parties book in parallel while keeping a single source of truth.
  • Hidden system-assigned tables vs. diner-selected tables. Letting the backend pick a table (while keeping table IDs private from the diner) maximizes floor utilization and lets staff slide a party of 2 from T4 to T5 later to free up a T3+T4 combination; letting diners lock specific window tables fragments the floor and should only be offered as an explicit opt-in tier on designated tables.
  • Event-driven cached search vs. live database search. Serving search from precomputed 128-bit Redis bitmasks shields PostgreSQL from 100:1 read spikes and delivers sub-10 ms city-wide pages, trading 1–2 seconds of staleness where an occasional click on a just-booked slot receives 409 SLOT_TAKEN with fresh alternatives.
  • 5-minute checkout holds vs. single-step instant booking. Temporary holds prevent frustrating snipes while a diner enters guest details or a deposit card, at the cost of hiding held tables from other diners for up to 5 minutes—requiring strict per-user hold caps (1 per restaurant, 3 global) and lazy + background expiration.
  • Synchronous standby replication vs. asynchronous replication. Requiring a synchronous standby (a replica in another availability zone that confirms each transaction on disk before COMMIT returns) adds 1–2 ms to booking writes, which is well worth guaranteeing zero lost confirmed reservations during a primary hardware failure.

Common mistakes

  • Modeling inventory as remaining_seats per time bucket. Two free 2-tops on opposite sides of the dining room look like "4 free seats" in a counter, causing embarrassing walk-up overbooking.
  • Using a 16-hour / 64-bit slot bitmask for a full day. A 24-hour local day contains 24 × 4 = 96 quarter-hours (and 100 quarter-hours on a 25-hour fall-back daylight-saving day), so always allocate a 128-bit (16-byte) mask per party size rather than overflowing a 64-bit integer on late-night or 24-hour venues.
  • Application-level check-then-insert (SELECT free tables, then INSERT) without row locks or constraints. Concurrent transactions read the exact same snapshot and double-book the table every time load spikes.
  • Calling Stripe or SMS APIs inside BEGIN ... COMMIT. External HTTP calls take 300–2,000 ms (or hang until timeout), holding PostgreSQL table locks the entire time and freezing checkout for everyone else.
  • Using closed intervals [18:00, 19:30] instead of half-open [18:00, 19:30). Closed intervals falsely treat two back-to-back reservations touching at 19:30 as colliding.
  • Recomputing the Redis availability cache from an asynchronous read replica. If a booking commits at t = 0 and the worker queries a replica lagging by 1.5 s, it overwrites Redis with stale pre-booking availability—always recompute from the shard primary after an outbox event.
  • Locking booking and table_assignment in inconsistent orders across endpoints. If confirm locks table_assignment then booking while the expiry sweeper locks booking then table_assignment, concurrent runs deadlock; enforce booking -> dining_table (ascending id) -> table_assignment everywhere.
  • Bypassing the booking database for walk-ins. Letting the host tablet track walk-ins in a separate table or local memory guarantees online diners will book tables currently occupied by walk-in guests.

Follow-up questions

  • Suppose a high-demand venue releases an entire month of inventory at a scheduled hour and thousands of guests rush to book simultaneously—how do you adapt the architecture? Keep the exact same PostgreSQL per-table locking and exclusion constraint for correctness, and add shock absorbers in front of both paths: shield reads with a 1–2 second CDN (Content Delivery Network edge cache) on /availability, and place a virtual waiting room in front of POST /holds that collects everyone waiting before 10:00 AM and assigns randomized queue tokens at 10:00 (defeating speed bots) to admit ~100 diners/s smoothly. Shorten holds to 3 minutes, enforce 1 active hold per diner, and pre-migrate that restaurant's logical shard onto an isolated PostgreSQL cluster before the drop; because row locks are per dining_table rather than restaurant-wide, diners booking different tables or nights still execute in parallel.
  • How can the allocator combine multiple tables for large groups while minimizing wasted capacity and blocked prime-time slots? Only allow combinations explicitly configured by staff (table_combo, such as adjacent T5 + T6 for 6–8 guests), and rank candidates during place_hold so single large tables are always tried first, followed by the combination with the smallest total seat capacity and fewest surrounding prime-time slots disrupted. Claiming a combo locks all member dining_table rows in ascending id order (preventing deadlocks between overlapping combos like T5+T6 and T6+T7) and inserts one table_assignment row per member table atomically. Because diners never see assigned table IDs, a lightweight background defragmentation job (or one-tap host suggestion) can swap an earlier party of 2 from T5 onto an identical free 2-top T9 inside a single ACID transaction to free T5+T6 for a party of 6.
  • What should happen when a manager retires a table from the floor layout while upcoming confirmed reservations are still mapped to it? Never DELETE the dining_table row; instead, lock the dining_table row (FOR UPDATE, serializing against any concurrent place_hold) and set active_until to the effective removal date so no new bookings can select it on or after that date. Immediately run a reassignment job that iterates through existing future bookings on that table and attempts to move each one to another free fitting table or combo via the standard atomic move transaction. Surface a clear summary on the staff dashboard (for example, "14 future bookings affected: 12 automatically moved to equivalent tables, 2 require host review"), leaving the unresolved conflicts highlighted for staff to combine tables, adjust hours, or personally contact the guest—never silently cancelling a confirmed diner.
  • How do you integrate upfront reservation deposits while guaranteeing network retries never double-charge a guest? Require a client-generated idempotency key (a unique request token per checkout attempt) on POST /confirm, and persist deposit_status = 'PENDING' plus the key row in PostgreSQL before making any network call so PostgreSQL locks aren't held during payment. Call the payment processor (such as Stripe) outside the DB transaction while passing booking_id as the processor's own idempotency key—guaranteeing that even if our server crashes mid-flight and retries, the processor charges the card at most once—then update deposit_status = 'AUTHORIZED' (or 'CAPTURED') and status = 'CONFIRMED'. A background reconciler polls any booking stuck in PENDING for more than a minute against the payment provider to either finalize confirmation or void the orphaned charge; for bookings up to 30 days ahead (since standard card authorizations expire after ~7 days), tokenize and save the payment method at booking time (SetupIntent) and run the idempotent charge/authorization only when a late cancellation or no-show actually occurs (or capture upfront and issue an idempotent refund on timely cancellation).

Follow-up questions

Similar questions

More Toast interview questions

All 2 Toast questions →