Katkat

Design a Train Ticket Booking System

NielsenBackend Engineer · Technical Screen

Last updated

This problem evaluates your ability to design a robust reservation system that handles concurrent bookings, maintains data integrity, and adheres to clean object-oriented design principles.

Problem Statement

Design the backend for a train ticket booking system. The system should allow users to search for trains between two stations and book seats for a specific journey.

Requirements

  1. Search: Find available trains between a source and destination station for a given date.
  2. Reservation: Book a specific seat on a train.
  3. Concurrency: Ensure that two users cannot book the same seat simultaneously.
  4. Data Model: Define the core entities (Train, Station, Seat, Booking).

API Interfaces

Define the following operations:

  • search_trains(source: str, destination: str, date: date) -> List[Train]
  • book_seat(user_id: str, train_id: str, seat_number: str) -> bool

Constraints

  • Assume there are thousands of concurrent users during peak hours.
  • The system must ensure atomicity: if a seat is marked as 'booked', the user must be assigned the ticket successfully.

Examples

# Search
search_trains("NYC", "BOS", "2023-12-25") 
# Returns: [{"train_id": "T1", "departure": "10:00"}, ...]

# Booking
book_seat("user_123", "T1", "A5") 
# Returns: True if successful, False if seat is already taken

Key Considerations

  • How will you handle race conditions when two users try to book the same seat at the exact same millisecond?
  • What database isolation levels or locking mechanisms are appropriate here?

Hints

Hint 1

Consider using database-level constraints or optimistic locking (e.g., a version field) to prevent race conditions during seat assignment.

Hint 2

Think about the schema design to represent the relationship between trains, seats, and bookings efficiently.

Hint 3

Discuss whether you would use an RDBMS (like PostgreSQL) versus a NoSQL store, and justify your choice based on the need for ACID transactions.

Follow-up questions

  • How would you modify the design to support a 'waitlist' feature if a train is fully booked?
  • How would you implement a distributed lock if the reservation service is scaled across multiple microservices?
  • What strategies would you implement to handle 'ghost bookings' where a user holds a seat in their cart but doesn't complete the payment within 10 minutes?