This question already has an answer here:
I'm trying to implement a little shopping system. I have a single product which has a limited stock.
For example, my product can be bought 5 times.
My problem is, if a user adds this product to his cart, fill the form and pay.
Decrement the stock when he adds the product to his cart (problem: if he quits the site before the payment? The product stock is decremented, but not bought)
Decrement the stock when the payment is confirmed (problem, if 2 or more user pay at the same time)
Have you got any advice on the best way to solve this?