Reservation Platform and High-Throughput Event Aggregation
System DesignModel answerLast updated
Build a seat reservation backend with strict consistency and a live vote counter handling millions of writes per second with eventual consistency.
Design two systems that handle different consistency and throughput requirements.
Problem 1: Seat Reservation Backend
Build a backend service for reserving seats on scheduled transportation. Users search available trips, view seating options, reserve specific seats, complete payment, and receive confirmation. The system must guarantee that no seat is sold twice, even under concurrent load.
Address these aspects:
- Schema design for core entities: scheduled trips, available seats, customer records, and confirmed reservations
- Database indexing strategy and rationale for each index
- Internal mechanics of tree-based indexes and how they influence query patterns
- Complete reservation workflow from search to confirmation, including the SQL operations at each step
- Concurrency control mechanisms to prevent duplicate seat assignments when multiple users attempt simultaneous bookings
Problem 2: Live Event Vote Aggregation
Design a system for a promotional campaign where users vote in real time during a major broadcast event. The system displays live results updated continuously as votes arrive.
Requirements:
- Handle burst traffic reaching several million votes per second during peak moments
- Voting requests should respond quickly to users
- Results dashboard reflects vote counts with minimal delay (1–2 second lag acceptable)
- System remains operational despite sudden traffic surges
Cover these elements:
- Service boundaries, API contracts, storage layers, and data pipeline
- Role of a distributed log or message queue for durability and buffering
- Approach to maintaining fast-updating counters and temporal aggregates
- Relevant internals of the streaming platform and time-series storage
- Container orchestration deployment including auto-scaling configuration
Hints
Hint 1
For reservations: think about what happens when two users click 'book' on the same seat at the same millisecond—your database operation must be atomic
Hint 2
For voting: recognize that writes vastly outnumber reads, and exact counts can lag by a second—this changes everything about your architecture
Hint 3
B-tree indexes are sorted; multi-column indexes only work left-to-right, so column order in a composite index directly determines which queries it can accelerate
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
These two problems test a fundamental trade-off in distributed systems: strict correctness versus massive throughput. Reservations demand zero conflicts on a small set of contested resources. Voting demands extreme write capacity, and slightly delayed results are acceptable.
Problem 1: Seat Reservation Backend
Scope and Scale Estimation
Functional requirements: search trips by route and date, display available seats with pricing, hold seats temporarily, process payment, issue confirmation, allow cancellations.
Non-functional targets: no double-booking under any circumstances, search latency p99 < 300ms, booking flow completes in under 2 seconds.
Expected load: approximately 100,000 trips daily, 10 million searches per day (~120 QPS average, peaking at 1,200 QPS), and 1 million bookings daily (~12 writes/second). Search traffic dominates by 100:1, making this a read-heavy system where write contention concentrates on popular routes.
API Design
GET /trips?origin=LAX&destination=BOS&date=2025-08-15&passengers=2
GET /trips/{trip_id}/seating
POST /reservations/hold {trip_id, seat_numbers[], passengers[]} → {hold_id, expires_at}
POST /reservations/confirm {hold_id, payment_info, dedup_key}
DELETE /reservations/{reservation_id}
Schema Design (PostgreSQL)
Trip table: (id, route_code, origin, destination, departure_time, arrival_time, vehicle_id, operational_status)
Seat table: (trip_id, seat_number, class, availability_status, hold_reference, hold_expiration, row_version) with composite primary key on (trip_id, seat_number)
Customer table: (id, full_name, birth_date, id_document, contact_email)
Reservation table: (id, customer_id, payment_status, total_amount, dedup_key UNIQUE, created_timestamp)
Ticket table: (id, reservation_id, customer_id, trip_id, seat_number, price) with a partial unique constraint: UNIQUE(trip_id, seat_number) WHERE active=true
This partial constraint is critical—it's the last line of defense. Even if application logic fails, the database physically prevents two active tickets for one seat.
Indexing Strategy
Trip(origin, destination, departure_time): composite index for search queries. Place equality predicates first, range predicates last—this follows the leftmost prefix rule.
Seat(trip_id, availability_status): accelerates "show me available seats" queries.
Ticket(reservation_id) and Reservation(customer_id, created_timestamp): power user history lookups.
Reservation(dedup_key) UNIQUE: prevents duplicate payment processing on retries.
Seat(hold_expiration) WHERE availability_status='HELD': allows a background job to efficiently find and release expired holds.
B-Tree Index Internals and Query Implications
B+trees organize sorted keys in pages (typically 8–16 KB). Interior nodes store separator keys and pointers to child pages. Leaf nodes contain actual keys with either row pointers or full row data (clustered indexes). Leaves are linked, enabling efficient range scans: one O(log N) tree descent followed by sequential leaf traversal.
With a fanout around 500, three levels accommodate hundreds of millions of rows.
Leftmost prefix matching: An index on (origin, destination, departure_time) accelerates queries filtering on all three columns, or just origin, or origin and destination. It cannot help a query filtering only destination. A range condition on an early column prevents using later columns in the index.
Covering indexes: Adding non-key columns via INCLUDE avoids fetching the full row from the heap.
Index-hostile patterns: Applying functions to indexed columns—like LOWER(origin)='lax'—defeats the index. Rewrite as a range or use a functional index.
Key generation: Random UUIDs as primary keys cause fragmentation and poor cache locality. Prefer time-ordered identifiers like ULIDs.
Complete Booking Flow
Step 1 - Search: Query hits read replicas or a cache layer (Redis/Elasticsearch) with a TTL of 2–3 minutes. Stale search results are acceptable.
Step 2 - Seat Map: Fetch current seat availability from the primary database or a frequently invalidated cache.
Step 3 - Hold Seats (10-minute reservation):
UPDATE seat
SET availability_status = 'HELD',
hold_reference = :hold_id,
hold_expiration = NOW() + INTERVAL '10 minutes'
WHERE trip_id = :trip_id
AND seat_number IN (:requested_seats)
AND (availability_status = 'AVAILABLE'
OR (availability_status = 'HELD' AND hold_expiration < NOW()));
-- Check rows_affected = len(requested_seats)
-- If not, rollback and return HTTP 409 Conflict
Step 4 - Payment: Call external payment processor with the deduplication key. Execute this outside any database transaction to avoid holding locks during network I/O.
Step 5 - Confirm Reservation (atomic transaction):
BEGIN;
UPDATE seat
SET availability_status = 'BOOKED'
WHERE hold_reference = :hold_id
AND hold_expiration > NOW();
INSERT INTO reservation (...);
INSERT INTO ticket (...);
COMMIT;
If the hold expired before confirmation, refund the payment asynchronously. Insert an outbox record to trigger confirmation email.
Step 6 - Cleanup: A periodic background job releases expired holds automatically.
Preventing Double-Booking
Primary mechanism - Conditional update: The UPDATE ... WHERE clause is an atomic compare-and-swap protected by a row-level lock. It fails fast without blocking other transactions.
Alternative - Pessimistic locking: SELECT ... FOR UPDATE also works but serializes all concurrent attempts. To prevent deadlocks, always lock seats in ascending seat_number order.
Inventory-based approach: For seatless booking (fare classes), use UPDATE inventory SET sold = sold + :count WHERE trip_id = :id AND sold + :count <= capacity.
Hot trips: High-demand routes can see thousands of simultaneous booking attempts. Mitigations:
- Place a Redis-based admission control (
DECRon remaining capacity) before database access - Implement per-trip queuing to serialize requests
- Shard by
trip_idto isolate hot-key contention
Defense in depth: Combine the unique constraint, idempotency keys, optimistic concurrency control, and payment capture only after confirmed hold.
Problem 2: Live Event Vote Aggregation
Requirements and Capacity Planning
Peak throughput: 3 million votes/second for 5-minute bursts = ~900 million total votes. At roughly 200 bytes per vote, that's 600 MB/s sustained write throughput.
Latency goals: Vote acknowledgment p99 < 50ms. Results dashboard lags by 1–2 seconds maximum.
Correctness model:
- Every accepted vote is eventually counted (at-least-once delivery with deduplication)
- Each user limited to one vote per window (or N votes, per business rules)
- Exact counts can lag by 1–2 seconds
Key insight: Only 5–10 voting options exist. These become extremely hot keys. Traditional database writes cannot scale.
API Contract
POST /v1/votes {campaign_id, option_id, user_id, timestamp, nonce} → 202 Accepted
GET /v1/results/{campaign_id} (point-in-time snapshot)
WebSocket /v1/results/{campaign_id}/live (server-push every ~1s)
Returning 202 Accepted means the vote is durably queued, not yet counted.
Architecture and Data Flow
Client → CDN/Global Load Balancer
→ Vote API (stateless pods, JWT auth, rate limiting per user)
→ Kafka topic "votes" (partitioned by user_id, ~300 partitions)
→ Stream processor (Flink/Kafka Streams): deduplication + 1-second tumbling windows
→ Redis (current totals) + TimescaleDB (second-by-second history) + S3 (raw archive)
Results Service reads from Redis, pushes updates via WebSocket; CDN caches GET /results with 1s TTL
Key Architectural Decisions
Asynchronous write path: The API validates the request and writes to Kafka, never touching a shared counter directly. This decouples ingestion from aggregation.
Avoiding hot keys in Kafka: Partitioning by user_id keeps each user's votes ordered within a partition, enabling stateful deduplication. Options are not partition keys—that would create extreme imbalance.
Pre-aggregation in the stream processor: Each Flink task maintains local state for its assigned partitions, emitting only (option, window) → count tuples. 3 million individual writes collapse into a few thousand aggregated updates per second.
Alternative - Redis counter sharding: If writing directly to Redis, shard each option's counter: votes:{option_id}:{shard_0..63} and sum on read. Use INCR for atomic updates.
Deduplication: Stream processor maintains a rolling window of seen (user_id, nonce) pairs using RocksDB state backend. Duplicates (retries, replay) are dropped.
Kafka Internals Relevant to This Design
Kafka organizes topics into partitions—append-only logs distributed across brokers. Producers write to the partition leader; replicas provide durability. Each message gets an offset (sequential per partition).
Consumer groups: Each Flink task claims a subset of partitions. Kafka tracks committed offsets per group. On failure, processing resumes from the last checkpoint.
Producer acknowledgment: acks=all waits for replica confirmation, trading ~10ms latency for guaranteed durability. This is essential—losing votes is unacceptable.
Compaction: Not used here (we need every vote), but log.cleanup.policy=compact keeps only the latest value per key, useful for changelog-style topics.
Exactly-once semantics: Kafka transactions plus Flink checkpointing achieve end-to-end exactly-once from ingestion to aggregation output.
Time-Series Database for Historical Results
TimescaleDB (Postgres extension) or InfluxDB stores (campaign_id, option_id, timestamp, vote_count) every second. This powers historical charts and post-event analysis.
Partitioning (TimescaleDB hypertables): Data automatically partitions by time (e.g., daily chunks). Old chunks compress or drop based on retention policy.
Continuous aggregates: Pre-computed rollups (per-minute, per-hour) speed up dashboard queries.
Write optimizations: Batch inserts, minimal indexing (time + option_id), and column-oriented storage for analytical queries.
Kubernetes Deployment and Auto-Scaling
Vote API: Stateless pods behind a service, horizontal pod autoscaler (HPA) targeting 70% CPU or custom metric (requests/second per pod). Start with 50 pods, scale to 500+ during peak.
Kafka: StatefulSet with persistent volumes for log segments. Brokers do not auto-scale during traffic—provision for peak capacity.
Flink/Stream Processor: Flink JobManager + TaskManager pods. Scale TaskManagers based on consumer lag metric: kafka.consumer.lag.max > 100000 triggers scale-out. Use cluster autoscaler to add nodes.
Redis: Redis Cluster with 6–12 shards, each running as a StatefulSet. Replica pods for read scaling.
Results Service: Stateless WebSocket handlers, HPA on connection count or CPU.
Pre-warming: Deploy full capacity 10 minutes before the event. Auto-scaling reacts too slowly for a 5-minute burst.
Traffic shaping: Global rate limiter (Envoy/API Gateway) enforces per-user limits (e.g., 5 votes/minute). This protects against abuse and runaway clients.
Common Mistakes to Avoid
Mistake 1: Writing every vote directly to a database counter. This creates a single hot row, serializing all writes. Throughput collapses.
Mistake 2: Using strong consistency where it's not needed. Vote counts can lag by a second—embracing eventual consistency unlocks massive scale.
Mistake 3: Partitioning Kafka by option_id. With only 5 options, 5 partitions cannot spread load. Partition by user_id instead.
Mistake 4: Ignoring deduplication. Network retries and Kafka replays produce duplicates. Without dedup, counts become inaccurate.
Mistake 5: Relying on auto-scaling alone during a 5-minute burst. Kubernetes takes 2–3 minutes to spin up pods. Pre-provision capacity.
Summary
Reservation systems require strict consistency on a small contested resource set—solved with atomic conditional updates and database constraints. Vote aggregation requires extreme write throughput where slight delays are acceptable—solved by decoupling ingestion (Kafka) from aggregation (stream processing) and embracing eventual consistency. Understanding when to enforce strong guarantees versus when to relax them is the core skill tested by these problems.