Build an In-Memory Venue Reservation Engine
System DesignModel answerLast updated
Design data structures and APIs for a reservation system that runs entirely in memory, handles concurrent bookings, and prevents double-reservations.
Build an In-Memory Venue Reservation Engine
You are building the core reservation engine for a chain of accommodations. There is no database — all state lives in memory for the lifetime of the process.
What you need to support
- Register a property, define its room categories, and set how many rooms exist in each category.
- Query which room categories have availability for a given arrival and departure date.
- Place a reservation for one or more rooms of a given category.
- Cancel an existing reservation and return those rooms to the available pool.
- Guarantee that two concurrent requests for the last available room cannot both succeed.
Constraints and expectations
- No external storage of any kind. Use only in-process data structures.
- Before writing anything, state your assumptions clearly: how dates are interpreted, whether check-out day is considered occupied, your planning horizon, and what is out of scope.
- Walk through the complexity of each operation. Justify your data structure choices.
- Explain your concurrency strategy. Describe the granularity of your locks and why you chose it. Identify any deadlock risks and how you would avoid them.
- You do not need to handle pricing or payments, but mention how you would extend the design if a payment hold step were added between search and confirmation.
What a strong answer looks like
A clear set of upfront assumptions, a data model with explicit reasoning, an API surface, a step-by-step explanation of how a booking is executed atomically, a comparison of at least two locking strategies with trade-offs, and a short code sketch of the critical booking path.
Hints
Hint 1
The hardest invariant to preserve is: available count never goes negative across every night in the requested range. Think about what 'atomic check-then-act' means in a multi-threaded context before picking a lock scope.
Hint 2
Storing a per-night integer counter per room category (rather than a list of bookings) makes availability checks a simple range-minimum scan and keeps memory usage predictable. Sketch the math: how many counters do you actually need?
Hint 3
When you hold multiple locks at once (e.g., booking two room categories in one transaction), you need a consistent acquisition order to avoid deadlock. What property of your data can you sort by?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a low-level design problem with three distinct challenges: choosing the right availability model, getting date semantics exactly right, and picking a locking strategy that prevents double-booking without choking throughput. Address each in order.
1. State Assumptions Upfront
These should come before any code:
- Dates are local calendar dates, not timestamps. A stay is the half-open interval
[arrival, departure). A guest departing on the 5th frees the room for a guest arriving on the 5th. This eliminates time-zone edge cases from the core logic. - Planning horizon is bounded — say 365 days from a fixed base date. Each date maps to an integer index
d = (date - base).days, which lets you use plain arrays instead of hash maps. - Reservations are against room categories, not specific physical rooms. Room assignment happens at check-in and is out of scope here.
- Single process, multi-threaded server. Multi-node is an extension; mention it but don't design it unless asked.
- Out of scope: pricing, payment. For payment flows, briefly note a "hold with TTL" pattern: a booking moves through PENDING → CONFIRMED → CANCELLED, and a background thread expires stale PENDING holds.
Rough sizing check. 5,000 properties × 8 categories × 365 nights ≈ 14.6M integer counters. At 4 bytes each that is ~58 MB. At ~100 bytes per booking, 5M active bookings is ~500 MB. The system is CPU- and lock-contention-bound, not memory-bound.
2. Data Model
Property
id, name, city
room_types: {rt_id -> RoomCategory}
RoomCategory
id, label, total_rooms
available[D] # available[d] = rooms free on night d, D = horizon length
lock # one lock per (property, category)
Booking
id, user_id, property_id, rt_id
arrival_idx, departure_idx, qty
status: CONFIRMED | CANCELLED
Indexes
properties_by_city: {city -> [property_id]}
bookings: {booking_id -> Booking}
idempotency: {key -> booking_id}
The core insight: store a per-night integer count, not a list of bookings. A request for qty rooms over nights [s, e) is valid if and only if min(available[s:e]) >= qty. This makes the check a single range scan and the update a simple loop decrement — no set intersections, no booking list traversal.
3. API Surface
add_property(name, city) -> property_id
add_category(property_id, label, count) -> rt_id
search(city_or_property_id, arrival, departure, qty=1) -> [(property_id, rt_id, min_available)]
reserve(user_id, property_id, rt_id, arrival, departure, qty, idempotency_key) -> booking_id | None
cancel(booking_id) -> bool
4. Operation Complexity
Let N = nights in the request, D = horizon, P = properties in a city, T = categories per property.
| Operation | Plain array | Segment tree (range-min + lazy range-add) |
|---|---|---|
| Availability check | O(N) | O(log D) |
| Reserve / Cancel | O(N) | O(log D) |
| City-wide search | O(P·T·N) | O(P·T·log D) |
For typical hotel stays of 1–7 nights the plain array wins: it is simpler, cache-friendly, and N is tiny. The segment tree is worth adding only if long-term rentals (30–90 nights) become common. Mention both and justify the default.
5. Preventing Double-Booking
The check-then-decrement must be atomic. Both steps run inside the same critical section.
Lock granularity options:
- Global lock — correct but serializes everything; not acceptable.
- Per property — reasonable starting point, still creates unnecessary contention between independent room categories.
- Per (property, category) — the right default. Bookings for different categories in the same property never contend with each other.
- Per (category, date) striping — maximizes parallelism but requires acquiring N locks per request in ascending order to avoid deadlock. Almost never worth the complexity.
Multi-category reservations (e.g., 1 suite + 2 doubles as a single atomic transaction):
- Sort the locks by
(property_id, rt_id)— canonical order prevents deadlock. - Validate all categories.
- Apply all decrements, then release.
Idempotency — network retries must not create duplicate bookings. Check the idempotency key before acquiring the inventory lock, then record it inside the same critical section.
Optimistic vs. pessimistic: A version-number CAS approach works well under low contention. Under hot inventory (holiday weekends) it causes retry storms. Pessimistic fine-grained locking is the safer default for a booking system.
6. Critical Path in Code
import threading, uuid
from datetime import date
class RoomCategory:
def __init__(self, rt_id, total, horizon):
self.id = rt_id
self.total = total
self.available = [total] * horizon
self.lock = threading.Lock()
class ReservationEngine:
def __init__(self, base: date, horizon: int = 365):
self.base = base
self.D = horizon
self.properties = {} # property_id -> {rt_id -> RoomCategory}
self.bookings = {} # booking_id -> dict
self.idempotency = {}
self.meta_lock = threading.Lock()
def _nights(self, arrival: date, departure: date):
s = (arrival - self.base).days
e = (departure - self.base).days
if not (0 <= s < e <= self.D):
raise ValueError("date range out of bounds")
return s, e
def add_category(self, property_id, rt_id, count):
cats = self.properties.setdefault(property_id, {})
if rt_id not in cats:
cats[rt_id] = RoomCategory(rt_id, count, self.D)
else:
with cats[rt_id].lock:
cats[rt_id].total += count
for d in range(self.D):
cats[rt_id].available[d] += count
def search(self, property_id, arrival, departure, qty=1):
s, e = self._nights(arrival, departure)
results = []
for rt in self.properties.get(property_id, {}).values():
# Lock-free read; may be slightly stale — book() re-validates
m = min(rt.available[s:e])
if m >= qty:
results.append((rt.id, m))
return results
def reserve(self, user_id, property_id, rt_id,
arrival, departure, qty, idem_key):
s, e = self._nights(arrival, departure)
# Idempotency check (read path, fast)
with self.meta_lock:
if idem_key in self.idempotency:
return self.idempotency[idem_key]
rt = self.properties[property_id][rt_id]
with rt.lock: # atomic check + decrement
if min(rt.available[s:e]) < qty:
return None # no availability
for d in range(s, e):
rt.available[d] -= qty
bid = str(uuid.uuid4())
booking = dict(user=user_id, property=property_id, rt=rt_id,
s=s, e=e, qty=qty, status="CONFIRMED")
with self.meta_lock:
self.bookings[bid] = booking
self.idempotency[idem_key] = bid
return bid
def cancel(self, booking_id):
with self.meta_lock:
b = self.bookings.get(booking_id)
if b is None or b["status"] == "CANCELLED":
return False # not found or already cancelled
b["status"] = "CANCELLED" # mark first to prevent double-cancel
rt = self.properties[b["property"]][b["rt"]]
with rt.lock:
for d in range(b["s"], b["e"]):
rt.available[d] += b["qty"]
return True
7. Common Mistakes to Avoid
- Checking availability outside the lock and then decrementing inside it — the gap between the two is a race condition.
- Restoring inventory on cancel without checking current status — a double-cancel would add rooms that were never removed.
- Acquiring multiple locks in arbitrary order — always sort by a stable key to prevent deadlock.
- Treating check-out day as occupied — using a closed interval
[arrival, departure]instead of half-open[arrival, departure)will incorrectly block same-day turnover bookings.