Concurrent Ticket Booking System

Hard
ConcurrencyMutexOptimistic 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:

  1. A seat can only be booked by one user.
  2. Booking is transactional (reserve + confirm is atomic).
  3. 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

  1. Two users booking the same seat concurrently must result in exactly one success.
  2. Seat reservation holds expire after a configurable timeout (e.g., 10 minutes).
  3. Expired holds automatically release seats back to available pool.
  4. Support idempotent cancel operations.
  5. 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.