Design a Seat-Booking System like BookMyShow
Author: System Design Expert | Date: 2026-08-28 Domain: High-Concurrency Seat Reservation & Booking Platform
Table of Contents
- Requirements Clarification
- Back-of-Envelope Calculations
- System Interface Design
- High-Level Architecture
- Core Component Design
- Data Model
- Key Design Decisions
- Concurrency Control
- Scalability Strategy
- Curveball Scenarios
- Failure Modes and Mitigations
1. Requirements Clarification
1.1 Functional Requirements
| ID | Requirement | Priority |
|---|---|---|
| FR-01 | Users can browse movies, shows, events by city, date, genre, popularity | Must |
| FR-02 | Users can view venue details with interactive seat maps (color-coded: available/booked/selected) | Must |
| FR-03 | Users can select one or more seats and reserve them for a limited time window (e.g., 10 minutes) | Must |
| FR-04 | Reserved seats are locked for other users during the reservation window | Must |
| FR-05 | Users can proceed to payment after seat reservation | Must |
| FR-06 | On successful payment, booking is confirmed and ticket is generated | Must |
| FR-07 | On payment failure or timeout, reserved seats are released back to inventory | Must |
| FR-08 | Users can view booking history, download e-tickets, and check-in via QR code | Must |
| FR-09 | Users can cancel bookings and request refunds (subject to policy) | Should |
| FR-10 | Venue operators can manage shows, seat layouts, pricing, and availability | Must |
| FR-11 | Admin can manage users, venues, content moderation, and analytics | Should |
| FR-12 | Real-time seat availability updates across all clients viewing the same show | Must |
| FR-13 | Support for multiple pricing tiers (premium, standard, discount, dynamic pricing) | Should |
| FR-14 | Group booking support (selecting adjacent seats) | Could |
| FR-15 | Waitlist functionality when a show is sold out | Could |
1.2 Non-Functional Requirements
| ID | Requirement | Target |
|---|---|---|
| NFR-01 | Availability | 99.95% uptime (21.6 min downtime/month max) |
| NFR-02 | Latency - Browse | < 200ms p95 for movie/show listing |
| NFR-03 | Latency - Seat Map | < 500ms p95 for seat map load |
| NFR-04 | Latency - Reservation | < 1s p95 for seat reservation |
| NFR-05 | Throughput | Support 50,000+ concurrent users during peak (blockbuster release) |
| NFR-06 | Consistency | Strong consistency for seat inventory (zero overbooking) |
| NFR-07 | Durability | Zero data loss for confirmed bookings |
| NFR-08 | Scalability | Horizontal scaling for all stateless services |
| NFR-09 | Security | PCI-DSS compliance for payment, GDPR for user data |
| NFR-10 | Idempotency | All booking operations must be idempotent |
2. Back-of-Envelope Calculations
2.1 Assumptions and Scale Estimates
We consider three assumption sets to cover different scales:
| Parameter | Conservative (Regional) | Target (India-scale) | Aggressive (Global) |
|---|---|---|---|
| Registered Users | 10M | 100M | 500M |
| Daily Active Users (DAU) | 500K | 5M | 25M |
| Peak Concurrent Users | 50K | 500K | 2M |
| Shows per day | 5,000 | 50,000 | 200,000 |
| Bookings per day | 100K | 1M | 5M |
| Avg seats per booking | 2 | 2.5 | 2 |
| Seats booked per day | 200K | 2.5M | 10M |
| Avg venues | 500 | 5,000 | 20,000 |
| Avg seats per venue | 200 | 250 | 300 |
2.2 Storage Estimates
Movies/Shows Catalog
Movies: 10,000 titles x 5 KB metadata = 50 MB
Showings: 50,000/day x 1 KB x 365 days = 18.25 GB/year
Seat Inventory (Hot Data)
Active showings at any time: ~50,000
Seats per showing: 250 avg
Total active seat records: 50,000 x 250 = 12.5M rows
Per seat record: ~200 bytes (show_id, seat_id, status, price, lock_info)
Hot seat inventory: 12.5M x 200B = ~2.5 GB (fits in memory)
Booking History
Bookings: 1M/day x 1 KB x 365 = 365 GB/year
With 7-year retention: ~2.5 TB
User Data
Users: 100M x 2 KB = 200 GB
Seat Maps (Images/JSON)
Venue seat layouts: 5,000 venues x 50 KB = 250 MB
Total Storage (Year 1)
Catalog: ~20 GB
Seat Inventory (hot): ~2.5 GB (in-memory)
Booking History: ~365 GB
User Data: ~200 GB
Media/Assets: ~500 GB
Logs/Metrics: ~1 TB
Total: ~1.6 TB
2.3 Bandwidth Estimates
Inbound (reads):
- Movie listing page: 50 KB x 5M DAU x 3 views/day = 750 GB/day
- Seat map loads: 100 KB x 1M seat-map views/day = 100 GB/day
- Total inbound: ~1 TB/day
Outbound (writes):
- Seat reservations: 1 KB x 2M reservations/day = 2 GB/day
- Booking confirmations: 5 KB x 1M bookings/day = 5 GB/day
- Total outbound: ~7 GB/day
Peak bandwidth (during blockbuster release):
- 500K concurrent users x 100 KB/s = 50 Gbps peak read
- Write burst: 10K reservations/sec x 1 KB = 10 Mbps
2.4 QPS Estimates
| Operation | Avg QPS | Peak QPS | Notes |
|---|---|---|---|
| Browse movies/shows | 500 | 5,000 | Read-heavy, cacheable |
| View seat map | 100 | 2,000 | Read-heavy, partially cacheable |
| Reserve seats | 10 | 5,000 | Write-heavy, bursty (show start) |
| Payment processing | 5 | 2,000 | External dependency |
| Booking confirmation | 5 | 2,000 | Write to DB |
| Cancel/refund | 1 | 100 | Low volume |
| QR validation | 10 | 500 | At venue gates |
Critical insight: The reserve QPS can be 500x the average. This is the defining challenge of booking systems.
3. System Interface Design
3.1 API Definitions
Catalog Service
GET /api/v1/movies # List movies (paginated, filterable)
GET /api/v1/movies/{movie_id} # Movie details
GET /api/v1/shows # List shows (city, date, movie filters)
GET /api/v1/shows/{show_id} # Show details
GET /api/v1/venues/{venue_id} # Venue details
GET /api/v1/venues/{venue_id}/seat-layout # Venue seat layout (geometry only)
Seat & Reservation Service
GET /api/v1/shows/{show_id}/seats # Seat availability map
POST /api/v1/reservations # Reserve seats
PUT /api/v1/reservations/{reservation_id} # Extend reservation time
DELETE /api/v1/reservations/{reservation_id} # Cancel reservation
GET /api/v1/reservations/{reservation_id} # Check reservation status
Booking Service
POST /api/v1/bookings # Create booking from reservation
GET /api/v1/bookings/{booking_id} # Booking details
GET /api/v1/users/{user_id}/bookings # User booking history
POST /api/v1/bookings/{booking_id}/cancel # Cancel booking
POST /api/v1/bookings/{booking_id}/refund # Request refund
GET /api/v1/bookings/{booking_id}/ticket # Generate e-ticket
Payment Service
POST /api/v1/payments/initiate # Initiate payment
POST /api/v1/payments/{payment_id}/confirm # Confirm payment received
POST /api/v1/payments/{payment_id}/refund # Process refund
GET /api/v1/payments/{payment_id}/status # Payment status
Key Request/Response Examples
Reserve Seats:
POST /api/v1/reservations
Headers:
X-Idempotency-Key: uuid-v4-unique-per-attempt
Authorization: Bearer <jwt>
{
"show_id": "show_12345",
"seat_ids": ["A12", "A13", "A14"],
"reservation_duration_sec": 600
}
Response 201:
{
"reservation_id": "res_abc123",
"expires_at": "2026-08-28T10:15:00Z",
"total_amount": 750.00,
"currency": "INR",
"payment_url": "/api/v1/payments/initiate?reservation_id=res_abc123"
}
Create Booking:
POST /api/v1/bookings
Headers:
X-Idempotency-Key: uuid-v4-unique-per-attempt
Authorization: Bearer <jwt>
{
"reservation_id": "res_abc123",
"payment_id": "pay_xyz789",
"payment_status": "SUCCESS"
}
Response 201:
{
"booking_id": "book_def456",
"status": "CONFIRMED",
"ticket_url": "/api/v1/bookings/book_def456/ticket",
"qr_code": "data:image/png;base64,..."
}
4. High-Level Architecture
graph TB
subgraph Client["Client Layer"]
Web[Web App]
Mobile[Mobile App]
Admin[Admin Portal]
end
subgraph Edge["Edge / CDN Layer"]
CDN[CDN<br/>(Static Assets)]
WAF[WAF / DDoS Protection]
LB[Global Load Balancer<br/>Anycast DNS]
end
subgraph APIGateway["API Gateway Layer"]
GW[API Gateway<br/>(Kong / APISIX)]
Auth[Auth Service<br/>(JWT Validation)]
RateLimiter[Rate Limiter<br/>(Token Bucket)]
end
subgraph Services["Microservices"]
subgraph Catalog["Catalog Domain"]
MovieSvc[Movie Service]
ShowSvc[Show Service]
VenueSvc[Venue Service]
end
subgraph Booking["Booking Domain"]
SeatSvc[Seat Service]
ReservationSvc[Reservation Service]
BookingSvc[Booking Service]
end
subgraph Payment["Payment Domain"]
PaySvc[Payment Service]
RefundSvc[Refund Service]
end
subgraph Support["Support Services"]
NotifySvc[Notification Service]
TicketSvc[Ticket Service]
AnalyticsSvc[Analytics Service]
end
end
subgraph DataLayer["Data Layer"]
subgraph Cache["Cache Layer"]
RedisCluster[Redis Cluster<br/>(Seat Locks + Cache)]
end
subgraph Databases["Databases"]
MySQL[MySQL Cluster<br/>(Bookings, Users)]
MongoDB[MongoDB<br/>(Seat Layouts)]
Cassandra[Cassandra<br/>(Audit Logs)]
end
subgraph Messaging["Messaging"]
Kafka[Kafka Cluster<br/>(Event Streaming)]
end
end
subgraph External["External Services"]
PayGateway[Payment Gateway<br/>(Razorpay / Stripe)]
SMS[SMS Gateway]
Email[Email Service]
end
Web --> CDN
Mobile --> CDN
Web --> WAF
Mobile --> WAF
Admin --> WAF
WAF --> LB
LB --> GW
GW --> Auth
Auth --> RateLimiter
RateLimiter --> MovieSvc
RateLimiter --> ShowSvc
RateLimiter --> VenueSvc
RateLimiter --> SeatSvc
RateLimiter --> ReservationSvc
RateLimiter --> BookingSvc
RateLimiter --> PaySvc
MovieSvc --> RedisCluster
ShowSvc --> RedisCluster
VenueSvc --> MongoDB
SeatSvc --> RedisCluster
SeatSvc --> Kafka
ReservationSvc --> RedisCluster
ReservationSvc --> Kafka
BookingSvc --> MySQL
BookingSvc --> Kafka
PaySvc --> PayGateway
PaySvc --> Kafka
RefundSvc --> PayGateway
Kafka --> NotifySvc
Kafka --> TicketSvc
Kafka --> AnalyticsSvc
Kafka --> Cassandra
NotifySvc --> SMS
NotifySvc --> Email
5. Core Component Design
5.1 Seat Service (The Critical Component)
This is the heart of the system. It manages real-time seat availability and locking.
Architecture
graph LR
subgraph SeatService["Seat Service"]
InMemory[In-Memory Seat Grid<br/>(Per Showing)]
LockMgr[Lock Manager<br/>(Redis Redlock)]
StateMgr[State Manager<br/>(Status Transitions)]
end
Client[Client] --> SeatService
SeatService --> Redis[(Redis Cluster)]
SeatService --> Kafka[(Kafka)]
Seat States and Transitions
stateDiagram-v2
[*] --> AVAILABLE
AVAILABLE --> RESERVED: User selects seats
RESERVED --> BOOKED: Payment confirmed
RESERVED --> AVAILABLE: Timeout / Cancel
BOOKED --> CANCELLED: User cancels
BOOKED --> REFUNDED: Refund processed
CANCELLED --> AVAILABLE: After cooldown
REFUNDED --> AVAILABLE: After cooldown
AVAILABLE --> BLOCKED: Maintenance / Issue
BLOCKED --> AVAILABLE: Resolved
In-Memory Seat Grid Design
Each active showing maintains an in-memory representation:
SeatGrid {
showing_id: String
seats: Map<SeatId, SeatState>
version: Long // For optimistic concurrency
last_updated: Timestamp
}
SeatState {
seat_id: String // e.g., "A12"
status: Enum // AVAILABLE, RESERVED, BOOKED, BLOCKED
price: Decimal
reserved_by: UserId? // Who reserved it
reserved_at: Timestamp?
expires_at: Timestamp?
booking_id: String? // If confirmed
}
Why In-Memory + Redis?
| Approach | Pros | Cons | Verdict |
|---|---|---|---|
| DB-only row locking | Simple, ACID | Too slow at scale, connection exhaustion | Reject |
| Redis only | Fast, atomic ops | Risk of data loss on crash | Partial (with persistence) |
| In-memory + Redis lock | Fastest reads, distributed lock | Complex, needs reconciliation | Selected |
| ZooKeeper locks | Strong consistency | Higher latency, operational complexity | Reject |
5.2 Reservation Service
Manages the reservation lifecycle with timeout handling.
Reservation Flow
sequenceDiagram
participant U as User
participant API as API Gateway
participant R as Reservation Service
participant Redis as Redis (Lock + TTL)
participant K as Kafka
participant T as Timer Service
U->>API: POST /reservations (seat_ids)
API->>R: Reserve seats
R->>Redis: MULTI; SETNX each seat; EXEC
alt All seats locked
Redis-->>R: OK (all acquired)
R->>Redis: SET seat:lock:user = userId EX 600
R->>Redis: SET reservation:res_id EX 600
R->>K: Emit SEAT_RESERVED event
R-->>U: 201 reservation_id, expires_at
Note over R,T: Timer monitors expiry
T->>Redis: Check TTL expiration
alt Payment not received
T->>R: Reservation expired
R->>Redis: Release seat locks
R->>K: Emit SEAT_RELEASED event
end
else Conflict detected
Redis-->>R: Partial failure
R->>K: Emit RESERVATION_FAILED event
R-->>U: 409 Conflict (some seats taken)
end
Timeout Handling Strategy
1. Redis TTL on reservation key (hard expiry)
2. Background Timer Service scans for expiring reservations
3. On expiry:
a. Release seat locks atomically
b. Emit SEAT_RELEASED event to Kafka
c. Notify user via WebSocket/push
4. Grace period: 30 seconds before hard release (allows payment retry)
5.3 Booking Service
Handles the transition from reservation to confirmed booking.
Booking Creation Flow
sequenceDiagram
participant U as User
participant B as Booking Service
participant P as Payment Service
participant PG as Payment Gateway
participant DB as MySQL
participant K as Kafka
participant N as Notification Service
U->>B: POST /bookings (reservation_id, payment_id)
B->>P: Verify payment status
P->>PG: Check payment
PG-->>P: SUCCESS
P-->>B: Payment confirmed
B->>DB: BEGIN TRANSACTION
B->>DB: INSERT booking (status=CONFIRMED)
B->>DB: UPDATE seats SET status=BOOKED
B->>DB: COMMIT
B->>K: Emit BOOKING_CONFIRMED
K->>N: Send confirmation SMS/Email
B-->>U: 201 booking_id, ticket_url
5.4 Payment Service
Payment Integration Pattern
graph TB
subgraph PaymentService["Payment Service"]
PayMgr[Payment Manager]
PayState[Payment State Machine]
RetryMgr[Retry Manager]
WebhookHandler[Webhook Handler]
end
subgraph Gateways["Payment Gateways"]
PG1[Razorpay]
PG2[Stripe]
PG3[PayPal]
PG4[Net Banking]
end
PayMgr --> PG1
PayMgr --> PG2
PayMgr --> PG3
PayMgr --> PG4
PG1 -.webhook.-> WebhookHandler
PG2 -.webhook.-> WebhookHandler
PG3 -.webhook.-> WebhookHandler
PG4 -.webhook.-> WebhookHandler
WebhookHandler --> PayState
PayState --> RetryMgr
Payment States
stateDiagram-v2
[*] --> INITIATED
INITIATED --> PROCESSING: Gateway accepted
PROCESSING --> SUCCESS: Payment confirmed
PROCESSING --> FAILED: Gateway declined
PROCESSING --> TIMEOUT: No response
SUCCESS --> [*]
FAILED --> RETRY: Auto-retry (max 3)
RETRY --> SUCCESS
RETRY --> FAILED
TIMEOUT --> REFUNDED: Auto-refund
FAILED --> [*]
REFUNDED --> [*]
5.5 Notification Service
Multi-channel notifications for booking lifecycle events.
Events -> Kafka Topics -> Notification Workers -> Channels
Topics:
- booking.confirmed -> SMS, Email, Push
- booking.cancelled -> SMS, Email
- reservation.expiring -> Push, In-app (2 min warning)
- reservation.expired -> Push, In-app
- payment.failed -> SMS, Email
- refund.processed -> SMS, Email
6. Data Model
6.1 Relational Schema (MySQL)
-- Users
CREATE TABLE users (
user_id BIGINT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) UNIQUE NOT NULL,
phone VARCHAR(20) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
status ENUM('ACTIVE', 'SUSPENDED', 'DELETED') DEFAULT 'ACTIVE',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_phone (phone),
INDEX idx_email (email)
) ENGINE=InnoDB;
-- Venues
CREATE TABLE venues (
venue_id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
city VARCHAR(100) NOT NULL,
address TEXT,
latitude DECIMAL(10, 8),
longitude DECIMAL(11, 8),
total_seats INT NOT NULL,
operator_id BIGINT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_city (city),
INDEX idx_location (latitude, longitude)
) ENGINE=InnoDB;
-- Movies / Events
CREATE TABLE movies (
movie_id BIGINT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
description TEXT,
genre VARCHAR(100),
duration_min INT NOT NULL,
rating DECIMAL(3, 1),
poster_url VARCHAR(500),
language VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_genre (genre),
INDEX idx_title (title)
) ENGINE=InnoDB;
-- Shows (a specific screening of a movie at a venue)
CREATE TABLE shows (
show_id BIGINT PRIMARY KEY AUTO_INCREMENT,
movie_id BIGINT NOT NULL,
venue_id BIGINT NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL,
status ENUM('UPCOMING', 'LIVE', 'COMPLETED', 'CANCELLED') DEFAULT 'UPCOMING',
total_seats INT NOT NULL,
booked_seats INT DEFAULT 0,
base_price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (movie_id) REFERENCES movies(movie_id),
FOREIGN KEY (venue_id) REFERENCES venues(venue_id),
INDEX idx_venue_time (venue_id, start_time),
INDEX idx_movie_time (movie_id, start_time),
INDEX idx_city_time (venue_id, start_time),
INDEX idx_status_time (status, start_time)
) ENGINE=InnoDB;
-- Reservations
CREATE TABLE reservations (
reservation_id VARCHAR(64) PRIMARY KEY,
user_id BIGINT NOT NULL,
show_id BIGINT NOT NULL,
seat_ids JSON NOT NULL, -- ["A12", "A13"]
total_amount DECIMAL(10, 2) NOT NULL,
status ENUM('ACTIVE', 'EXPIRED', 'CONVERTED', 'CANCELLED') DEFAULT 'ACTIVE',
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (show_id) REFERENCES shows(show_id),
INDEX idx_user (user_id, status),
INDEX idx_expires (expires_at, status),
INDEX idx_show (show_id, status)
) ENGINE=InnoDB;
-- Bookings
CREATE TABLE bookings (
booking_id VARCHAR(64) PRIMARY KEY,
reservation_id VARCHAR(64) NOT NULL,
user_id BIGINT NOT NULL,
show_id BIGINT NOT NULL,
seat_ids JSON NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
status ENUM('CONFIRMED', 'CANCELLED', 'REFUNDED', 'NO_SHOW') DEFAULT 'CONFIRMED',
qr_code VARCHAR(500),
check_in_status ENUM('PENDING', 'CHECKED_IN') DEFAULT 'PENDING',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (reservation_id) REFERENCES reservations(reservation_id),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (show_id) REFERENCES shows(show_id),
INDEX idx_user (user_id, status),
INDEX idx_show (show_id, status),
INDEX idx_booking_id (booking_id)
) ENGINE=InnoDB;
-- Payments
CREATE TABLE payments (
payment_id VARCHAR(64) PRIMARY KEY,
booking_id VARCHAR(64),
reservation_id VARCHAR(64) NOT NULL,
user_id BIGINT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
currency VARCHAR(3) DEFAULT 'INR',
gateway VARCHAR(50) NOT NULL,
gateway_ref VARCHAR(255),
status ENUM('INITIATED', 'PROCESSING', 'SUCCESS', 'FAILED', 'REFUNDED') DEFAULT 'INITIATED',
failure_reason VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id),
INDEX idx_booking (booking_id),
INDEX idx_reservation (reservation_id),
INDEX idx_status (status, created_at)
) ENGINE=InnoDB;
-- Audit Log (append-only)
CREATE TABLE booking_audit_log (
log_id BIGINT PRIMARY KEY AUTO_INCREMENT,
entity_type VARCHAR(50) NOT NULL, -- 'RESERVATION', 'BOOKING', 'PAYMENT'
entity_id VARCHAR(64) NOT NULL,
action VARCHAR(50) NOT NULL, -- 'CREATED', 'UPDATED', 'DELETED'
old_state JSON,
new_state JSON,
user_id BIGINT,
ip_address VARCHAR(45),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_entity (entity_type, entity_id),
INDEX idx_time (created_at)
) ENGINE=InnoDB;
6.2 Redis Data Structures
# Seat availability (per showing) - Hash
Key: seat:show:{show_id}
Field: {seat_id}
Value: JSON {
"status": "AVAILABLE|RESERVED|BOOKED|BLOCKED",
"price": 250.00,
"reserved_by": null,
"expires_at": null
}
# Seat lock (distributed lock)
Key: lock:seat:{show_id}:{seat_id}
Value: {user_id}
TTL: 600 seconds (10 min)
# Reservation
Key: reservation:{reservation_id}
Value: JSON {
"user_id": 12345,
"show_id": 67890,
"seat_ids": ["A12", "A13"],
"total_amount": 500.00,
"created_at": "2026-08-28T10:00:00Z"
}
TTL: 600 seconds
# Show-level lock (for bulk operations)
Key: lock:show:{show_id}
Value: {operation_id}
TTL: 30 seconds
# Rate limiting
Key: ratelimit:{user_id}:{endpoint}
Value: count
TTL: 60 seconds
# Seat map cache (entire showing)
Key: cache:seatmap:{show_id}:{version}
Value: Serialized seat grid
TTL: 30 seconds (invalidated on any seat state change)
6.3 Kafka Topics
Topic: seat.events
Partition key: show_id
Events: SEAT_RESERVED, SEAT_RELEASED, SEAT_BOOKED, SEAT_BLOCKED
Topic: booking.events
Partition key: booking_id
Events: BOOKING_CREATED, BOOKING_CONFIRMED, BOOKING_CANCELLED
Topic: payment.events
Partition key: payment_id
Events: PAYMENT_INITIATED, PAYMENT_SUCCESS, PAYMENT_FAILED, PAYMENT_REFUNDED
Topic: notification.events
Partition key: user_id
Events: NOTIFICATION_SMS, NOTIFICATION_EMAIL, NOTIFICATION_PUSH
Topic: analytics.events
Partition key: event_type
Events: PAGE_VIEW, SEAT_VIEW, RESERVATION_ATTEMPT, BOOKING_COMPLETE
7. Key Design Decisions
7.1 Decision Matrix
| Decision | Option A | Option B | Chosen | Rationale |
|---|---|---|---|---|
| Seat state storage | RDBMS only | In-memory + Redis | In-memory + Redis | Sub-ms reads for seat map; Redis provides persistence and distributed access |
| Locking strategy | DB row-level locks | Redis distributed locks | Redis Redlock | DB locks cause connection exhaustion at 5K QPS; Redis handles 100K+ ops/sec |
| Reservation timeout | Client-side only | Server-side TTL | Server-side TTL (Redis) | Clients can be unreliable; server is source of truth |
| Booking confirmation | Synchronous | Eventual (async via Kafka) | Synchronous for user, async for side effects | User needs immediate confirmation; notifications/analytics can be async |
| Payment flow | Redirect to gateway | Embedded/SDK | Both (gateway-dependent) | Flexibility per region and gateway capability |
| Seat map delivery | Full JSON each time | Delta updates | Full JSON with cache + WebSocket deltas | Simple initial load; deltas for real-time updates during active browsing |
| Database sharding | Single sharded DB | Polyglot persistence | Polyglot | MySQL for bookings (ACID), Redis for seats (speed), MongoDB for layouts (flexible) |
| Idempotency | Client-side dedup | Server-side idempotency keys | Server-side idempotency keys | Network retries are inevitable; server must handle them safely |
7.2 Trade-off Analysis
Consistency vs. Availability (CAP Theorem)
For seat inventory: CP (Consistency + Partition Tolerance)
- We CANNOT afford overbooking
- If Redis partition occurs, reject reservations until resolved
- Browse operations can be AP (stale seat map is acceptable)
For booking confirmation: CP
- Must be durable and consistent
- Payment reconciliation runs async
For catalog/browse: AP
- Stale movie info is acceptable
- Cache-first with background refresh
Synchronous vs. Asynchronous Booking
Synchronous path (user-facing):
Reserve -> Pay -> Confirm (all within user session)
Latency budget: < 5 seconds total
Asynchronous path (backend):
Confirm -> Notify -> Analytics -> Audit (via Kafka)
No user-facing latency impact
8. Concurrency Control
This is the most critical section for a booking system.
8.1 The Core Problem
Scenario: 10,000 users try to book the last 2 seats simultaneously
Without proper concurrency control:
- All 10,000 see seats as AVAILABLE
- All 10,000 attempt to reserve
- Result: 10,000 reservations for 2 seats = OVERBOOKING
We must ensure: At most 1 reservation succeeds for any given seat
8.2 Multi-Layer Concurrency Strategy
graph TB
subgraph Layer1["Layer 1: Rate Limiting (Pre-filter)"]
RL[Token Bucket per User<br/>Max 5 reservation attempts/min]
end
subgraph Layer2["Layer 2: Redis Atomic Lock (Fast Path)"]
SETNX[SETNX seat:lock:{show}:{seat}<br/>Atomic, single round-trip]
end
subgraph Layer3["Layer 3: Optimistic Locking (DB)"]
OLock[UPDATE bookings SET version=version+1<br/>WHERE version=expected_version]
end
subgraph Layer4["Layer 4: Idempotency (Safety Net)"]
Idem[Idempotency Key Check<br/>Prevents duplicate processing]
end
Client[Client Request] --> RL --> SETNX --> OLock --> Idem --> Success[Booking Confirmed]
RL -->|Exceeded| Reject1[429 Too Many Requests]
SETNX -->|Locked| Reject2[409 Conflict]
OLock -->|Version mismatch| Retry[Retry with fresh state]
Idem -->|Duplicate| Existing[Return existing result]
8.3 Redis Distributed Lock Implementation
import redis
import time
import uuid
class SeatLockManager:
"""
Redis-based distributed lock for seat reservations.
Uses SETNX + TTL for automatic expiry.
"""
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def try_lock_seats(self, show_id: str, seat_ids: list, user_id: str,
ttl_seconds: int = 600) -> tuple[bool, list]:
"""
Atomically attempt to lock multiple seats.
Returns (success, locked_seat_ids).
Uses Redis MULTI/EXEC for atomicity.
"""
lock_keys = [f"lock:seat:{show_id}:{sid}" for sid in seat_ids]
lock_value = f"{user_id}:{uuid.uuid4()}:{int(time.time())}"
pipe = self.redis.pipeline(True) # MULTI
try:
for key in lock_keys:
pipe.set(key, lock_value, nx=True, ex=ttl_seconds)
results = pipe.exec()
# All SETNX must return True (key was created)
locked_seats = []
for i, result in enumerate(results):
if result: # SETNX succeeded
locked_seats.append(seat_ids[i])
else:
# This seat is already locked - release all we acquired
self._release_seats(lock_keys[:i], lock_value)
return False, []
return True, locked_seats
except redis.RedisError:
# On Redis error, release any acquired locks
self._release_seats(lock_keys, lock_value)
raise
def release_seats(self, show_id: str, seat_ids: list, user_id: str):
"""Release locks for specific seats owned by this user."""
lock_keys = [f"lock:seat:{show_id}:{sid}" for sid in seat_ids]
self._release_seats(lock_keys, user_id)
def _release_seats(self, lock_keys: list, owner_value: str):
"""Release locks only if we own them (prevent releasing others' locks)."""
pipe = self.redis.pipeline(True)
for key in lock_keys:
# Lua script for atomic check-and-delete
script = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
"""
pipe.eval(script, 1, key, owner_value)
pipe.exec()
8.4 Reservation Service Concurrency Flow
class ReservationService:
def create_reservation(self, user_id: str, show_id: str,
seat_ids: list, idempotency_key: str) -> Reservation:
"""
Create a seat reservation with full concurrency control.
"""
# Step 1: Idempotency check
existing = self.check_idempotency(idempotency_key)
if existing:
return existing
# Step 2: Try to lock all seats atomically
success, locked_seats = self.lock_manager.try_lock_seats(
show_id, seat_ids, user_id
)
if not success:
raise SeatConflictError(
f"Seats {set(seat_ids) - set(locked_seats)} are no longer available"
)
# Step 3: Update seat state in Redis
reservation_id = generate_uuid()
self.update_seat_states(show_id, seat_ids, user_id, reservation_id)
# Step 4: Persist reservation record
reservation = Reservation(
reservation_id=reservation_id,
user_id=user_id,
show_id=show_id,
seat_ids=seat_ids,
expires_at=datetime.utcnow() + timedelta(minutes=10)
)
self.repo.save(reservation)
# Step 5: Record idempotency key
self.record_idempotency(idempotency_key, reservation_id)
# Step 6: Emit event
self.event_bus.publish(SeatReservedEvent(reservation))
return reservation
8.5 Preventing Overbooking: The Invariant
INVARIANT: For any seat S in showing SH:
count(reservations where show_id = SH and S in seat_ids and status = ACTIVE)
+ count(bookings where show_id = SH and S in seat_ids and status = CONFIRMED)
<= 1
Enforcement layers:
1. Redis SETNX (fast, prevents concurrent acquisition)
2. DB unique constraint (show_id, seat_id, reservation_status='ACTIVE')
3. Application-level validation (final check before confirmation)
8.6 Handling the “Thundering Herd” at Show Start
Problem: At 12:00:00 when tickets go on sale, 100K+ users hit the API simultaneously.
Solutions:
1. Staggered release: Different users see different "go" times (±30 seconds)
2. Queue-based: Virtual waiting room with position number
3. Token bucket: Global rate limit on reservation endpoint
4. Pre-warming: Load all seat data into memory before sale starts
5. Read replicas: Seat map reads go to Redis replicas, writes to primary
9. Scalability Strategy
9.1 Horizontal Scaling Plan
graph TB
subgraph Tier1["Tier 1: Stateless Services (Scale Horizontally)"]
API1[API Gateway x N
Catalog x N
Notify x N
end
subgraph Tier2["Tier 2: Sharded State"]
Redis1[Redis Shard 1<br/>Shows 1-10000]
Redis2[Redis Shard 2<br/>Shows 10001-20000]
Redis3[Redis Shard 3<br/>Shows 20001-30000]
end
subgraph Tier3["Tier 3: Database Sharding"]
DB1[MySQL Shard 1<br/>Users A-M]
DB2[MySQL Shard 2<br/>Users N-Z]
end
subgraph Tier4["Tier 4: Event Streaming"]
Kafka1[Kafka Partition 0]
Kafka2[Kafka Partition 1]
Kafka3[Kafka Partition 2]
end
API1 --> Redis1
API1 --> Redis2
API1 --> Redis3
Redis1 --> DB1
Redis2 --> DB2
9.2 Scaling Dimensions
| Component | Scaling Strategy | Trigger | Max Scale |
|---|---|---|---|
| API Gateway | Add instances behind LB | CPU > 70% | Unlimited |
| Seat Service | 1 instance per Redis shard | Memory > 80% | # of shards |
| Redis Cluster | Add shards (consistent hashing) | Memory > 70% or ops/sec > 50K | 1000+ shards |
| MySQL | Read replicas + sharding by user_id | Connections > 80% | 100+ replicas |
| Kafka | Add partitions + brokers | Lag > 1000 messages | Unlimited partitions |
| Notification | Add worker instances | Queue depth > 10K | Unlimited |
9.3 Caching Strategy
Cache Hierarchy:
┌─────────────────────────────────────────────┐
│ L1: In-process cache (Caffeine/Guava) │ TTL: 5s, Size: 10K entries
│ Per service instance │
├─────────────────────────────────────────────┤
│ L2: Redis Cluster │ TTL: 30s, Size: 100M entries
│ Shared across instances │
├─────────────────────────────────────────────┤
│ L3: CDN (for static assets) │ TTL: 24h, Edge cached
│ Images, JS, CSS │
├─────────────────────────────────────────────┤
│ L4: Database (source of truth) │ No TTL
└─────────────────────────────────────────────┘
Cache Invalidation:
- Seat state change -> Invalidate L1 + L2 for that showing
- Show cancelled -> Invalidate all caches for that show
- Use cache versioning: cache:seatmap:{show_id}:{version}
9.4 Database Sharding Strategy
Sharding Key: user_id (for booking-related tables)
show_id (for seat-related data)
Why user_id for bookings?
- All queries for a user hit the same shard
- "My bookings" query is efficient
- User cancellation/refund stays local
Why show_id for seats?
- All seats for a showing are co-located
- Seat reservation is a single-shard operation
- No cross-shard transactions needed
10. Curveball Scenarios
Curveball 1: “What if 1 million users try to book at once?”
Scenario: A highly anticipated concert releases 10,000 tickets. 1 million users refresh the page at the exact same second.
Impact Analysis:
1M users / 60 seconds = 16,667 QPS on reservation endpoint
Each reservation attempt = Redis SETNX + DB write
Redis capacity: ~100K ops/sec (cluster)
DB capacity: ~5K writes/sec (single instance)
Result: System would collapse without mitigation
Mitigation Strategy:
| Layer | Strategy | Effect |
|---|---|---|
| Pre-sale | Virtual waiting room with queue position | Distributes load over time |
| Edge | Aggressive rate limiting (2 attempts/min per IP) | Reduces to ~8.3K QPS |
| Gateway | Request queuing with backpressure | Smooths burst to sustainable rate |
| Service | In-memory seat grid (no DB for reads) | Handles 50K+ read QPS |
| Redis | Cluster with 10+ shards | Handles 1M+ ops/sec |
| DB | Batch writes + async persistence | Sustains 20K+ writes/sec |
| Client | Staggered “go” signals (±60 sec jitter) | Spreads 1M users over 2+ minutes |
Virtual Waiting Room Design:
sequenceDiagram
participant U as User
participant VR as Virtual Waiting Room
participant Q as Queue Service
participant S as Seat Service
U->>VR: Request access (before sale)
VR->>Q: Join queue, get position
Q-->>VR: Position #45,231
VR-->>U: "You are #45,231 in line. ETA: ~3 min"
Note over Q: Queue processes 500 users/sec
Q->>VR: Your turn! Token valid for 2 min
VR-->>U: Access granted (JWT with 2min TTL)
U->>S: Browse and book seats (with token)
Expected Outcome:
- 1M users enter queue over 10 minutes
- 500 users/sec get access = 2 minutes to process all
- Each user gets 2 minutes to book
- System handles sustainable 500 QPS instead of 16K burst
Curveball 2: “What if we need refund processing?”
Scenario: A show is cancelled 2 hours before start. 50,000 bookings need automatic refunds. Additionally, individual users request refunds at any time.
Design:
graph TB
subgraph RefundSystem["Refund Processing System"]
Trigger[Refund Trigger]
Policy[Refund Policy Engine]
Batch[Batch Processor]
Individual[Individual Processor]
PG[Payment Gateway]
Ledger[Financial Ledger]
Notify[Notification Service]
end
Trigger -->|Show Cancelled| Policy
Trigger -->|User Request| Policy
Policy -->|Bulk| Batch
Policy -->|Single| Individual
Batch --> PG
Individual --> PG
PG --> Ledger
Ledger --> Notify
Refund Policy Engine:
Refund Eligibility Rules:
┌──────────────────────────┬────────────┬──────────────────┐
│ Condition │ Refund % │ Processing Time │
├──────────────────────────┼────────────┼──────────────────┤
│ Show cancelled (organizer)│ 100% │ Instant │
│ > 48 hours before show │ 100% │ 5-7 business days│
│ 24-48 hours before show │ 75% │ 5-7 business days│
│ 12-24 hours before show │ 50% │ 5-7 business days│
│ < 12 hours before show │ 0% │ Not eligible │
│ Payment failed │ N/A │ Auto-release │
└──────────────────────────┴────────────┴──────────────────┘
Batch Refund Processing:
class BatchRefundProcessor:
def process_show_cancellation(self, show_id: str, reason: str):
"""Process refunds for all bookings of a cancelled show."""
# Step 1: Lock the show to prevent new bookings
self.lock_show(show_id)
# Step 2: Find all active bookings
bookings = self.booking_repo.find_by_show(show_id, status='CONFIRMED')
# Step 3: Process in batches (avoid overwhelming payment gateway)
batch_size = 100
for batch in chunk(bookings, batch_size):
for booking in batch:
refund_amount = calculate_refund(booking, show_start_time)
self.process_refund(booking, refund_amount, reason)
time.sleep(1) # Rate limit to payment gateway
# Step 4: Release seats back to inventory
self.release_all_seats(show_id)
# Step 5: Notify all affected users
self.notify_all(bookings, "show_cancelled")
Key Considerations:
- Idempotency: Refund requests must be idempotent (gateway retries)
- Audit trail: Every refund step logged for financial reconciliation
- Partial refunds: Support split refunds (convenience fee non-refundable)
- Concurrency: Batch processor uses show-level lock to prevent race conditions
Curveball 3: “What if seats need to be held for X minutes?”
Scenario: Corporate clients want to hold 100+ seats for 30 minutes while they confirm attendee lists. VIP customers get 15-minute holds. Regular users get 10 minutes.
Design Extensions:
graph TB
subgraph HoldSystem["Seat Hold System"]
HoldPolicy[Hold Policy Engine]
HoldTimer[Hold Timer Service]
HoldExtender[Hold Extension API]
HoldExpiry[Hold Expiry Handler]
end
User[User] --> HoldPolicy
Admin[Admin] --> HoldPolicy
HoldPolicy --> HoldTimer
HoldTimer --> HoldExtender
HoldTimer --> HoldExpiry
HoldExpiry --> Release[Release Seats]
Hold Policy Configuration:
{
"hold_policies": {
"regular": {
"duration_minutes": 10,
"max_seats": 10,
"max_extensions": 1,
"extension_minutes": 5
},
"premium": {
"duration_minutes": 15,
"max_seats": 20,
"max_extensions": 2,
"extension_minutes": 5
},
"corporate": {
"duration_minutes": 30,
"max_seats": 100,
"max_extensions": 3,
"extension_minutes": 10,
"requires_approval": true
}
}
}
Implementation:
class HoldManager:
def create_hold(self, user_id: str, show_id: str,
seat_ids: list, hold_type: str) -> Hold:
policy = self.get_policy(hold_type)
# Validate against policy
if len(seat_ids) > policy.max_seats:
raise PolicyViolationError(
f"Max {policy.max_seats} seats allowed for {hold_type}"
)
# Apply hold with policy-specific TTL
ttl_seconds = policy.duration_minutes * 60
self.lock_seats(show_id, seat_ids, user_id, ttl_seconds)
hold = Hold(
user_id=user_id,
show_id=show_id,
seat_ids=seat_ids,
hold_type=hold_type,
expires_at=datetime.utcnow() + timedelta(seconds=ttl_seconds),
extensions_remaining=policy.max_extensions
)
self.repo.save(hold)
return hold
def extend_hold(self, hold_id: str) -> Hold:
hold = self.repo.find(hold_id)
if hold.extensions_remaining <= 0:
raise NoExtensionsLeftError()
if datetime.utcnow() > hold.expires_at:
raise HoldExpiredError()
policy = self.get_policy(hold.hold_type)
new_expiry = datetime.utcnow() + timedelta(
minutes=policy.extension_minutes
)
# Extend Redis lock TTL
self.extend_lock_ttl(hold.show_id, hold.seat_ids,
int((new_expiry - datetime.utcnow()).total_seconds()))
hold.expires_at = new_expiry
hold.extensions_remaining -= 1
self.repo.save(hold)
return hold
Fairness Consideration:
- Long holds reduce available inventory for other users
- Solution: “Hold pressure” metric - if > 30% of seats are on hold, reduce hold duration for new holds
- Corporate holds require pre-approval and may have a deposit requirement
Curveball 4: “What if the payment gateway goes down during peak?”
Scenario: During a blockbuster release, the primary payment gateway experiences an outage. 10,000 reservations are active with seats locked.
Mitigation:
graph TB
subgraph PaymentFailover["Payment Failover Strategy"]
Primary[Primary Gateway<br/>Razorpay]
Secondary[Secondary Gateway<br/>Stripe]
Tertiary[Tertiary Gateway<br/>PayPal]
Queue[Payment Queue]
Monitor[Health Monitor]
end
Monitor -->|Healthy| Primary
Monitor -->|Unhealthy| Secondary
Secondary -->|Unhealthy| Tertiary
Primary -->|Timeout| Queue
Secondary -->|Timeout| Queue
Tertiary -->|Timeout| Queue
Actions:
- Health checks: Every 5 seconds per gateway (circuit breaker pattern)
- Automatic failover: Switch to next healthy gateway in < 10 seconds
- Queue pending payments: If all gateways down, queue payments with extended hold
- Extend holds: Auto-extend reservation TTL while payment is queued
- Auto-refund: If payment cannot be processed within 30 minutes, release seats and notify
- Retry with backoff: Exponential backoff (1s, 2s, 4s, 8s) for transient failures
Curveball 5: “What if we detect bot activity scalping tickets?”
Scenario: Bots are buying up 80% of tickets for resale at premium prices.
Detection and Prevention:
| Signal | Detection Method | Action |
|---|---|---|
| High request rate | > 10 requests/min from same IP/user | Rate limit + CAPTCHA |
| Headless browser | User-agent analysis + JS challenge | Block + flag account |
| Known bot IPs | IP reputation database | Block at WAF level |
| Unusual patterns | ML model on booking patterns | Flag for review |
| Multiple accounts | Device fingerprinting | Link accounts, block all |
| Fast checkout | < 5 seconds from browse to book | Require verification |
Anti-Bot Measures:
1. Progressive CAPTCHA: Trigger after suspicious behavior
2. Device fingerprinting: Link accounts by device/browser
3. Purchase limits: Max 4 tickets per user per show
4. Verified purchase: Phone/email verification before booking
5. Random delays: Add 1-3 second random delay for suspicious requests
6. Honeypot seats: Fake seats that trigger bot detection when selected
11. Failure Modes and Mitigations
11.1 Failure Mode Analysis
| Failure Mode | Probability | Impact | Detection | Mitigation |
|---|---|---|---|---|
| Redis node failure | Medium | High | Health check timeout | Redis Cluster with replicas; automatic failover |
| MySQL primary failure | Low | Critical | Connection pool exhaustion | Read replicas promote to primary; MHA/Orchestrator |
| Payment gateway timeout | Medium | Medium | HTTP timeout / 5xx | Circuit breaker; failover gateway; queue + retry |
| Seat overbooking | Low (with safeguards) | Critical | Reconciliation job | Multi-layer locking; unique constraints; audit alerts |
| Reservation leak (lock not released) | Medium | Medium | Orphan lock detector | Redis TTL auto-expiry; background cleanup job |
| Kafka broker failure | Low | Medium | Consumer lag spike | Kafka replication (factor 3); automatic leader election |
| CDN cache poisoning | Low | High | Content hash mismatch | Cache signing; origin validation |
| DDoS attack | Medium | High | Traffic anomaly detection | WAF; rate limiting; CDN DDoS protection |
| Clock skew (TTL miscalculation) | Low | Medium | NTP drift detection | NTP sync; use server time only; add buffer to TTLs |
| Memory exhaustion (seat grid) | Low | High | Memory monitor | Evict inactive showings; shard by showing |
11.2 Disaster Recovery
RPO (Recovery Point Objective): 1 minute
- MySQL: Binary log replication (sync)
- Redis: AOF persistence (everysec)
- Kafka: Replication factor 3, acks=all
RTO (Recovery Time Objective): 5 minutes
- Automated failover for Redis and MySQL
- Runbook for manual intervention
- DR site in different availability zone
11.3 Monitoring and Alerting
Critical Metrics:
├── Seat Overbooking Count (ALERT if > 0)
├── Reservation Success Rate (ALERT if < 95%)
├── Payment Success Rate (ALERT if < 90%)
├── API Latency p99 (ALERT if > 2s)
├── Redis Memory Usage (ALERT if > 85%)
├── DB Connection Pool Usage (ALERT if > 80%)
├── Kafka Consumer Lag (ALERT if > 10K)
└── Error Rate by Endpoint (ALERT if > 5%)
Dashboards:
├── Real-time Booking Funnel (Browse -> Select -> Reserve -> Pay -> Confirm)
├── Seat Availability Heatmap (by showing)
├── Payment Gateway Health
└── System Resource Utilization
11.4 Reconciliation Jobs
Job: Seat Inventory Reconciliation
Frequency: Every 5 minutes
Logic:
1. For each active showing:
a. Count seats in Redis by status
b. Count bookings in MySQL by status
c. Verify: Redis(AVAILABLE) + Redis(RESERVED) + MySQL(BOOKED) = Total Seats
2. If mismatch:
a. Log discrepancy
b. Alert on-call engineer
c. Auto-correct if safe (e.g., release orphaned reservations)
Job: Payment Reconciliation
Frequency: Every 1 hour
Logic:
1. Fetch all payments from gateway for last hour
2. Compare with local payment records
3. Reconcile mismatches (missing callbacks, duplicate refunds)
Appendix A: Glossary
| Term | Definition |
|---|---|
| Showing | A specific screening of a movie/event at a venue and time |
| Seat Grid | In-memory representation of all seats for a showing |
| Reservation | Temporary hold on seats pending payment |
| Booking | Confirmed purchase of seats after successful payment |
| SETNX | Redis command: SET if Not eXists (atomic lock acquisition) |
| Redlock | Redis-based distributed lock algorithm for high availability |
| Idempotency Key | Client-generated unique identifier to prevent duplicate operations |
| Thundering Herd | Massive concurrent request burst at a specific time |
| Circuit Breaker | Pattern to prevent cascading failures to dependent services |
Appendix B: Technology Stack Recommendations
| Component | Recommended Technology | Alternatives |
|---|---|---|
| API Gateway | Kong / APISIX | AWS API Gateway, NGINX |
| Service Framework | Spring Boot / Go | Node.js, Rust |
| Cache / Lock | Redis Cluster | Memcached (no locks), Dragonfly |
| Primary DB | MySQL 8.0 | PostgreSQL |
| Document DB | MongoDB | DynamoDB |
| Message Queue | Apache Kafka | RabbitMQ, Pulsar |
| Search | Elasticsearch | OpenSearch |
| Container Orchestration | Kubernetes | ECS, Nomad |
| Monitoring | Prometheus + Grafana | Datadog, New Relic |
| Tracing | Jaeger / OpenTelemetry | Zipkin |
Appendix C: Estimated Infrastructure Costs (Monthly, Target Scale)
| Resource | Quantity | Monthly Cost (USD) |
|---|---|---|
| API Gateway instances | 10 | $2,000 |
| Application servers | 50 | $10,000 |
| Redis Cluster (10 shards + replicas) | 20 nodes | $8,000 |
| MySQL Primary + 10 replicas | 11 instances | $5,500 |
| Kafka Cluster (5 brokers) | 5 nodes | $3,000 |
| MongoDB Cluster (3 nodes) | 3 nodes | $1,500 |
| CDN | - | $5,000 |
| Load Balancers | 5 | $1,000 |
| Monitoring/Logging | - | $2,000 |
| Total | ~$38,000/month |
Document Version: 1.0 | Last Updated: 2026-08-28