Optimistic vs. Pessimistic Locking Strategies

Nader Medhat
Nerd For Tech
Published in
5 min readMar 18, 2022

What is locking?

locking is the technique of preventing simultaneous access to data in a the system, To allow several users to mauplate a record at the same time and also prevent inconsistencies results created by unrestricted access, a single record can be locked when retrieved for updating. Anyone attempting to retrieve the same record for editing is denied write access because of the lock. Once the record is saved or edits are canceled, the lock is released. Records can never be saved so as to overwrite other changes, preserving data integrity.

Locking general example

as example you have an inventory object for each product in you app and you need to place an order and dudct the quantity then saved it after it placed

imagine now you 2 customers sent a request to place an order from the inventory as the same time and you have 3 items available in your inventory

First customer will buy 2 items so the inventory will check the qunityt and it will be valid then it will dudtect the qunity from the inventory and it the avalble quantity will be 1 after saving the item

second customer will buy 3 items so the inventory will check the qunityt and it will be valid then it will dudtect the qunity from the inventory and it the avalible quantity will be 0 after saving the item

but the total dudcted qunitity is 5 so it will put the inventory object invalid state this is a simple example for this topic and will go throw to different strategies in this article to solve it

Optimistic locking

What is Optimistic locking?

in this staratgy assumes that multiple users will work without affecting each other. In other words, no locks are enforced while doing optimistic locking. we just verifies that no other transaction has modified the data. In case of modification, we will rolled back our changes.

Optimistic locking different implementations

we could use this strategy with many implementations like :

  • check old values and new values before updating.
  • Create a timestamp data type in your object and while updating check if the old timestamp is equal to the record timestamp
  • add a version to the object

Solutions for our problem with Optimistic locking

we will use version to solve our problem . we will add version number to the inventory object and before save the object we will check if there is an inventory object with this version before saving the object with the version

so our case will be like that :

first and second customer will make their requests in to the objects in the run time but when saving it only one will be saved the second willn’t find the object because it was changed be the first request as explained with the blow image

user A and B will get the inventory object but only user A modified object will be saved and User b object will be dismissed because version updated and DB will take only one request by the time because the synchronization natural of it

Pessimistic locking

What is Pessimistic locking?

in this staratgy assumes when you need to access the object for updating purpose we will lock the record for exclusive use until you we finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.

Pessimistic locking different implementations

We could use this strategy with many implementations like :

  • add a lock on the object in the memory or in the database after getting it
  • make the method that gets and update the object serializable in the code level
  • use stronger transaction isolation level

Solutions for our problem with Pessimistic locking

we will use locking to solve our problem . we will lock on the inventory object while getting it to be proceed for updating and if any request sent after that to get the same object will be failed

so our case will be like that :

first or second customer will make their requests in to the objects in the run time and the anthor will have an error because the object is locked by anthor request like the image blow

user A will get the inventory object and add local on it but when the user (B) tries to get this object will fail because it locked by another user

Conclusion

Optimistic locking is a very useful technique, and it works just fine even when using less-strict isolation levels, or when reads and writes are executed in subsequent transactions.

The downside of optimistic locking is that a rollback will be triggered by the data access , therefore losing all the work we've done previously by the currently executing transaction.

The more contention, the more conflicts, and the greater the chance of aborting transactions. Rollbacks can be costly for the system as it needs to revert all current pending changes which might involve both table rows and index records.

For this reason, pessimistic locking might be more suitable when conflicts happen frequently, as it reduces the chance of rolling back transactions.

--

--