Skip to content

Optimistic vs Pessimistic Locking

When concurrent writes collide — version columns, SELECT FOR UPDATE, and choosing the right strategy.

15 min readdatabases, locking, concurrency, optimistic-locking, pessimistic-locking

Two users open the same customer record at 10:00 AM. User A changes the phone number and saves at 10:03. User B changes the email and saves at 10:05. User B's save overwrites User A's phone number change because User B was still working with the original version.

This is the lost update problem, and it's one of the most common data integrity bugs in web applications. The database's ACID guarantees protect individual transactions, but they don't protect against the gap between when you read data and when you write it back.

Locking is how you prevent concurrent modifications from clobbering each other. There are two fundamental strategies, and choosing the right one depends on how often collisions actually happen.

The Lost Update Problem

Let's see it in code:

 

This lesson is part of the Guild Member curriculum. Plans start at $29/mo.