0

If a Asp.net WebApi receives multiple PUT calls at the same time for creation/updation of a resource when a previous call for same resource's PUT operation is still in progress - how should it be handled ? Is there a way to lock the resource for the time its PUT is still in progress and return a conflict response in case another PUT call is received for same resource and release the lock once the creation of resource from first received call is completed? Basically I wanted to lock on the basis of 'name' of the resource. How can I handle race condition in such cases both in single and multi server environments.

Pulkit Sharma
  • 390
  • 2
  • 14
  • Search for `idempotency`. Web services/APIs don't use locks. Even if there was anything to lock, it reduces the throughput of the entire system dramatically. They use mechanisms to either discard duplicates or ensure duplicate processing produces the same results. – Panagiotis Kanavos Jun 26 '23 at 13:44
  • In POST/PUT etc, the [ETag header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) of the request can be used along with the `If-Match` header to ignore the request if the resource has changed in the meantime – Panagiotis Kanavos Jun 26 '23 at 13:46
  • This question might be relevant: [ConcurrentDictionary GetOrAdd async](https://stackoverflow.com/questions/54117652/concurrentdictionary-getoradd-async). – Theodor Zoulias Jun 26 '23 at 14:02
  • What do you mean with 'multi server environments'? Clustered server AND clustered storage? You might want to look what your storage can do here or if you need some sort of distributed locking system besides that. And yes that will have impact on throughput. – Ralf Jun 26 '23 at 14:17
  • What kind of resource? – shingo Jun 26 '23 at 14:21
  • @shingo resource is any kind of json object – Pulkit Sharma Jun 26 '23 at 14:36
  • @Ralf yes clustered server and clustered storage. Do you have any documentation on distributed locking system implementation. – Pulkit Sharma Jun 26 '23 at 14:38
  • No. As i said at best your storage system has something already. If you need something additional in such environments people often use something like Redis to implement distributed locking. See https://redis.io/docs/manual/patterns/distributed-locks/ – Ralf Jun 26 '23 at 14:40

0 Answers0