Lesson 7 of 19
17. Transactions and Locking

17.6 What is pessimistic locking?

3 min read+10 XP

Locking

On the train: The clerk puts a hand on seat 14 the moment you ask for it. Anyone else who wants seat 14 waits until you've paid or walked away.

In the system: Pessimistic locking locks the rows you intend to change before you change them, so nobody else can change them meanwhile:

sql

pessimistic: lock then work; optimistic: work then check the version.

Figure: lock first when conflicts are common; check last when they're rare.

  • Guarantees no conflict at the end: nobody else could touch the row.
  • Costs: others wait while you hold the lock, so hold it briefly; and locks can deadlock (17.8).
  • Watch out for a hot single row. If every booking locks one events row to decrement seats_left, and each transaction holds it for about 50 ms, the whole event can only sell about 20 tickets a second, however many servers you have. Lock per seat instead, or use an atomic update.

Memory code: "Hand on the seat before you sit."