Suppose I have a web app where sellers add their products and set them as available for sale. Then I show a list of products in my mobile app, where I get products via my REST API. My problem: suppose two clients view the same product(and there's only 1 item available from the seller) and they make simultaneous order. How do I resolve such collision?

My technology stack: RoR, PostgreSQL, heroku.

  • The key search terms to look for are "optimistic pessimistic locking inventory" possibly tossing "ecommerce" in there too.
    – user40980
    Commented May 14, 2013 at 13:35

1 Answer 1


There's no such thing a simultaneous order. Your server is going to have to process one of the basket add actions first. At the point that happens the product should be locked, and any subsequent basket add actions should return an out-of-stock message. If the customer doesn't checkout within a fixed time (often one hour) it's normal to remove the lock on the product and return it to sale. This can be supplemented with messaging on the basket page explaining that the item in their bag is only going to be available for a fixed time due to low stock.

The critical thing from the user's perspective is that whichever one of them tries to add the item to their basket second should receive a message indicating the item is out of stock immediately after trying to add it to their basket. It's terrible UX to let them get into the checkout thinking they've got an item and then reject the sale later.

In general ecommerce websites get around this problem by automatically marking items as out of stock when they get down to low but non-zero product levels. This allows the merchandisers to restock the items without ever having taken an order that they're unable to fulfil; though that might not be possible in your case if the sellers are selling unique items.

  • 3
    Most web servers and DBMSs are multi-threaded, and they do allow parallel handling of more than one request. While no two orders can be inserted into a database at the exact same time, the entire process of creating an order has additional steps, and unless special care is taken, race conditions can occur and lead to undesirable behavior.
    – tdammers
    Commented May 14, 2013 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.