Concurrency Control
Database Management
Optimistic Locking
Pessimistic Locking
Data Security

Optimistic vs. Pessimistic locking

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

When dealing with multi-user databases, maintaining data integrity and preventing write conflicts is crucial. Two primary strategies to manage these challenges are optimistic and pessimistic locking mechanisms. These approaches differ significantly in their methodologies and use cases.

What is Pessimistic Locking?

Pessimistic locking is a strategy used to prevent concurrent modification conflicts by locking the data targets before they are actually used or modified. When a record is locked in a pessimistic manner, other transactions are unable to modify or lock the same data until the lock is released. This approach is akin to saying, "Assume the worst—that a conflict will occur—and lock the resource to prevent it."

For instance, in a banking system where two users might concurrently attempt to withdraw money from the same account, pessimistic locking would ensure that once one user starts a transaction involving the account, the account is locked until the transaction is complete. This prevents any other transaction from modifying the account balance until the lock is released.

Example of Pessimistic Locking:

In SQL, you might see pessimistic locking implemented like so:

sql
1BEGIN TRANSACTION;
2SELECT * FROM accounts WHERE account_id = 101 FOR UPDATE;
3-- Adjust balance
4UPDATE accounts SET balance = balance - 100 WHERE account_id = 101;
5COMMIT;

Here, FOR UPDATE clause ensures that the selected account is locked against updates by other transactions.

What is Optimistic Locking?

Optimistic locking operates on the premise that multiple transactions can frequently complete without interfering with each other. Rather than locking the data from the outset, it proceeds with the transaction and checks at the point of update whether another transaction has modified the data since it was originally read. If the data has been altered, the transaction is rolled back; otherwise, it commits successfully.

This approach is beneficial in environments with low conflict chances and where locking each use would be overly cautious and could hinder performance.

Example of Optimistic Locking:

Optimistic locking is often implemented using version numbers or timestamps. For example:

sql
1BEGIN TRANSACTION;
2SELECT balance, version FROM accounts WHERE account_id = 101;
3-- Checks if version is the same and then updates if it's unchanged
4UPDATE accounts SET balance = balance - 100, version = version + 1 WHERE account_id = 101 AND version = 1;
5COMMIT;

If the version field has changed from its original value during the transaction, the update will fail, signaling a conflict.

When to Use Each Approach

The choice between pessimistic and optimistic locking can depend on several factors:

  • Transaction duration: Pessimistic locking might be more suitable for longer transactions or where immediate consistency is crucial.
  • Data contention: For high contention environments (many users accessing the same data), pessimistic locking might prevent constant rollback of transactions due to frequent conflicts.
  • Performance concerns: Optimistic locking can perform better in scenarios where conflict is rare, as it reduces the overhead of lock management.

Comparison Table

FeatureOptimistic LockingPessimistic Locking
Locking MechanismOccurs when updating data, checks versions or timestampsLocks data before processing
Use CaseLow conflict scenarios (e.g., editing user settings)High conflict scenarios (e.g., frequent updates to critical data)
PerformanceGenerally better in low conflict scenarios due to fewer locksCan be slower due to locking overhead
RiskHigher risk of rollbacks in high conflict scenariosCan lead to deadlocks if not managed properly
SuitabilitySuitable for short transactionsPreferred for transactions that aren't time-sensitive and require guaranteed access

Conclusion

Understanding the distinctions between optimistic and pessimistic locking is essential for database designers and developers to ensure the integrity and performance of database operations. The choice of locking strategy should align with specific use cases, transaction lengths, and system environments to balance between performance and data correctness. By strategically selecting the locking mechanism, applications can achieve the necessary balance between concurrency and consistency.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.