Concurrent Ticket Booking System
HardConcurrencyMutexOptimistic LockingCASRace ConditionPessimistic Locking
Problem Statement
Design a concurrent ticket booking system for a cinema/concert/flight that prevents double-booking when multiple users try to book the same seat simultaneously. The system must handle high concurrency while ensuring:
- A seat can only be booked by one user.
- Booking is transactional (reserve + confirm is atomic).
- Temporary holds expire if not confirmed within a timeout.
class TicketBookingSystem {
public TicketBookingSystem(int totalSeats) {}
// Returns seat number if successfully reserved, -1 if no seats available
public int reserveSeat(String userId) {}
// Confirm the reserved seat; returns false if hold expired
public boolean confirmBooking(String userId, int seatNumber) {}
// Release a seat back to available pool
public void cancelBooking(String userId, int seatNumber) {}
public List<Integer> getAvailableSeats() {}
public int availableSeatCount() {}
}
Key Entities
- Seat state machine: AVAILABLE → RESERVED → BOOKED → AVAILABLE (on cancel).
- ConcurrentHashMap<Integer, SeatState>: Seat status with atomic CAS transitions.
- ReservationRegistry: Maps userId → (seatNumber, reservationExpiry).
- ScheduledExecutorService: Background task to expire timed-out holds.
Requirements
- Two users booking the same seat concurrently must result in exactly one success.
- Seat reservation holds expire after a configurable timeout (e.g., 10 minutes).
- Expired holds automatically release seats back to available pool.
- Support idempotent cancel operations.
availableSeatCount()must return accurate real-time count.
Asked at: BookMyShow, Amazon, Paytm, Flipkart, Uber, Swiggy, MakeMyTrip, IRCTC
!Constraints
- 1 ≤ totalSeats ≤ 100,000
- Concurrent bookings from up to 10,000 simultaneous users.
- Hold expiry timeout: 1 second to 30 minutes (configurable).
- A user can only hold one reservation at a time.
- System must handle thundering-herd scenarios (many users competing for last seat).
Output
Run or submit your code to see output here.