1

I have an API that are used for add/update new records to DB.

On start of such request I try to get data from db by some identifiers for request and do some updates.

In case there there are few concurrent requests to my API, some duplicates maybe be created.

So I am thinking about "wait till prev request is finished".

For this I found a solution to use new SemaphoreSlim(1,1) to allow only 1 request in a time.

But now I am wondering if it is a good solution. Because in case 1 request may take up to 1 min of processing, will other requests be alive until SemaphoreSlim allow to process them?

For sure it is something related to configuration, but it always some approx. number in settings and it may be limited by some additional threshold settings.

demo
  • 6,038
  • 19
  • 75
  • 149
  • The other requests will be alive for as long as they're configured to be, at some point they'll time out if the server doesn't respond within their allowed limit – MindSwipe Oct 31 '22 at 10:07
  • @MindSwipe logical answer :) – demo Oct 31 '22 at 10:09

1 Answers1

2

The canonical way to do this is to use database transactions.

For example, SQL Server's transaction isolation level "serializable" ensures that even if transactions are concurrent, the effect will be as if they had been executed one after another. This will give you the best of both worlds: Your requests can be processed in parallel, and the database engine ensures that locks and serialization happen if, and only if, it's required to avoid transactional inconsistency.

Conveniently, "serializable" is the default isolation level used by TransactionScope. Thus, if your DB library provider supports it, wrapping your code in a TransactionScope block might be all you need.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • Thx for you answer. Just one question - is it also an option to load all resources in transaction before doing some updates just to "cache" them for get requests while that resources are locked in db? – demo Oct 31 '22 at 11:50
  • @demo: Sure, if it's acceptable that those get requests get data which might be outdated. – Heinzi Oct 31 '22 at 15:29