What is the difference between optimistic and pessimistic locking?
Answer
Optimistic locking assumes conflicts are rare. Multiple transactions read the same row simultaneously. Before saving changes, the transaction verifies the row hasn't been modified by comparing a version number or timestamp. If it has changed, the save fails with a conflict error and the client retries. No database locks are held during the transaction — high concurrency, low overhead. Pessimistic locking acquires an exclusive lock on the row when it is read (SELECT ... FOR UPDATE), preventing others from modifying it until the transaction completes. Guarantees no conflicts but serializes access, reducing concurrency. Use optimistic for high-read/low-conflict scenarios; pessimistic for high-conflict critical sections.
Previous
What is an ORM and what are its trade-offs?
Next
What is database migration strategy for zero-downtime deployments?
More Database Design / Normalization Questions
View all →- Intermediate What are database anomalies and how does normalization prevent them?
- Intermediate What is denormalization and when is it used?
- Intermediate What are isolation levels in database transactions?
- Intermediate What are dirty reads, non-repeatable reads, and phantom reads?
- Intermediate What is query optimization and what is a query execution plan?