Reputation: 38503
I have a WebAPI POST controller method that basically just inserts a record with a quantity value into a table. I need to check that quantity against available quantity. The issue is that I can have multiple submissions occurring at the same time and want to eliminate any possible race conditions.
There are numerous ways to do this, but I am trying to determine the best approach. I thought of using a queue, but then the client device will need to make checks back to see state. I thought of using singleton pattern, but then the client will have to wait on release.
Anyone have any pointers?
Upvotes: 4
Views: 2763
Reputation: 3279
Your question is not related to WebAPI, but to your data and the data management layer. WebAPI should not care about the data, its role is to accept requests and send back responses. The response depends on the input data, validation , business logic and so on.
Your question is the classic concurrency control question. There're many answers and the right one will depend on your system and architecture.
I assume your database transaction involves these steps? : 1) New Record Insert with qty 2) Quantity Update ( new total = total - qty) And They must happen together or not happen at all?
One way to go is Optimistic Concurrency. Let the database (or your ORM (i.e Entity Framework)) tell you if the quantity counter is not stale, if it is stale, query it again and validate that the available quantity is still valid.
You'll need to google on how to implement the Optimistic Concurrency for your database. In a nutshell, it's a timestamp on the table that cannot be blindly modified. When an update is sent to the database, it contains the timestamp value that had been checked before the update, if it still matches, the transaction goes through, if the values are different, transaction is aborted.
Upvotes: 5