Preventing race conditions for ecommerce application with MySQL
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开发者_如何学JAVA 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.
checkout
reserver_the_items_in_cart
if(reservation_succesfull){
get_the_payments_done_via_payment_gatway
if(payment_successful) {
update_the_reserverd_to to sold_status
}else{
make_reserved_item_to_available.
}
}else{
show_error_that_item_not_available.
}
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.
The way I am going about this is 1. check availability for X books 2. if there are X books, place the actual order 3. check availability again if availability is ok, then everything is ok... if availability is off, I reverse the order and notify customer.
精彩评论