user1790300
user1790300

Reputation: 1735

Shopping cart application strategies

I am developing a shopping cart application for my client and am trying to find a strategy to make sure there is no way a collision can occur during purchasing.

For example, if there are five items left in inventory, and two clients happen to make a purchase at the same time; the inventory should be three items left and not four. It seems like I would have to know right before the purchase, what the current inventory is. Also, I need a way to tell if someone grabbed the last item even if they have not made the purchase yet.

What strategies/patterns should I use to ensure these conditions are met? I am developing a .net mvc application with SQL Server.

Upvotes: 1

Views: 419

Answers (1)

Adam Tuliper
Adam Tuliper

Reputation: 30142

Ah concurrency. You have multiple things to consider here:

  1. If you store the inventory and subtract from it and write it again in a separate update you are leaving your inventory count open to issues
  2. If your update is a single transaction to reduce the inventory by the current amount you could make your inventory go negative

Your updates must:

  1. Start a transaction
  2. Lock the row in question by performing a select on it and reading inventory. Handle the case where there isn't enough on hand.
  3. If enough inventory update the row 3a sanity check the inventory during testing
  4. Commit or rollback the transaction

There are various ways to do this but the above should work fine here. You can start the transaction in your code via a new transactionscope object or server side in a proc via begin transaction.

Upvotes: 2

Related Questions