Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Databases
Databaseshard

Optimistic vs pessimistic locking — what’s the difference?

Tags
#locking#optimistic#pessimistic#concurrency
Back to categoryPractice quiz

Answer

Optimistic locking assumes conflicts are rare: you update with a version/timestamp check and retry on conflict. Pessimistic locking locks rows upfront (e.g., `SELECT ... FOR UPDATE`) to prevent others from changing them.

SELECT *
FROM accounts
WHERE id = 1
FOR UPDATE;

Advanced answer

Deep dive

Both approaches prevent lost updates under concurrency, but they fail differently.

Optimistic locking

  • No lock up front.
  • On update, you assert “I’m updating the version I read”.
  • If another transaction updated first, your update affects 0 rows → you retry or abort.

Example:

UPDATE accounts
SET balance = balance - 10, version = version + 1
WHERE id = 1 AND version = 7;

Best when:

  • conflicts are rare,
  • you want high throughput,
  • you can retry safely.

Pessimistic locking

  • Lock the row(s) first (e.g., `SELECT ... FOR UPDATE`).
  • Others block (or fail fast) until you commit/rollback.

Best when:

  • conflicts are frequent,
  • business rules require strict sequencing,
  • retries are expensive.

Common pitfalls

  • Optimistic locking without idempotent

Related questions

Databases
What is a deadlock in a database and how do you reduce it?
#deadlock#locking#transactions
Databases
What is an isolation level (and why do we care)?
#transactions#isolation#concurrency
Testing
How do you test asynchronous or concurrent code?
#async#concurrency
retry logic.
  • Pessimistic locks held too long (deadlocks, reduced concurrency).
  • Mixing lock orders across code paths (deadlock risk).
  • #determinism
    Operating Systems
    What causes deadlocks and how can you prevent them?
    #deadlock#locks#concurrency
    Operating Systems
    Processes vs threads — what’s the difference and when does it matter?
    #processes#threads#concurrency
    PostgreSQL
    MVCC in Postgres: why don’t readers block writers?
    #postgres#mvcc#concurrency