Handling Concurrency in ASP.NET Core 2.0 Web API

Problem

How to handle concurrency in ASP.NET Core Web API.

Solution

Create an empty project and update Startup class to add services and middleware for MVC:

Add a controller with GET and PUT, to demonstrate concurrency:

Send a GET request and observe ETag header (using Postman):

Now using this ETag value, send a PUT request:

Discussion

We want to ensure that users are not overriding changes done by other users between the time they retrieved the data and submit their changes.

At its core, implementing such concurrency is a simple two-step process:

GET

We add a magic value to the response based on data we hold at the time. Usually ETag header is added for this purpose containing hashed value based on data/body of response.

Clients send this ETag value in subsequent requests as If-Match header, which we compare against ETag produced for current data and if unchanged, send a 304 (Not Modified) response.

PUT

We compare against ETag produced for current data and if changed, send a 412 (Precondition Failed) response.

Other Methods

Using hashed values of model representation is not the only way to implement concurrency. Entity Framework also provide mechanism to implement concurrency, I’ll discuss in a later post on EF Core.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Api.Concurrency

Leave a Reply