Spring boot + Mongodb, how do i read and lock document and then write (save) and unlock the document

Viewed 735

I have a several cases where microservices are utilizing the same document (has many fields) and alot of those fields are shared between services for some validations. Here is the problem we're running into with the CrudRepo apis , concurrency, and atomic.

User 1 makes an update, so it calls the API and reads the document, and performs business logic, then at the end saves it. User 2 makes the same update as well (with different data), same API.

What happens is user 1 works perfectly fine, and saves the update to the document, user 2 reads the document before user1 finishes his update, so he doesn't see user1 changes on it. So when user 2 updates the document (they're updating the same array, adding/updating elements) and saves, he overwrites user 1's changes in there.

Ideally i'd like a read and lock to happen, so user 2 doesn't even read the document unless its ready to be read with the latest changes and then perform the business logic with the latest data. that would solve user2's problem. And a write (save) and unlock at the very end so other APIs can list reactively and then its their turn to go for that document.

I'm open to hearing any best practices and standards for this type of problem though! Would really appreciate the help!

0 Answers
Related