Pessimistic Locking

Serialize a short critical section with database row locks.

Problem

A scarce resource must be checked and changed without interference.

When to use it

  • Inventory or refund limit contention is bounded
  • All writers share the database owner

When not to use it

  • Long external calls occur in the transaction
  • Rows are locked in inconsistent order

Minimal example

SELECT inventory ... FOR UPDATE; verify available; update reserved; commit before calling external services.

Tradeoffs

  • Can deadlock or reduce throughput
  • Lock order and timeout policy matter