How to Choose Between Pessimistic and Optimistic Locks
Compare SELECT FOR UPDATE against version-column checks, pick by contention level and transaction length, and implement retries for conflicts.
On this page
Introduction
Two users edit the same record at the same moment. Pessimistic locking answers by making the second wait: the row is locked before the first transaction finishes, so updates serialize. Optimistic locking answers by letting both proceed and rejecting the loser at write time: each transaction carries the version it read, and the update succeeds only if that version is still current. Both preserve correctness; they differ in where they spend their cost. Pessimistic spends it always, in lock waits and deadlock risk, even when no conflict would have occurred. Optimistic spends it only on actual conflicts, in rejected work and retries, which makes it nearly free under low contention and punishing under high. Choosing between them is a measurement question about the conflict rate and the shape of transactions, not a philosophical one. This tutorial implements both against the same schema, quantifies the crossover, covers the deadlock discipline that pessimistic locking demands, and builds the retry loop that optimistic locking demands.
The mechanics of each strategy
Pessimistic locking in SQL is SELECT … FOR UPDATE: the row, or rows, matched by the query are locked until the transaction commits or rolls back. Other transactions attempting to lock or update those rows block. Variants matter: NOWAIT fails immediately instead of waiting, and SKIP LOCKED skips past locked rows, which is the foundation of lock-based work queues. Deadlocks arise when two transactions lock rows in different orders, and the database resolves them by aborting one, so lock ordering discipline is mandatory. Optimistic locking needs no special SQL: a version column, incremented on every update, with the UPDATE statement carrying the version it based its computation on. The WHERE clause includes both the key and the version, so a conflicting earlier update makes the affected row count zero, and the transaction knows its premise is stale. The variant column can be a monotonic counter, a content hash, or a timestamp, though timestamps collide under low resolution and are best avoided.
-- pessimistic: second writer waits
BEGIN;
SELECT * FROM accounts WHERE id = 7 FOR UPDATE;
-- compute, then apply
UPDATE accounts SET balance = balance - 500 WHERE id = 7;
COMMIT;
-- optimistic: second writer fails fast
UPDATE accounts
SET balance = balance - 500, version = version + 1
WHERE id = 7 AND version = 4;
-- 0 rows updated means conflict
Measure contention before choosing
The decision variable is the conflict rate on the rows in question, and it is measurable. Conflict rate: the frequency with which two transactions touch the same row inside overlapping windows, observable from application metrics, retry counters, or database lock statistics. Transaction length: the time between reading and writing, which determines the window. A two-second human-approval flow has an enormous window and should never be pessimistic, because it would hold locks across user think-time and serialize the whole department on one row. A twenty-millisecond inventory decrement has a tiny window, and if its conflict rate is high, because many buyers race for the same SKU, optimistic retries burn CPU and user patience while pessimistic locking makes the losers wait ten milliseconds. The crossover is empirical, but the rule of thumb is stable: conflict probability times retry cost versus wait probability times wait cost. Low contention, almost always the common case, favors optimistic because it costs nothing when there is no conflict. High contention with short transactions favors pessimistic because waiting is cheaper than redoing work.
Implement pessimistic locking safely
Pessimistic locking is safe only with three disciplines. Lock order: every transaction acquires rows in a consistent order, usually ascending primary key, which eliminates the circular wait that produces deadlocks. Short transactions: locks are held to commit, so no user think-time, no external HTTP calls, no gaps between lock and commit. Minimal scope: lock exactly the rows the business rule requires, with a WHERE clause as tight as the logic allows, because FOR UPDATE locks everything the query touches under the plan it chooses, and a plan that widens the scan widens the lock.
tx, _ := db.BeginTx(ctx, nil)
rows, err := tx.QueryContext(ctx,
"SELECT id, balance FROM accounts WHERE id IN ($1, $2) ORDER BY id FOR UPDATE", a, b)
// ... compute on both balances ...
_, err = tx.ExecContext(ctx,
"UPDATE accounts SET balance = $2 WHERE id = $1", a, newA)
_, err = tx.ExecContext(ctx,
"UPDATE accounts SET balance = $2 WHERE id = $1", b, newB)
err = tx.Commit()
The ORDER BY id in the locking SELECT is the entire deadlock defense for this pattern. Add a statement timeout so a lock wait cannot outlive the caller’s patience, and treat deadlock errors, which the database resolves by aborting one victim, as a retryable class with a small bounded retry, since the abort itself is the system working as designed.
Implement optimistic locking with retries
The optimistic path needs an honest retry policy, because a conflict means the transaction’s premise is stale: re-running the same UPDATE blindly fails again. The retry must re-read the row, recompute from the fresh values, and re-attempt, which distinguishes it from the network retry that resends identical bytes.
async function transfer(from: number, to: number, cents: number) {
for (let attempt = 0; attempt < 3; attempt++) {
const row = await db.one('SELECT balance, version FROM accounts WHERE id = $1', from);
if (row.balance < cents) throw new Error('insufficient funds');
const updated = await db.result(
'UPDATE accounts SET balance = $2, version = version + 1 WHERE id = $1 AND version = $3',
[from, row.balance - cents, row.version]);
if (updated.rowCount === 1) return;
await sleep(fullJitter(attempt));
}
throw new ConflictError('account changed during transfer');
}
Cap the retries, three is typical, because sustained conflicts signal contention that retries worsen rather than resolve, and surface the conflict to the caller or the UI when the cap is reached. For flows spanning a user session, edit forms with a hidden version field, the same mechanism rejects the stale submission at the server, and the conflict surfaces as a message asking the user to reload, which is optimistic locking exactly as it behaves in version control.
SKIP LOCKED as the queue pattern
One hybrid deserves its own section because it solves a different problem well: work distribution. A jobs table with competing workers can use FOR UPDATE SKIP LOCKED to claim jobs without coordination: each worker selects the next available rows, skipping anything another worker already holds, and locks only what it claims. No polling coordination, no queue service, and contention is resolved by construction because workers never wait on each other, they just take different rows.
WITH next_jobs AS (
SELECT id FROM jobs
WHERE status = 'queued'
ORDER BY priority DESC, id
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs j
SET status = 'running', locked_at = now()
FROM next_jobs
WHERE j.id = next_jobs.id
RETURNING j.*;
The pattern is pessimistic locking used optimally: transactions are as short as the claim, lock scope is exactly the claimed rows, and the skip means no queueing. It replaces a surprising amount of dedicated queue infrastructure for moderate scale, and it composes with a visibility timeout, locked_at, for reclaiming jobs from dead workers.
Test conflicts deliberately
Locking bugs are invisible on single-threaded tests, so tests must create the races deliberately. For optimistic: two transactions read the same version, both attempt the update, assert exactly one succeeds and the other sees zero affected rows and a clean conflict error. For pessimistic: begin a transaction holding a lock, attempt a second lock from another connection with NOWAIT, and assert the immediate failure; then attempt without NOWAIT with a short timeout and assert the wait resolves at commit. Deadlock discipline deserves its own test: two connections locking the same two rows in opposite orders, asserting the database aborts one and the application retries it successfully. Under concurrency, run N parallel transfers over a small set of accounts and assert the invariant, sum of balances unchanged, which is the property all this machinery exists to protect.
const results = await Promise.all(
Array.from({ length: 20 }, () => transfer(7, 9, 10)));
expect(results.filter(r => r === 'ok')).toHaveLength(20);
expect(await totalBalance(7, 9)).toBe(initialTotal);
Common pitfalls
- Locking across user think-time. A pessimistic lock held through a confirmation screen serializes everyone on one row; optimistic is built for this.
- Inconsistent lock order. The classic two-row deadlock, solved once by always locking ascending by key.
- Blind optimistic retries. Resending the same UPDATE after a conflict fails again; retry must re-read and recompute.
- FOR UPDATE with a wide plan. The lock covers whatever the scan touches; keep the locking query tight.
- Unbounded retries on hot rows. Retries amplify contention; cap them and escalate to pessimistic or queueing.
- Timestamps as versions. Second-resolution collisions corrupt the mechanism; use counters or content hashes.
Conclusion
Pessimistic and optimistic locking both preserve correctness under concurrency and differ only in where cost lands: always, as lock waits and deadlock discipline, versus only on conflict, as rejected work and honest retries. Measure the conflict rate and the read-to-write window, then apply the rule: low contention or long windows favor optimistic version checks with recompute-and-retry; hot short transactions favor FOR UPDATE with ordered, tight, short-lived locks, and SKIP LOCKED turns that machinery into contention-free work claiming. Test the races deliberately, parallel writers asserting the money invariant, and treat deadlocks and conflicts as designed outcomes with bounded handling, not as errors to be surprised by. The right choice per table is measurable, mixable, and worth revisiting as the workload drifts.
Sources: PostgreSQL: explicit locking, PostgreSQL: transaction isolation, MySQL: InnoDB locking.
FAQ
- Which isolation level removes the need for either?
- Serializable isolation detects conflicts automatically, but it works by aborting transactions, so it is optimistic locking with database-managed retries. It shifts the work rather than eliminating it, and it costs throughput on hot rows.
- What does SKIP LOCKED do?
- It makes SELECT FOR UPDATE skip rows already locked by others instead of waiting, which turns lock-based queries into a work queue where competing workers claim disjoint rows without coordination.
- Can I mix both strategies?
- Yes, and mature systems do: optimistic for typical low-contention flows and pessimistic for the few hot entities where retry storms would dominate, such as counters, inventory, and leader election.
Report a problem with this articleOpens a pre-filled issue on GitHub.