Lesson 8 of 19
17. Transactions and Locking

17.7 What is optimistic locking?

3 min read+10 XP

On the train: No hand on the seat. You fill in the form, and just before printing, the clerk checks: "is seat 14 still exactly as it was when you started?" If someone took it, you start again.

In the system: Optimistic locking takes no lock. It reads a version (a counter or timestamp) with the row, and makes the write conditional on the version being unchanged:

sql

In the chapter's code, Asha books the last seat; Ravi's write, carrying the old version, is rejected, and his retry sees zero left.

  • No waiting, no locks held, which suits web apps where a user may take minutes between reading and saving (editing a profile, a document).
  • Costs: under heavy contention (thousands chasing 100 seats), most attempts fail and retry, wasting work. There, pessimistic locks, atomic updates or a queue (Chapter 43) do better.

Many ORMs support this directly with a version column.

Memory code: "Check it's still free as you sit."