Handling Concurrency and Preventing Duplicate Ticket Booking in Train Ticket Systems
The article examines how a train ticket ordering system can encounter duplicate bookings when multiple users concurrently request the same seat and evaluates four different locking strategies—including flag fields, pessimistic locks, synchronized blocks, and a hybrid optimistic‑pessimistic approach—to ensure data consistency and avoid over‑booking.
In a train ticket ordering scenario, two users (A and B) simultaneously view an available lower berth; user B books it first, and when user A later attempts to book the same berth, the system reports it as already reserved, highlighting the need for proper concurrency control.
Solution 1 – Simple Flag Field: Add a FLAG column (0 = free, 1 = reserved) to the seat table and check it before booking. Under high load, race conditions occur: both users read FLAG=0, both set it to 1, resulting in duplicate reservations. The timeline is illustrated as: A FLAG=0 at T1 (query) B FLAG=0 at T2 (query) B FLAG=1 at T3 (update) A FLAG=1 at T4 (update)
Solution 2 – Pessimistic Lock (FOR UPDATE SKIP LOCKED): Use a query such as SELECT * FROM table WHERE … FOR UPDATE SKIP LOCKED to lock rows during selection; if a row is already locked, the query skips it. While this prevents duplicate bookings, it degrades user experience because available seats may be hidden.
Solution 3 – Synchronized Block: Apply synchronized in application code to serialize access. This works only in a single‑node deployment; in a clustered environment a global lock mechanism is required.
Solution 4 – Hybrid Optimistic‑Pessimistic Lock: First read the seat information without locking (optimistic read). When a user proceeds to book, acquire a pessimistic lock on that specific record with SELECT * FROM table WHERE … FOR UPDATE . The second user attempting to lock the same record will fail, thus preventing duplicate booking.
The article concludes that combining optimistic reads with targeted pessimistic locks offers a practical balance between concurrency and user experience in high‑traffic ticketing systems.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.