Optimistic vs pessimistic locking?
Understand the concept
Optimistic locking checks whether data changed before committing an update, often by comparing a version number. Pessimistic locking acquires a database lock before performing a critical change. The first avoids waiting when conflicts are rare; the second coordinates competing writers but can increase waits and deadlocks.
Important ideas
-
Optimistic: update only if a version still matches; retry or reject conflicts.
-
Pessimistic: lock needed rows before changing them, for example with
FOR UPDATE. -
A transaction alone does not prevent every lost update; choose the right update and isolation strategy.
-
A version check must be part of the UPDATE condition, and the application must check how many rows were affected.
Example — optimistic locking:
UPDATE orders
SET status = 'approved', version = version + 1
WHERE id = $1 AND version = $2;- Bind the order ID and version read earlier. Zero affected rows means the row is missing or its version changed; reload or report a conflict.
Can you explain it without the notes?
Optimistic vs pessimistic locking?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
Optimistic locking checks whether data changed before committing an update, often by comparing a version number. Pessimistic locking acquires a database lock before performing a critical change. The first avoids waiting when conflicts are rare; the second coordinates competing writers but can increase waits and deadlocks.
Turn this concept into a clear answer.
- Choose based on conflict frequency and business behavior on conflict, not the assumption that one strategy is always faster.
Adapted from 05_SQL_POSTGRESQL.md · “Optimistic vs pessimistic locking?”. Examples are study fragments; framework behavior can depend on your version.