MongoDB optimistic locking
Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?
Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.
So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!
Introduction
When moving from JPA to MongoDB you start to realize how many JPA features you’ve previously taken for granted. JPA prevents “lost updates” through both pessimistic and optimistic locking. Optimistic locking doesn’t end up locking anything, and it would have been better named optimistic locking-free or optimistic concurrency control because that’s what it does anyway.
Lost updates
So, what does it mean to “lose updates”?
A real-life example would be when multiple background tasks update different attributes of some common Entity.
In our example, we have a Product Entity with a quantity and a discount which are resolved by two separate batch processors.
- the Stock batch loads the Product with {quantity:1, discount: 0}
- the Stock changes the quantity, so we have {quantity:5, discount: 0}
- the Discount batch loads the Product with {quantity:1, discount: 0}
- the Discount changes the discount, so we have {quantity:1, discount: 15}
- Stock saves the Product {quantity:5, discount: 0}
- Discount saves the Product {quantity:1, discount: 15}
- the saved quantity is 1, and the Stock update is lost
In JPA you may provide the @Version field (usually an auto-incremented number) and Hibernate takes care of the rest. Behind the scenes, there is a safety mechanism that checks the updated rows number when given a specific version. If no row was updated, then the version has changed and an optimistic locking exception is thrown.
UPDATE Product SET quantity=1, discount=15 WHERE version=1;
But if your storage is not a relational database system but a NoSQL database instead, you still want to prevent lost updates.
Luckily Spring Data comes to the rescue, as it provides a set of Document-oriented annotations, among which you can find a @Version annotation with the same semantic as its JPA counterpart.
If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.
Conclusion
An automatic retry mechanism should be employed if the optimistic locking exception is a recoverable one, meaning that it is allowed to reload the latest Entity snapshot, merge the specific changes, and update the record in the database.
So, Spring Data offers more than base repository support and simple query automation. The optimistic locking add-on provides the proper level of write consistency required by your application requirements.
