LESSON 15 / 24·2 min readAdvanced

Optimistic vs pessimistic locking?

01 Understand02 Recall03 Prepare

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:

SQL
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.
PAUSE & RECALL

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.

CONNECT IT TO YOUR INTERVIEW

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.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What is a deadlock, and how do I handle it?

Adapted from 05_SQL_POSTGRESQL.md · “Optimistic vs pessimistic locking?”. Examples are study fragments; framework behavior can depend on your version.