Design a Table Booking Platform
System DesignModel answerLast updated
Design a scalable system for booking dining tables that handles concurrent requests and prevents conflicts.
You're building a platform that lets diners reserve tables at restaurants. The system needs to support searching for dining options, checking availability, making reservations, and cancellations.
Core Features
Your system must support:
- Discovery: Diners search for restaurants by location, food type, and dining time
- Availability checking: Users see open time slots for a particular venue and party size
- Booking: Reserve a table for a specific group size and time
- Cancellation: Remove existing bookings
Technical Constraints
- Strong consistency for reservations—the same slot cannot be given to multiple parties
- Handle traffic spikes during popular dining hours (lunch/dinner rushes)
- Fast search with minimal lag for browsing and filtering
What to Cover
Provide a complete architecture covering:
- REST endpoints for search, booking operations, and cancellation
- Database schema showing how you track table state and availability
- Concurrency mechanisms to ensure two simultaneous requests don't claim the same slot
- Infrastructure choices including caching layers, load distribution, and storage systems
Focus on the booking consistency problem—how you guarantee atomicity when multiple users compete for limited inventory.
Hints
Hint 1
Think about whether users book specific tables or just capacity slots—this affects your data model
Hint 2
Consider a two-phase approach: temporarily hold a slot while collecting user details, then confirm
Hint 3
Use database row-level locking or versioning to handle race conditions on the same table
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Table Booking Platform Design
1. Requirements Analysis and Scale Estimation
Start by clarifying ambiguities with your interviewer:
Inventory semantics: Are we booking individual tables or aggregate capacity? I'll assume table-level tracking with tables grouped by capacity (2-seat, 4-seat, etc.)—this is more complex and realistic.
Time granularity: Use 15-minute increments. Each reservation spans multiple consecutive slots (e.g., 90 minutes = 6 slots).
Booking horizon: Users can book up to 60 days in advance.
Scale estimates:
- 100,000 restaurants, averaging 20 tables each
- 20M monthly active users
- Read traffic: 5,000 QPS average, 20,000 QPS peak (search and availability)
- Write traffic: 50 QPS average, 500 QPS peak (bookings)
- Inventory records: 100K restaurants × 20 tables × 60 days × 48 slots/day ≈ 6 billion rows
Key insight: reads dominate writes ~40:1. Reads tolerate slight staleness; writes demand strict consistency. Design these paths separately.
2. API Design
GET /restaurants
?lat=&lng=&radius_km=&cuisine=&party_size=&datetime=&cursor=
→ [{id, name, cuisine, distance_km, open_slots: ["19:00", "19:30"]}]
GET /restaurants/{id}/slots?date=2024-06-01&party_size=4
→ [{time: "19:00", available: true}, {time: "19:15", available: false}, ...]
POST /reservations/locks (with Idempotency-Key header)
{restaurant_id, party_size, start_time}
→ {lock_id, table_id, expires_at} | 409 if unavailable
POST /reservations (with Idempotency-Key header)
{lock_id, guest_name, contact, special_requests}
→ {reservation_id, status: "confirmed"} | 410 if lock expired
DELETE /reservations/{id}
→ {status: "cancelled"}
The lock-then-confirm pattern prevents cart abandonment from blocking inventory. Users get 5-7 minutes to complete their booking while holding the slot.
3. Data Schema
Use a relational database (PostgreSQL) for transactional integrity:
CREATE TABLE restaurants (
id BIGINT PRIMARY KEY,
name VARCHAR(255),
cuisine VARCHAR(100),
latitude DECIMAL(9,6),
longitude DECIMAL(9,6),
timezone VARCHAR(50),
slot_duration_mins INT,
reservation_duration_mins INT
);
CREATE TABLE dining_tables (
id BIGINT PRIMARY KEY,
restaurant_id BIGINT,
capacity INT,
min_guests INT
);
CREATE TABLE slot_inventory (
restaurant_id BIGINT,
table_id BIGINT,
time_slot TIMESTAMP,
state VARCHAR(20) CHECK (state IN ('available', 'locked', 'reserved')),
lock_id UUID,
lock_expiry TIMESTAMP,
reservation_id BIGINT,
PRIMARY KEY (restaurant_id, table_id, time_slot)
);
CREATE TABLE bookings (
id BIGINT PRIMARY KEY,
restaurant_id BIGINT,
user_id BIGINT,
table_id BIGINT,
start_time TIMESTAMP,
end_time TIMESTAMP,
party_size INT,
state VARCHAR(20),
idempotency_key UUID UNIQUE,
created_at TIMESTAMP
);
Key design choices:
- Explicit rows per (table, slot) make locking straightforward
- Pre-materialize slots for 60 days via daily batch jobs
- Shard by
restaurant_idso each transaction stays within one shard idempotency_keyprevents duplicate submissions
4. System Architecture
Users → API Gateway (auth, rate limiting) → Load Balancer
↓ ↓
Search Service Reservation Service
↓ ↓
Elasticsearch (location + cuisine) PostgreSQL (sharded by restaurant_id)
Redis (availability cache) ↓
Event Stream (Kafka)
↓
[Cache Invalidator, Search Indexer,
Notifications, Analytics]
Search Service (read-heavy):
- Elasticsearch handles geospatial queries and cuisine filtering
- Redis caches availability bitmaps per restaurant/date with 30-second TTL
- Results may be slightly stale—acceptable since booking re-validates against source of truth
- Horizontally scaled stateless instances
Reservation Service (write-critical):
- Only component that modifies inventory
- Uses transactional outbox pattern: writes to database and outbox table atomically
- Background relay publishes outbox events to Kafka
- Stateless, horizontally scaled
Storage Strategy:
- Shard PostgreSQL by
restaurant_idusing consistent hashing - Each shard has primary + read replicas
- Why not shard by geography? Creates hot shards (downtown Friday nights) and offers no benefit since bookings never span restaurants
5. Concurrency Control (Critical Section)
Approach: Row-Level Locking with Conditional Update
When a lock request arrives:
BEGIN TRANSACTION;
-- Find candidate table of appropriate size, acquire row locks
SELECT table_id, time_slot
FROM slot_inventory
WHERE restaurant_id = :rid
AND table_id = :tid
AND time_slot BETWEEN :start AND :end
AND state = 'available'
FOR UPDATE SKIP LOCKED;
-- If we got all required slots, claim them
UPDATE slot_inventory
SET state = 'locked',
lock_id = :new_lock_id,
lock_expiry = NOW() + INTERVAL '7 minutes'
WHERE (restaurant_id, table_id, time_slot) IN (...)
AND state = 'available';
-- If UPDATE affected 0 rows, table was claimed by someone else
-- Insert booking record and outbox event
INSERT INTO bookings (...);
INSERT INTO outbox_events (...);
COMMIT;
Why this works:
FOR UPDATEacquires row locks, serializing competing transactionsSKIP LOCKEDlets other users try different tables instead of waiting- The
state = 'available'predicate ensures only one transaction transitions each row - Losers get 0 updated rows and immediately try alternate tables
- Locking slots in time order prevents deadlocks
Confirmation step:
UPDATE slot_inventory
SET state = 'reserved', reservation_id = :rid
WHERE lock_id = :lock_id
AND lock_expiry > NOW();
Returns 410 error if the lock expired.
Alternative approaches:
Optimistic locking: Add version column, retry on conflict. Works under low contention but wastes CPU on hot slots.
Distributed locks (Redis): Adds external dependency and failure modes. Single-database locking is simpler and sufficient.
Serializable isolation: Simpler code but lower throughput due to transaction retries.
6. Cache Strategy
Search results: Cache by (geohash, cuisine, date) for 2-5 minutes. Invalidate on restaurant updates.
Availability bitmaps: Per restaurant/date in Redis, 30-second TTL. Compact representation (bit per table/slot combination). Background job or Kafka consumer refreshes on booking events.
Trade-off: Slight staleness is acceptable—users see optimistic availability, but booking logic re-checks database. This prevents cache-thundering-herd on the transactional store.
7. Common Mistakes
- Not addressing race conditions: Simply checking availability then writing fails under concurrency
- Over-engineering with distributed consensus: Single-database locking is sufficient for restaurant-scoped inventory
- Holding database connections during user input: Causes connection exhaustion; use the lock/confirm pattern instead
- Ignoring idempotency: Duplicate requests from retries will double-book without idempotency keys
- Forgetting time zones: Store everything in UTC, convert at API boundary using restaurant's timezone
8. Follow-Up Questions
Q: How do you handle expired locks?
Background job runs every minute to release locks where lock_expiry < NOW(). Set state back to available and publish release events.
Q: What about overbooking (airlines-style)?
Add overbook_factor to restaurants table. Generate 110% of physical capacity in slots. Track no-show rates per restaurant.
Q: Scaling to 100M users? Current design scales horizontally (stateless services) and via sharding (database). Add more shards by consistent hashing. Use read replicas for non-booking queries.
Q: How do you prevent bots from holding all slots? Rate limiting per user, CAPTCHA on repeated failures, require deposits for peak times, limit number of concurrent locks per user.