Lesson 1 of 19
17. Transactions and Locking

The picture to keep in your head

3 min read+10 XP

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 trainIn the system
A ticket that's seat and payment together, or nothingA transaction
Both passengers seeing "free" and bookingA race condition: lost update, double booking
What other passengers can see while you're bookingIsolation levels
Clerk's hand on the seat while you payPessimistic locking (SELECT ... FOR UPDATE)
"Let me check it's still free" before printingOptimistic locking (version check)
Two clerks each holding a seat the other needsDeadlock
A ten-minute holdReservation with expiry
Seat from one office, meal from another, payment from a thirdTransactions across services: 2PC or a saga

the train booking mapped to transactions, races, locks and holds.

Figure: every booking bug is two people acting on the same "it's free" at the same time.