Member-only story
When to Use Optimistic vs Pessimistic Locking
Can you hold the lock, how often do writers collide, and what does a lost write cost?
Optimistic vs pessimistic locking is a choice about when you check for a conflicting write, not about whether you lock. Pessimistic locking claims the row up front with a database lock, so no one else can touch it until you commit. Optimistic locking lets the write proceed and checks a version number at commit time, failing if another transaction changed the row first. Start optimistic, and move to pessimistic only when conflicts are frequent and the work you would lose is expensive to redo.
Not a Medium member? Read this article for free here.
That one sentence settles more arguments than most code reviews. The trouble is that almost every guide on the topic starts in the wrong place. It opens with “optimistic is faster, pessimistic is safer,” picks a side, and never explains the question underneath.
Here is the problem both strategies exist to solve. Two requests read the same row — an account balance, an inventory count, a document — at the same time. Each one computes a new value from what it read. Each one writes its value back. The second write silently overwrites the first, and the update from the first request is simply gone. This is the lost…





