I am using Java Spring Framework and Hibernate. I am doing a e-commerce web application where public user is able to purchase product from the web app. Each product will have a quantity count.
Issue
I want to prevent the scenario where two concurrent users purchase the same product is left with quantity value 1. In this case, only the first user should get to purchase the product while the second user should receive a "no stock available" message.
Workflow
I intend to decrement the quantity count and then send the purchase information to the payment gateway. If payment gateway encounters payment issue, I will increment the quantity count. The lock will be released before purchase info is sent to payment gateway.
So my question is,
1) I would like to confirm this answer on pessimistic locking does help solves my issue.
2) Is my workflow ok? Is there a better way to do this?