17. Transactions and Locking
The picture to keep in your head
Every question below is answered twice: first on the train, so you can picture it, then in the system, so you know exactly how it works. Each answer ends with a memory code to lock it in.
The picture to keep in your head
Two passengers look at the seat chart at the same moment. Seat 14 is free. Both book it. Both board, both walk to seat 14, and now there's an argument in the aisle. Nothing was wrong with either booking on its own; the problem is that both acted on the same "it's free" at the same time.
Railways solve this in a few ways. The booking clerk puts a hand on the seat while you pay, so nobody else can take it. Or they check again at the very last moment that it's still free before printing the ticket. Or they give you a ten-minute hold: the seat is yours if you pay in time, and released if you don't. And a ticket is all or nothing: you never get the seat without paying, or pay without getting the seat.
That's transactions (all or nothing) and locking (stopping two people from acting on the same "it's free").
Our running example: the bookstore's Book Fest author signing, with 100 numbered seats at ₹499 each, opening at 10 am. Thousands of fans try to book in the first minute.
| On the train | In the system |
|---|---|
| A ticket that's seat and payment together, or nothing | A transaction |
| Both passengers seeing "free" and booking | A race condition: lost update, double booking |
| What other passengers can see while you're booking | Isolation levels |
| Clerk's hand on the seat while you pay | Pessimistic locking (SELECT ... FOR UPDATE) |
| "Let me check it's still free" before printing | Optimistic locking (version check) |
| Two clerks each holding a seat the other needs | Deadlock |
| A ten-minute hold | Reservation with expiry |
| Seat from one office, meal from another, payment from a third | Transactions across services: 2PC or a saga |
Figure: every booking bug is two people acting on the same "it's free" at the same time.