Optimistic locking
Оптимистичная блокировка
A way to prevent stale edits from overwriting newer ones. Instead of keeping a record locked while someone works on it, the application checks at save time whether the record has changed.
Also known as: пессимистичная блокировка
The problem it solves
Suppose two support agents open the same ticket. One reassigns it and saves. The other edits the summary and submits a form that still contains the original assignee. If the server blindly writes every submitted field, the reassignment is undone. That’s a lost update. Optimistic locking lets the server reject the stale save rather than silently overwrite the newer state.
How a version check works
Give each row a version number and return it with the data. When the client saves, it sends back the version it originally read. The database compares that version and applies the change in a single statement:
UPDATE tickets
SET summary = :summary, version = version + 1
WHERE id = :id AND version = :expected_version;
If both agents read version 4, the first update to commit advances it to 5. At PostgreSQL’s READ COMMITTED isolation level, the stale update then affects zero rows. Check the affected row count: zero means the expected row version wasn’t found, which can also happen if the ticket was deleted. At stronger isolation levels, PostgreSQL may report a serialization failure instead.
Choosing a conflict strategy
Optimistic locking fits systems where competing writes are uncommon or where users might spend minutes editing a form. On conflict, show the user what changed and let them reconcile the edits. A background job can sometimes retry safely by reading the latest state and recomputing the change, with a limit on attempts. Swapping in the newest version while resending the old payload defeats the check.
Pessimistic locking is an alternative, not another name for the same technique. For example, SELECT ... FOR UPDATE takes a row lock up front and holds it until the transaction ends. That can make sense for a short operation with frequent conflicts, but not while waiting for someone to submit a form. Optimistic locking avoids holding a lock between the read and the write; it doesn’t mean the UPDATE itself is lock-free.
What interviewers look for
Be ready to explain why a separate version check followed by an unconditional write is unsafe: another writer can change the row in between. Also consider every write path. An ORM can manage versions automatically, but a bulk job or direct SQL update that changes data without advancing the version can go undetected. Finally, a per-row version check doesn’t by itself enforce a rule that depends on several rows, such as keeping at least one person on call.