I’m building a ecommerce application with MySQL, but I’m having a hard time coming up with a solution that prevents the following race condition:
Two users checkout at the same time with the same item in their cart. The store only has one item available for sale. One user should be able to purchase the last item, and the other user should see an error message because the item is out of stock.
I’m using an item counter to keep track of the number of items in inventory, so I figure I would just decrement the item after processing the user’s credit card.
I know about the SELECT...UPDATE query in MySQL, but I’d like to stay away from locking rows or tables – unless that’s really the best way for an ecommerce app to solve this problem.
I’m also interested in hearing other solutions other than checking/decrementing an item counter.
Why are worried about locking. It wont hurt you till you have 100s of simultaneous customers at a time and database engines like innodb are made to handle those things. You wont be able to get way from some kind of atomicity and workaround.
You need to keep application level transaction management.
Other best way to handle this is never allow “show_error_that_item_not_available” to happen. Replenish inventory on time when it started running out.