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
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/bookingp99 < 500 ms. - Freshness split: Search results may lag reality by1–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,000restaurants,2Mbookings/day,50Msingle-restaurant page views/day, and10Mcity-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.,2guests =90 min,3–4=105 min,5+=120 min) plus a15-minutecleaning/turnover buffer. We computeend_atwhen creating the booking so a future rule edit never silently shifts existing reservations. - Booking window & policies: Up to30 daysahead by default; optional deposits (e.g.,$25/personfor parties of6+); overbooking is off by default (with an opt-in table-less buffer explained later).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 holdsWhat these numbers tell us: Platform-wide write throughput (
~330total 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/son a single famous restaurant), so search must be served from a compact~465 MBprecomputed cache without touching PostgreSQL.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.- 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.
- Discrete
(table_id, 15_min_bucket)grid rows: A 105-minute seating inserts7bucket rows withUNIQUE (table_id, bucket_start). Works on any database with unique indexes, but multiplies row writes6–8×and forces every custom duration onto fixed 15-minute boundaries. - 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 timestampaand excludes its end timestampb. 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 ifstart_1 < end_2 AND start_2 < end_1.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-minutehold 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-Keyheader): 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-Matchversion header): Each edit passes the booking's last seenversioninteger; if staff and the diner edit the same booking simultaneously, the second writer gets412 Precondition Failedinstead 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), and409 SLOT_TAKENreturns live alternative slots computed right inside the database fallback path so a diner who loses a race can pick18:45in one tap.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 IANAtimezone('America/New_York') so daylight-saving transitions never shift a19:00local dinner to18:00or20: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 equaltable_id(=) and overlappingduringranges (&&). - Transactional outbox (outboxtable): 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 + T6simply inserts two rows intotable_assignment(one forT5, one forT6) in the same transaction, sono_double_bookingprotects each individual table automatically. 2. Soft deactivation (active = false) instead ofDELETE: Keeping historical assignment rows lets us audit staff table moves, and using abigserial idprimary key (rather than(booking_id, table_id)) lets a diner shift a reservation from19:00to19:15on the same tableT12cleanly.High-level architecture: separating search from booking
Because diners browse roughly
100times 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-byteRedis entry (avail:{rid}:{date}). City searches query the geo/cuisine search index for the top 20 matchingrestaurant_ids, then issue a single batchedMGETof 20 keys from Redis. On a cold cache miss, the service computes the mask from a PostgreSQL read replica and writes to Redis withSET 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.
- Search path: Single-restaurant searches fetch one
Deep dive 1: Preventing double-booking under simultaneous clicks
Suppose Table
T8is the very last 4-top open at19:30, and Maya and Noah both tap "Book" at19:30:00.050. Let's compare why naive concurrency approaches fail before tracing our solution: - Application check-then-insert (SELECTfree tables, thenINSERT): Both Maya and Noah runSELECTat.050, both seeT8free, 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 for6 seconds, her Redis lock expires, Noah acquires the lock and booksT8, 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 booking17:30to wait in a single-file line behind 500 people fighting over20:00on Valentine's Day.The authoritative solution: per-table row locks (
SELECT ... FOR UPDATE) backed by the GiST exclusion constraint. Why use bothFOR UPDATEondining_tableand the exclusion constraint ontable_assignment? WithoutFOR UPDATE, two simultaneous inserts intotable_assignmentwait on each other inside PostgreSQL's GiST index check untildeadlock_timeout(1,000 msdefault!) before aborting one. Locking thedining_tablerow(s) in ascendingidorder turns that 1-second deadlock stall into an orderly2 msqueue!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] optionsHere is the exact SQL transaction for claiming one candidate option (
$table_idsis[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 NoneGolden 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 for1–3 ms, allowing hundreds of concurrent holds per second on a single restaurant.Deep dive 2: Precomputing fast availability in Redis
Why not patch individual bits in Redis when a booking happens? Because one booking on
T5can simultaneously block single-table party sizes3–4and comboT5+T6for party sizes6–8across seven overlapping 15-minute start slots! Instead, recomputing the entire restaurant-day from scratch is both simpler and tiny: - Service hours have ~40–60quarter-hour start slots (11:00to22:00). - Party sizes1..12=12sizes. - ~30single tables + ~10combos =40options. - Checking50 slots × 12 sizes × 40 optionsagainst2–3sorted bookings per table is< 50,000integer comparisons—taking under1 millisecondin 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 FalseKeeping the Redis cache fresh without race conditions: 1. Every hold, confirm, move, walk-in, or cancel writes an
outboxrow for(restaurant_id, local_date). 2. The Outbox Relay publishes to Kafka partitioned byrestaurant_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 a200 mswindow—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 the12 × 128-bitbitmasks alongside the highestoutbox.idprocessed (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-bookDeep 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, andtable_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_holdskips step 1 (itsbookingrow does not exist yet!) and goes2 -> 3, whileconfirm,sweeper,change_booking, andmoveall start at1and 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_holdfrees an expired hold immediately if another diner wants that exact table) and actively (every15 s, the Hold Sweeper queriesSELECT id FROM booking WHERE status = 'HELD' AND hold_expires_at < now() FOR UPDATE SKIP LOCKED, marksbooking.status = 'EXPIRED', setstable_assignment.active = false, and writes anoutboxevent so Redis re-opens the slot). When a diner confirms,confirmlocksbooking(FOR UPDATE), checksstatus = '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, soconfirmrolls back and returns410 HOLD_EXPIRED. Otherwise, even a diner clicking Confirm at5m 03sgraciously succeeds if nobody else needed the table yet! - Modifying a booking (
19:00 -> 19:15): Lockbooking, lock both old and new candidatedining_tablerows in ascendingidorder, set oldtable_assignment.active = falsefirst (otherwise19:15on the same tableT12would collide with the diner's own19:00row!), verify no overlap, and insert the new assignment. If no table fits19:15,ROLLBACKleaves the19:00booking 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 at18:15wantingT12(which has a19:30online booking),18:15 + 90m + 15m turnover = 20:00fails 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 an18:00table lingers past19:30, extending itsend_atflags the19:30conflict and lets the host one-tap reassign the incoming19:30party to another free 4-top.
- Confirming a hold vs. hold expiration: Holds expire in two complementary ways: lazily (step 2 of
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 across4physical 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 lightweightdiner_bookingslookup table populated asynchronously from Kafka; tapping into one reservation routes directly torestaurant_id's shard for strongly consistent edits.Handling a viral monthly release (
10,000 reads/s+ thousands of concurrent writers) - Edge read shield: Put a1–2 secondCDN cache in front of/availabilityfor hot restaurants, collapsing10,000user refreshes/s into ~1 origin cache lookup/s per party size and date. - Virtual waiting room & anti-bot fairness: Everyone present before10:00:00enters a pre-drop lobby and receives a randomized queue position at10:00:00(eliminating any incentive for millisecond-scraping bots!), admitting~100 diners/sinto the hold endpoint. - Tighter hold rules & shard isolation: Shorten hold TTL from5 minto3 min, cap at1hold 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 in15–30 swith zero lost confirmed bookings; clients retrying during failover pass the sameIdempotency-Keyand 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 overlappingactive = trueintervals pertable_id(must always return0rows) and alert if the oldest expiredHELDrow exceeds2 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 standardUNIQUEindex multiplies write amplification8×—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:30patio vs.21:00bar), while an external Redis distributed lock can expire during a garbage-collection pause and split-brain from the database; locking only the candidatedining_tablerows 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
T4toT5later to free up aT3+T4combination; 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-bitRedis bitmasks shields PostgreSQL from100:1read spikes and delivers sub-10 mscity-wide pages, trading1–2 secondsof staleness where an occasional click on a just-booked slot receives409 SLOT_TAKENwith 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 (
1per restaurant,3global) 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
COMMITreturns) adds1–2 msto booking writes, which is well worth guaranteeing zero lost confirmed reservations during a primary hardware failure.
Common mistakes
- Modeling inventory as
remaining_seatsper 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-bitslot bitmask for a full day. A24-hourlocal day contains24 × 4 = 96quarter-hours (and100quarter-hours on a 25-hour fall-back daylight-saving day), so always allocate a128-bit(16-byte) mask per party size rather than overflowing a64-bitinteger on late-night or 24-hour venues. - Application-level check-then-insert (
SELECTfree tables, thenINSERT) 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 take300–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 at19:30as colliding. - Recomputing the Redis availability cache from an asynchronous read replica. If a booking commits at
t = 0and the worker queries a replica lagging by1.5 s, it overwrites Redis with stale pre-booking availability—always recompute from the shard primary after an outbox event. - Locking
bookingandtable_assignmentin inconsistent orders across endpoints. Ifconfirmlockstable_assignmentthenbookingwhile the expiry sweeper locksbookingthentable_assignment, concurrent runs deadlock; enforcebooking -> dining_table (ascending id) -> table_assignmenteverywhere. - 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 secondCDN (Content Delivery Network edge cache) on/availability, and place a virtual waiting room in front ofPOST /holdsthat collects everyone waiting before10:00 AMand assigns randomized queue tokens at10:00(defeating speed bots) to admit~100 diners/ssmoothly. Shorten holds to3 minutes, enforce1active hold per diner, and pre-migrate that restaurant's logical shard onto an isolated PostgreSQL cluster before the drop; because row locks are perdining_tablerather 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 adjacentT5 + T6for6–8guests), and rank candidates duringplace_holdso 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 memberdining_tablerows in ascendingidorder (preventing deadlocks between overlapping combos likeT5+T6andT6+T7) and inserts onetable_assignmentrow 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 fromT5onto an identical free 2-topT9inside a single ACID transaction to freeT5+T6for 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
DELETEthedining_tablerow; instead, lock thedining_tablerow (FOR UPDATE, serializing against any concurrentplace_hold) and setactive_untilto 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 atomicmovetransaction. 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 persistdeposit_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 passingbooking_idas 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 updatedeposit_status = 'AUTHORIZED'(or'CAPTURED') andstatus = 'CONFIRMED'. A background reconciler polls any booking stuck inPENDINGfor 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
- 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?
- How can the allocator combine multiple tables for large groups while minimizing wasted capacity and blocked prime-time slots?
- What should happen when a manager retires a table from the floor layout while upcoming confirmed reservations are still mapped to it?
- How do you integrate upfront reservation deposits while guaranteeing network retries never double-charge a guest?
Similar questions
- Auditing a Multi-File HTTP Service for Method, Payload, and Validation Defects
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency