Designing a Multi-Restaurant Booking Platform
System DesignModel answerLast updated
Build a reservation system where users find and book tables across restaurants while preventing double-bookings under concurrent requests.
You're building a platform that connects diners with restaurants for table reservations. Users should be able to find available seating across multiple venues, secure a reservation, and modify or cancel it later. Restaurant owners need to set up their seating capacity, operating hours, view incoming reservations, and track guest arrivals and absences.
Your design should address:
Core Functionality:
- Users query open time slots by filtering on city, date, desired time, and group size
- Users complete a reservation for a selected slot
- Users update or remove their existing reservations
- Restaurants define their table inventory and service windows
- Restaurants view their reservation schedule and update party status
Key Constraints:
- The platform serves numerous restaurants across multiple cities
- Browsing activity significantly exceeds actual booking completions
- No table can be confirmed for two different groups during overlapping periods—this is your primary correctness requirement
- Payment processing, rating systems, and food menus are outside this scope
Design Phases:
Phase 1 — Foundation Establish what the system must achieve for both user types and what it explicitly won't handle. Define the core API contracts and storage schema for venues, seating inventory, operating schedules, and reservation records. Show how you'll track which tables are occupied when.
Phase 2 — Preventing Conflicts Detail the end-to-end flow when a user commits to a time slot. If two users simultaneously select the final available table for the same period, your design must ensure only one succeeds. Address retry scenarios, connection failures during booking, and how venue-side changes (like removing tables) affect existing reservations.
Phase 3 — Performance at Scale Most requests are users exploring options across many venues. Explain how availability queries remain responsive and reasonably current. Then consider a scenario where a highly sought-after venue releases new booking dates: describe how your system handles the surge without degrading service for other venues or treating users unfairly.
Provide rough capacity estimates to justify your choices, explain your trade-offs, and describe how you'd verify the system is working correctly.
Hints
Hint 1
Think about separating read-heavy browsing from write-critical booking confirmation—different consistency needs suggest different strategies.
Hint 2
The core correctness challenge is serializing access to the same table-time combination; consider database primitives that naturally enforce mutual exclusion.
Hint 3
For high-traffic venues, consider whether you need temporary claims on tables before final confirmation, and how those claims expire if abandoned.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Phase 1: Foundation and Data Model
Functional Requirements:
For users: discover venues with availability, create reservations specifying party size and time, modify reservation details (time, size), cancel reservations, receive confirmations and reminders.
For venues: configure table inventory (quantity, capacity ranges), set operating hours and service periods (lunch, dinner), view reservation calendar, mark parties as arrived or absent.
Non-functional Requirements:
- Availability reads vastly outnumber bookings (perhaps 100:1 ratio)
- Booking confirmation requires strong consistency—zero tolerance for double-booking
- Availability search can tolerate slight staleness (seconds to minutes)
- Handle traffic spikes when popular venues open new dates
- Geographic distribution across cities
APIs:
POST /api/search
{ city, date, time, partySize }
→ [ { restaurantId, availableSlots[] } ]
POST /api/bookings
{ restaurantId, date, timeSlot, partySize, userId, idempotencyKey }
→ { bookingId, confirmationCode, status }
PATCH /api/bookings/{bookingId}
{ newDate?, newTime?, newPartySize?, idempotencyKey }
→ { status }
DELETE /api/bookings/{bookingId}
{ idempotencyKey }
→ { status }
Restaurant APIs for configuration and viewing would be separate but similar patterns.
Data Model:
Restaurant: id, name, location, contactInfo
Table: id, restaurantId, minCapacity, maxCapacity
(e.g., a 4-top can seat 2-4 people)
ServicePeriod: id, restaurantId, dayOfWeek, startTime, endTime, slotDuration
(defines lunch/dinner windows and standard seating duration)
Booking: id, restaurantId, tableId, userId, date, startTime, endTime,
partySize, status, createdAt, idempotencyKey
(status: pending, confirmed, seated, cancelled, no_show)
BookingIndex: restaurantId_date_time → list of table IDs
(denormalized for fast availability checks)
The booking duration typically comes from the service period configuration—perhaps 90 minutes for dinner, 60 for lunch. The table assignment can happen at booking time or be deferred to restaurant staff, depending on the venue's preference.
Phase 2: Conflict-Free Booking
Confirmation Flow:
- User submits booking request with idempotency key
- System validates the request (restaurant exists, time is valid, party size feasible)
- Begin database transaction
- Query available tables:
SELECT id FROM Table WHERE restaurantId = ? AND minCapacity <= ? AND maxCapacity >= ? AND id NOT IN (SELECT tableId FROM Booking WHERE restaurantId = ? AND date = ? AND status IN ('confirmed', 'seated') AND timeRangesOverlap) - If no tables available, return failure immediately
- Insert booking record with status='confirmed' and the selected table
- Commit transaction
- Asynchronously send confirmation message
Concurrency Control:
Use database-level locking to serialize competing requests. Two approaches:
Pessimistic locking: SELECT ... FOR UPDATE on the table record during the transaction. The second concurrent request blocks until the first commits or rolls back.
Optimistic locking: Include a version number in the Booking table. Check for conflicts at insert time using a unique constraint on (restaurantId, tableId, date, timeSlot, status) where status is not cancelled. If a second request tries to book the same slot, the database rejects it with a constraint violation.
Pessimistic is simpler for this use case since conflicts are expected during spikes.
Idempotent Retries:
The idempotency key (client-generated UUID) prevents duplicate bookings if the client retries. Before starting the booking logic, check:
SELECT * FROM Booking WHERE idempotencyKey = ?
If found and recent (within 24 hours), return the existing booking. This handles network failures after the booking was confirmed but before the response reached the client.
Hold Mechanism (Optional):
For complex flows where payment or additional confirmation steps follow table selection, implement short-lived holds:
- User selects slot, system creates Booking with status='held' and expiresAt = now + 10 minutes
- User completes payment or confirmation
- System updates status to 'confirmed' before expiration
A background job releases expired holds every minute. This reduces lock contention but adds complexity. For simple flows, skip directly to confirmed status.
Venue Changes:
When a restaurant removes a table or closes a service period, check for existing confirmed bookings:
- If bookings exist, reject the change or notify restaurant to contact affected guests
- Cancelled or past bookings don't block the change
- System could offer automatic rebooking to alternative tables if available
Phase 3: Scaling Search and Surge Handling
Availability Read Path:
Maintain a materialized availability cache:
AvailabilityCache: restaurantId_date_timeSlot → availableTableCount
Update pattern:
- On booking confirmation: decrement counter
- On cancellation: increment counter
- TTL: 5 minutes, rebuild from database on miss
Cache in Redis partitioned by restaurant ID. This allows:
- Sub-100ms search queries across hundreds of restaurants
- Slight staleness is acceptable—users see near-real-time availability
- If cache is slightly stale and user attempts to book a "available" slot that's actually taken, the transaction in Phase 2 will catch it
For cities with thousands of restaurants, partition search by geographic quadrants so queries only scan relevant restaurants.
Capacity Estimation:
Assume 10,000 restaurants, each with 20 tables, 2 service periods/day, 12 time slots per service, 30 days booking window:
- Availability keys: 10K × 20 × 2 × 12 × 30 = 144M slots
- At 100 bytes per cache entry: ~14GB
- Comfortably fits in memory across a few Redis nodes
Handling Booking Spikes:
When a popular restaurant opens new dates at a published time:
-
Rate limiting: Apply per-user rate limits (e.g., 5 booking attempts per minute) to prevent single users from monopolizing the system
-
Queue-based admission control: During detected spikes (monitor request rate per restaurant), funnel requests through a queue with fixed processing rate. Return estimated wait time to users: "You're in line, estimated wait: 2 minutes"
-
Database partitioning: Ensure bookings table is partitioned by restaurant ID so one hot restaurant doesn't create lock contention affecting others
-
Fast rejection: If a restaurant's slots are fully booked, update a flag in cache so subsequent requests receive immediate "sold out" responses without database queries
-
Fairness: First-come-first-served via queue preserves fairness. Alternatively, use lottery system where users register interest and winners are randomly selected.
Asynchronous Work:
- Confirmation emails/SMS: published to message queue after booking commits
- Reminders: cron job queries bookings for next day, sends reminders
- No-show handling: restaurants mark status, triggers analytics pipeline
- Metrics collection: track conflict rate, hold expiration rate, search latency
Observability:
- Alert on database transaction conflict rate exceeding threshold
- Dashboard showing availability cache hit rate and staleness
- Audit query: verify no overlapping confirmed bookings for same table
- Monitor per-restaurant booking velocity to detect abuse or surge
Trade-offs:
- Slot-based vs. flexible intervals: Fixed slots (7:00, 7:15, 7:30) simplify availability calculation but reduce flexibility. Flexible intervals allow optimal packing but complicate conflict detection.
- Immediate confirmation vs. holds: Direct confirmation reduces complexity but may frustrate users who lose a slot while browsing details. Holds improve UX but require expiration management.
- PostgreSQL vs. distributed database: PostgreSQL with proper partitioning handles this scale with strong consistency. Distributed databases add operational complexity without clear benefit until much larger scale.
This design prioritizes correctness where it matters (booking confirmation), performance where traffic is highest (availability search), and graceful degradation during spikes.