Building a Scalable Multi-Tenant Event Reservation Platform
System DesignModel answerLast updated
Design a backend system for managing event reservations across multiple venue types with pluggable business logic, concurrency safety, and transactional integrity.
You're building a reservation platform that handles bookings for various event categories—concerts, cinema screenings, sporting matches, and more. The system must support multiple operations: creating new events with capacity definitions, querying available inventory, temporarily reserving capacity with time-limited holds, completing purchases with payment idempotency, and processing refunds according to business rules.
Your design should demonstrate:
-
Extensibility: Show how the architecture accommodates new event categories and business rules without modifying core logic. Consider using appropriate design patterns for type registration and policy composition.
-
Concurrency safety: Explain how you prevent double-booking when thousands of users compete for limited capacity. Address both assigned seating and general admission scenarios.
-
Data modeling: Propose a persistence schema that supports your operations efficiently. Consider partitioning strategies for scale.
-
API contracts: Define the key endpoints (REST or gRPC), including request/response formats and error semantics.
-
Transactional guarantees: Describe how you handle partial failures, payment provider interactions, and idempotent operations.
-
Evolution strategy: How would you add new pricing algorithms (surge pricing, bundled discounts) or refund policies as the business grows?
Include complexity analysis for critical paths, testing approaches, and operational considerations for high-traffic scenarios.
Hints
Hint 1
Consider separating the concerns of inventory management, pricing calculation, and payment processing into distinct components with clear boundaries
Hint 2
Think about optimistic vs pessimistic concurrency control—which operations can tolerate occasional retries vs which need strict serialization?
Hint 3
Idempotency isn't just about duplicate detection; consider how you store and replay responses for retried requests
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Solution: Multi-Tenant Event Reservation Platform
1. Requirements Analysis and Scope
Functional Requirements
- Event management: Create events with venue layouts, capacity pools, and category-specific attributes
- Inventory queries: Users browse availability, filtered by section/category/price
- Reservation flow: Two-phase commit—temporary holds (10-minute TTL) followed by confirmed purchases
- Payment integration: Idempotent purchase operations that survive network retries
- Refund processing: Category-specific refund eligibility rules
Non-Functional Requirements
- Correctness over availability: Zero overbooking tolerance—strong consistency for capacity state
- Read-heavy workload: Inventory queries outnumber writes 100:1, can tolerate slight staleness
- Traffic spikes: Major events trigger thundering herds—50k simultaneous users competing for 10k seats
- Purchase latency: Hold operations target p99 < 200ms; purchase bounded by payment gateway (~1-2s)
Scale Estimation
- Active inventory: 100k events × 5k average capacity = 500M allocation records
- Storage: ~100 bytes per seat record = 50GB for seat state (fits single-region RDBMS with sharding)
- Transaction volume: 5M purchases/day, 1KB average = ~5GB daily order data
- Peak throughput: 20k hold requests/second during major on-sales
2. API Design
I'd use REST with clear semantic HTTP methods:
POST /v1/events
Body: {name, venue_id, starts_at, ticket_categories[]}
-> {event_id, ...}
GET /v1/events/{event_id}/availability?category=VIP§ion=A
-> {seats: [{id, section, quoted_price}], ga_remaining: 120}
POST /v1/holds
Body: {event_id, selections: [{seat_id} | {category, quantity}]}
-> {hold_id, items[], total_cents, expires_at}
DELETE /v1/holds/{hold_id}
POST /v1/purchases
Headers: Idempotency-Key: {uuid}
Body: {hold_id, payment_token}
-> {order_id, status: PENDING|CONFIRMED|FAILED}
GET /v1/orders/{order_id}
POST /v1/refunds
Headers: Idempotency-Key: {uuid}
Body: {order_id, ticket_ids[], reason}
-> {refund_id, status, eligible_amount_cents}
Error taxonomy:
409 CONFLICT: Requested capacity unavailable (someone else grabbed it)410 GONE: Hold expired before purchase attempt402 PAYMENT_REQUIRED: Payment provider declined422 UNPROCESSABLE: Refund not permitted under policy429 TOO_MANY_REQUESTS: Rate-limited (waiting room active)
3. Data Model
Core tables (Postgres with row-level sharding on event_id):
events: event_id, venue_id, category, starts_at, state
ticket_categories: (event_id, category_id), pricing_rules JSONB, refund_policy JSONB
seats: (event_id, seat_id) PK, category_id, state ENUM, hold_id, hold_expiry, version INT
ga_pools: (event_id, category_id) PK, total_capacity, reserved_count
holds: hold_id, user_id, event_id, quoted_items JSONB, expires_at, state
orders: order_id, user_id, hold_id UNIQUE, total_cents, currency, state
tickets: ticket_id, order_id, seat_id, category_id, paid_cents, state
idempotency_log: (user_id, idem_key) PK, request_digest, response_snapshot, created_at
Key design decisions:
- Money as integers: Store prices in minor units (cents) to avoid floating-point errors
- Frozen pricing: Quote stored in
holds.quoted_itemsis binding—dynamic prices can't change mid-checkout - Version column: Enables optimistic locking for seat updates
4. Extensible Architecture
Use three design patterns to achieve open/closed principle:
Pattern 1: Type Registry
from abc import ABC, abstractmethod
from typing import Dict, Type
class TicketCategory(ABC):
category_code: str
@abstractmethod
def allocation_model(self) -> str: # "ASSIGNED" or "POOLED"
pass
def __init__(self, config: dict, pricer: 'PricingEngine', refund_rules):
self.config = config
self.pricer = pricer
self.refund_rules = refund_rules
# Global registry
_CATEGORIES: Dict[str, Type[TicketCategory]] = {}
def register_category(code: str):
def decorator(cls):
cls.category_code = code
_CATEGORIES[code] = cls
return cls
return decorator
@register_category("CONCERT_GA")
class ConcertGeneralAdmission(TicketCategory):
def allocation_model(self): return "POOLED"
@register_category("SPORTS_SEAT")
class SportsReservedSeat(TicketCategory):
def allocation_model(self): return "ASSIGNED"
class CategoryFactory:
@staticmethod
def build(code: str, config: dict, pricer, refund_rules):
if code not in _CATEGORIES:
raise ValueError(f"Unrecognized category: {code}")
return _CATEGORIES[code](config, pricer, refund_rules)
Pattern 2: Composable Pricing Strategies
from dataclasses import dataclass
@dataclass
class PriceContext:
base_cents: int
demand_factor: float # 0.0 - 1.0 (fraction sold)
time_to_event_hours: float
user_segment: str
class PricingRule(ABC):
@abstractmethod
def apply(self, ctx: PriceContext, current_cents: int) -> int:
pass
class StaticPricing(PricingRule):
def apply(self, ctx, current):
return ctx.base_cents
class DemandMultiplier(PricingRule):
def __init__(self, max_factor: float):
self.max_factor = max_factor
def apply(self, ctx, current):
surge = 1.0 + (self.max_factor - 1.0) * ctx.demand_factor
return int(current * surge)
class ConvenienceFee(PricingRule):
def __init__(self, rate: float):
self.rate = rate
def apply(self, ctx, current):
return current + int(current * self.rate)
class PricingEngine:
def __init__(self, rules: list[PricingRule]):
self.rules = rules
def calculate(self, ctx: PriceContext) -> int:
amount = 0
for rule in self.rules:
amount = rule.apply(ctx, amount)
return amount
Configuration drives composition:
{
"pricing_rules": [
{"type": "static"},
{"type": "demand", "max_factor": 1.8},
{"type": "fee", "rate": 0.12}
]
}
Benefit: Adding "student discount" or "early-bird pricing" means writing one new PricingRule subclass and registering it. Existing categories are untouched.
5. Concurrency Control Deep Dive
Assigned Seating
Use atomic conditional updates with optimistic locking:
-- Reserve multiple seats atomically
UPDATE seats
SET state = 'HELD',
hold_id = $1,
hold_expiry = NOW() + INTERVAL '10 minutes',
version = version + 1
WHERE event_id = $2
AND seat_id = ANY($3)
AND (state = 'AVAILABLE' OR (state = 'HELD' AND hold_expiry < NOW()))
RETURNING seat_id;
Check returned row count equals requested count. If mismatch, rollback and return 409.
Alternative approach (pessimistic):
SELECT * FROM seats
WHERE event_id = $1 AND seat_id = ANY($2)
ORDER BY seat_id -- Critical: prevents deadlocks
FOR UPDATE SKIP LOCKED;
General Admission Pools
Simple counter decrement:
UPDATE ga_pools
SET reserved_count = reserved_count + $1
WHERE event_id = $2
AND category_id = $3
AND reserved_count + $1 <= total_capacity;
High-Contention Mitigation
Layer 1: Virtual waiting room
Token bucket admission control—issue signed JWTs at 5k/minute when queue detected.
Layer 2: Seat pool partitioning
Divide seats into 10 partitions, hash users to partition. Reduces contention 10×.
Layer 3: Write-through cache
Redis sorted set tracks available seats, synchronized via change-data-capture from Postgres. Read path hits cache; write path updates both.
6. Transactional Guarantees
Idempotency Implementation
def idempotent_purchase(user_id: str, idem_key: str, hold_id: str, payment_token: str):
# Check for replay
cached = db.query(
"SELECT response_snapshot FROM idempotency_log WHERE user_id=$1 AND idem_key=$2",
user_id, idem_key
)
if cached:
return json.loads(cached['response_snapshot'])
# Generate request fingerprint
digest = hash_request({'hold_id': hold_id, 'payment_token': payment_token})
with db.transaction():
# Lock hold
hold = db.query("SELECT * FROM holds WHERE hold_id=$1 FOR UPDATE", hold_id)
if hold['expires_at'] < now():
raise HoldExpiredError()
# Create order
order_id = uuid4()
db.execute("INSERT INTO orders (order_id, user_id, hold_id, total_cents, state) VALUES ...")
# Call payment provider (idempotent on their side via merchant reference)
payment_result = payment_gateway.charge(
amount=hold['total_cents'],
token=payment_token,
idempotency_key=f"order-{order_id}"
)
if payment_result.success:
db.execute("UPDATE seats SET state='SOLD' WHERE hold_id=$1", hold_id)
db.execute("UPDATE orders SET state='CONFIRMED' WHERE order_id=$1", order_id)
response = {'order_id': order_id, 'status': 'CONFIRMED'}
else:
response = {'error': 'PAYMENT_DECLINED', 'reason': payment_result.decline_code}
# Store idempotency record
db.execute(
"INSERT INTO idempotency_log (user_id, idem_key, request_digest, response_snapshot) VALUES ...",
user_id, idem_key, digest, json.dumps(response)
)
return response
Failure Modes
- Network timeout to payment gateway: Retry with same idempotency key; gateway deduplicates
- Database crash mid-transaction: Rollback releases hold; user retries
- Partial seat update: Use serializable isolation level or SELECT...FOR UPDATE to prevent
7. Testing Strategy
Unit tests: Mock pricing engines, verify rule composition produces expected amounts
Integration tests: Spin up test DB, simulate concurrent hold attempts, assert zero double-booking
Chaos tests: Kill DB connections mid-transaction, verify cleanup
Load tests: Generate 10k concurrent holds against 1k-seat event, measure p99 latency and error rate
8. Complexity Analysis
- Hold creation: O(n) where n = seat count; single UPDATE with row lock
- Inventory query: O(1) with covering index on (event_id, state, category)
- Purchase: O(1) transactional writes + payment gateway latency (1-2s)
Common Mistakes to Avoid
- Using SELECT then UPDATE: Creates race conditions. Use atomic conditional updates.
- Floating-point money: Always use integer cents.
- Recalculating prices at purchase: Quote must be binding from hold creation.
- Ignoring idempotency: Network retries will create duplicate charges.
- Over-engineering: Don't build distributed locks or saga orchestration unless you've proven single-DB transactions insufficient.
This architecture balances correctness, extensibility, and operational simplicity for a high-scale reservation system.