The Strategy
Pessimistic locking assumes conflicts are likely, so it locks the data before working on it. A transaction acquires a lock on the rows it touches and holds it until commit, blocking others from changing them.
How It Looks
- A statement like SELECT FOR UPDATE grabs a write lock on matched rows.
- Other transactions that want those rows wait until the lock releases.
- On commit or rollback the lock is freed.
When To Use It
- High contention where many writers target the same rows.
- Operations where retrying after a conflict is expensive or unsafe.
The Costs
- Reduced concurrency, since waiters block.
- Risk of deadlock when two transactions lock rows in opposite order.
- Risk of long waits if a lock holder is slow.
The opposite approach, optimistic locking, lets work proceed and checks a version at commit, which fits low contention better.
Key idea
Pessimistic locking blocks others by locking rows before use, trading concurrency for safety under high contention.