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.
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:
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:
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
| Feature | Optimistic Locking | Pessimistic Locking |
| Locking Mechanism | Occurs when updating data, checks versions or timestamps | Locks data before processing |
| Use Case | Low conflict scenarios (e.g., editing user settings) | High conflict scenarios (e.g., frequent updates to critical data) |
| Performance | Generally better in low conflict scenarios due to fewer locks | Can be slower due to locking overhead |
| Risk | Higher risk of rollbacks in high conflict scenarios | Can lead to deadlocks if not managed properly |
| Suitability | Suitable for short transactions | Preferred 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
- Optimize finding index of nearest point in 2d arrays
- Optimize write performance for AWS Aurora instance
- Optimizing queries for the next and previous element
- Optional secondary indexes in DynamoDB
- Override Authorize Attribute in ASP.NET MVC
- Parsing secrets from AWS secrets manager using AWS cli
- order of execution in async/await
- Out of Memory exception while uploading and resizing multiple images asynchronously

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack 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.