WebAPI Race Conditions Prevention

I have a WebAPI controller POST method that basically just inserts a record with a count value into a table. I need to check this quantity against the available quantity. The problem is that I can present multiple views at the same time and want to eliminate any possible race conditions.

There are many ways to do this, but I am trying to determine the best approach. I was thinking about using a queue, but then the client device would need to check back to see the state. I was thinking about using a singleton pattern, but then the client would have to wait for release.

Anyone have pointers?

+3


source to share


1 answer


Your question is not about WebAPI, but about your data and data management layer. WebAPI doesn't have to care about data, its role is to accept requests and send responses. The answer depends on the input, validation, business logic, etc.

Your question is a classic concurrency control question. There are many answers, and the right choice will depend on your system and architecture.

I am assuming your database transaction involves these steps ?: 1) New record with qty 2) Quantity update (new total = total) And do they have to happen together or not at all?



One way: Optimistic Concurrency . Let the database (or your ORM (ie Entity Framework)) tell you if the count is not out of date, if it's out of date, request it again and confirm that the available count is still valid.

You will need google how to implement Optimistic concurrency for your database. In a nutshell, it is a table timestamp that cannot be blindly modified. When an update is sent to the database, it contains the timestamp value that was checked before the update, if it still matches, the transaction goes through, if the values ​​are different, the transaction is aborted.

+4


source







All Articles