Optimistic Locking
ELI5 — The Vibe Check
Optimistic locking assumes conflicts are rare so it does not lock the row upfront. Instead, it adds a version number to each row. When you update, it checks if the version matches what you read. If someone else changed it first, your update fails and you retry. Less locking, more retrying.
Real Talk
Optimistic locking is a concurrency control strategy that checks for conflicts at write time rather than locking rows during reads. It is implemented by adding a version or timestamp column. Before updating, the query verifies the version matches. If another transaction modified the row first, the update affects 0 rows, signaling a conflict. Used when conflicts are infrequent.
Show Me The Code
-- Check version before updating
UPDATE products
SET stock = stock - 1, version = version + 1
WHERE id = 42 AND version = 7;
-- If 0 rows updated, someone else changed it first
When You'll Hear This
"Use optimistic locking for low-conflict scenarios to avoid blocking." / "The ORM uses a version column for optimistic locking automatically."
Related Terms
Locking
Locking prevents two transactions from modifying the same data at the same time. It is how databases coordinate concurrent access.
Pessimistic Locking
Pessimistic locking assumes conflicts are likely, so it locks the row the moment you read it. Nobody else can touch it until you are done.
Race Condition
A race condition is when two parts of your code are racing to do something at the same time and the winner isn't guaranteed — leading to unexpected, hard-t...
Transaction
A transaction groups multiple database operations into one all-or-nothing bundle. Either ALL of them succeed, or NONE of them happen.