Event Seat Reservation System with Timed Locks
System DesignModel answerLast updated
Design a high-traffic event ticketing platform with temporary seat reservations, automatic expiration, and zero overselling under concurrent access.
You are building a large-scale event reservation platform where users can browse concerts and sporting events, view seating maps, and reserve specific seats.
The platform must support:
- Event search and browsing with live seat availability
- Temporary seat reservations: when a user selects seats, they are locked for exactly 5 minutes
- Automatic lock release if payment is not completed within the time window
- Guaranteed prevention of double-booking (the same seat cannot be sold to two customers)
- Performance under extreme load: tens of thousands of users competing for inventory during popular on-sales
Design this system end-to-end. Address:
- Core use cases and API surface
- Architecture and main components
- Data model for events, inventory, reservations, and orders
- Reservation mechanism: how locks are acquired, enforced, and expired
- Concurrency control: techniques to prevent race conditions and overselling
- Consistency vs. availability tradeoffs, and how the system scales across multiple servers
Assume internet-scale deployment with distributed infrastructure.
Hints
Hint 1
Think about the difference between browsing (read-heavy, tolerates staleness) and booking (write-heavy, requires strong consistency).
Hint 2
Database row-level locks and conditional updates can enforce single-seat atomicity. How do you make multi-seat reservations all-or-nothing?
Hint 3
Consider both lazy expiration (check at access time) and active cleanup (background workers) for releasing timed locks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Requirements and Scale
Functional scope:
- Search events and view real-time seat maps
- Reserve specific seats with a 5-minute lock preventing others from taking them
- Complete payment: success creates tickets, timeout or cancellation frees the seats
- Zero tolerance for overselling — this is the invariant we cannot violate
Non-functional constraints:
- Browsing is read-dominated and can tolerate eventual consistency (a few seconds of staleness is acceptable)
- Reservations and purchases require strong consistency per seat
- The system must survive sudden traffic spikes
Rough numbers for a hot on-sale:
- A large venue has ~50,000 seats
- 1–2M users arrive at on-sale time, generating ~500k seat-map requests per second
- Reservation attempts peak at 5–20k/sec, concentrated on a single event
- Actual purchases are bounded by inventory: ~50k successful orders over 15 minutes
Key insight: The bottleneck is lock contention on one event's inventory, not overall data volume. The system is globally read-heavy, but writes are extremely concentrated.
API Design
GET /events?q=&city=&date= → event list
GET /events/{eventId} → event details, venue info
GET /events/{eventId}/seats → seat map + status (available/reserved/sold)
POST /events/{eventId}/reservations body: {seatIds[], idempotencyKey}
→ 201 {reservationId, expiresAt} | 409 {unavailableSeats[]}
DELETE /reservations/{reservationId} → manual early release
POST /reservations/{reservationId}/purchase body: {paymentToken, idempotencyKey}
→ 200 {orderId, tickets[]} | 410 expired | 402 payment declined
GET /orders/{orderId}
Reservations are atomic: a user gets all requested seats or none. Idempotency keys make retries safe.
Data Model
The source of truth for inventory is a strongly consistent relational store (Postgres, MySQL with synchronous replication, or Spanner/CockroachDB), sharded by event_id. This keeps all seats for an event on one shard, allowing single-shard transactions.
events(
event_id PK, venue_id, name,
start_time, sale_opens_at, status
)
venues(venue_id PK, name, city)
sections(venue_id, section_id, layout_json) -- static, heavily cached
inventory(
event_id, seat_id, -- PK (event_id, seat_id)
state ENUM(AVAILABLE, RESERVED, SOLD),
reservation_id NULL,
lock_expires_at TIMESTAMP NULL,
order_id NULL
)
reservations(
reservation_id PK, event_id, user_id,
seat_ids[],
state ENUM(ACTIVE, COMPLETED, EXPIRED, CANCELLED),
expires_at, created_at
)
orders(
order_id PK, user_id, event_id,
reservation_id UNIQUE,
total_amount,
state ENUM(PENDING, PAID, FAILED),
payment_reference,
idempotency_key UNIQUE
)
tickets(
ticket_id PK, order_id, event_id, seat_id,
UNIQUE(event_id, seat_id) -- last-line defense
)
The UNIQUE(event_id, seat_id) constraint on tickets is a failsafe. Even if application logic has a bug, the database refuses duplicate ticket issuance.
High-Level Architecture
Client
→ CDN (static venue layouts, images)
→ API Gateway (auth, rate limiting, bot detection)
→ Waiting Room Service (queue tokens for hot sales)
→ Event Service → Elasticsearch (search), Redis (event metadata)
→ Inventory Service → Sharded Inventory DB, Redis (availability bitmap)
→ Checkout Service → Payment Provider API, Orders DB
→ Expiration Workers (delayed task queue)
→ Event Bus (Kafka: seat state changes)
→ Cache Invalidator
→ WebSocket Push Service
→ Analytics
- Search: Elasticsearch, populated via change-data-capture (CDC) from the events table
- Seat maps: Static layouts from CDN; dynamic availability as a compressed bitmap per event in Redis, updated from Kafka events. Clients poll every few seconds or receive server-sent events (SSE). Stale "available" is fine because the reservation write is authoritative.
- Inventory Service is the sole writer to the
inventorytable.
Implementing the 5-Minute Lock
Acquiring a Reservation
Use a single atomic conditional update within a transaction:
BEGIN;
-- Try to claim all requested seats
UPDATE inventory
SET state = 'RESERVED',
reservation_id = :rid,
lock_expires_at = now() + interval '5 minutes'
WHERE event_id = :eid
AND seat_id = ANY(:seat_ids)
AND (state = 'AVAILABLE' OR (state = 'RESERVED' AND lock_expires_at < now()));
-- Check we got all seats
IF row_count != length(:seat_ids) THEN
ROLLBACK;
RETURN 409 conflict;
END IF;
INSERT INTO reservations(...);
COMMIT;
This is optimistic compare-and-set concurrency. Two users racing for the same seat both issue the update, but row-level locking ensures exactly one matches the predicate. To avoid deadlocks when reserving multiple seats, lock rows in a deterministic order (sorted seat_id).
Expiring Reservations
Two complementary mechanisms:
-
Lazy expiration (correctness): The predicate
lock_expires_at < now()treats an expired reservation as available when someone tries to claim the seat. Correctness never depends on a background job running on time. -
Active cleanup (freshness): A delay queue (Redis sorted set keyed by expiration timestamp, or SQS with message delays) triggers at
expires_at. A worker marks the reservationEXPIRED, resets seats toAVAILABLE(onlyWHERE reservation_id = :rid), and publishes a state-change event. Workers are idempotent; a periodic sweeper catches any missed expirations.
Critical: Use the database's clock (now()), not application server clocks, to avoid drift between servers.
Alternative worth mentioning: Holding the seat in Redis with SET seat:{e}:{s} resId NX PX 300000 gives free TTL expiration and is fast, but Redis failover can lose locks. If used, treat it only as a fast-path filter and keep the database conditional update and unique constraint as the authority. Interviewers appreciate hearing why cache TTL alone is insufficient.
Checkout Without Overselling
-
Validate reservation: Must be
ACTIVE, owned by the requesting user, and not expired. Extend the lock by transitioning toPAYMENT_PENDINGwithexpires_at += 2 minutes, so a payment initiated at 4:59 isn't released mid-charge. -
Create order: Insert an
ordersrow inPENDINGstate with an idempotency key. -
Call payment provider using the same idempotency key.
-
On payment success, execute atomically:
BEGIN; UPDATE inventory SET state = 'SOLD', order_id = :oid WHERE reservation_id = :rid AND state = 'RESERVED'; INSERT INTO tickets(...); UPDATE orders SET state = 'PAID' WHERE order_id = :oid; UPDATE reservations SET state = 'COMPLETED' WHERE reservation_id = :rid; COMMIT; -
Conflict handling: If step 4 finds the reservation gone (edge-case race), immediately refund. Never issue the ticket.
For payment failures and timeouts, a reconciliation job queries the payment provider for PENDING orders. This implements a saga pattern where compensation is refund or release.
Handling Traffic Surges
Virtual waiting room: Users receive signed queue tokens at on-sale time. Admission is metered to sustainable throughput (e.g., 5k concurrent users), preventing inventory service overload and providing fair access.
Caching layers:
- Redis: event metadata (1h TTL), seat availability bitmaps (real-time updates), session state
- CDN: static venue layouts, event images
Database optimization:
- Shard by
event_id: Each hot event gets its own shard, eliminating cross-shard contention - Read replicas: Browsing and search use replicas; primary handles only writes
- Connection pooling: Per-service instance pools prevent connection exhaustion
Rate limiting:
browse endpoints: 100 req/sec per IP
reservation: 10 req/sec per user
purchase: 5 req/sec per user
Exponential backoff on retries: base 100ms, max 5s, 3 attempts
Consistency vs. Availability Tradeoffs
Strong consistency (CP) for inventory writes:
- Use synchronous replication (Spanner, CockroachDB, or Postgres with synchronous standbys + Patroni auto-failover)
- Prefer rejecting writes over overselling during a partition
Eventual consistency (AP) for reads:
- Elasticsearch can lag by a few seconds
- Seat-map cache can be briefly stale
- CDC pipeline updates asynchronously
Failure modes:
- Database primary down: Auto-failover to synchronous replica (<30s). Waiting room pauses admission. Existing reservations remain valid.
- Redis down: Degrade to database reads. Activate standby Redis cluster. Seat maps may briefly not refresh.
- Payment timeout: Extend reservation lock. Async reconciliation job queries payment provider. Auto-retry or refund.
Scaling Strategy
Horizontal scaling:
- Stateless services (API gateway, event service, inventory service): linear scaling with load balancers and auto-scaling groups
- Stateful services: database sharded by
event_id, Redis clustered by event partition, Kafka partitioned byevent_idfor ordering
Geographic distribution:
- Reads: serve from nearest region (CDN + regional replicas)
- Writes: route to primary region, or use multi-primary with conflict resolution
- Inventory: single-primary for strong consistency
Key metrics:
SLIs:
- Reservation success rate >95% (excluding sold-out)
- Reservation latency P99 <500ms
- Purchase success rate >99% (excluding payment declines)
- Expiration processing delay <10s
Alerts:
- Same seat reserved twice (overselling risk)
- Expiration backlog >1000
- Database replication lag >5s
Key Takeaways for Interviews
Strengths to highlight:
- Clear separation of strong consistency (inventory) vs. eventual consistency (search)
- Multi-layer defense against overselling: conditional updates + unique constraints + idempotency
- Sharding by
event_idsolves hot-spot contention - Lazy + active expiration provides both correctness and freshness
Deep-dive topics:
- Why not distributed locks (Redlock)? Answer: Single-database transactions are simpler and more reliable for this use case
- Cross-region inventory sharing? Answer: Use Spanner's global transactions or sacrifice consistency for compensating actions
- Scalper prevention? Answer: CAPTCHAs, device fingerprinting, user reputation scoring, per-user purchase limits
Common pitfalls to avoid:
- Relying on application-level clock synchronization
- Using only cache TTL without database fallback
- Ignoring idempotency design
- Applying eventual consistency to inventory writes