views:

18

answers:

2

What is the general pattern or approach to managing transactions in a web-based e-commerce system? How do you handle the situation where more than one user tries to buy the last item, for example?

+1  A: 

To prevent two users from purchasing the same stock item of which there is only 1 unit in stock, you need to check that each item in a user's cart has stock available right before you create an order and decrement stock for that item.

This operation will have to be atomic and only one order can be processed at any given time (read: database transaction), which should not be a problem if you are using a central database for stock management.

If stock has run out by the time a client checks out, you should remove the item from the client's cart and redirect them to their shopping cart, informing them of the situation.

Of course, this situation only occurs when two users both add the same stock item to their cart of which only one unit is in stock and one of them checks out. First come, first served. You should generally not allow clients to add products to their cart if no stock is available at that moment, unless you can order new stock within a reasonable amount of time, but in that case, the whole point is moot.

You can take a preemptive approach by checking that stock is available the moment a client initiates checkout and take the same route as above. However, that would depend on the nature of your product and the volume of transactions vs cancelled orders. If it is likely that another order for the same item was cancelled in the meantime and stock becomes available by the time a client checks out, then you don't want to lose a sale by telling the client that no stock is available. Better to let the order fail at the moment stock is not available and inform the client of the situation, which is rare after all.

FreshCode
and then how do you handle failure? if stock isn't available when you try to process an order, do you just present a message to a user saying sorry item unavailable?
flesh
edited my answer.
FreshCode
A: 

Why not take the order and then get that item for the customer, perhaps a bit later? You can win a repeat customer :)

Ilya Vassilevsky