EF Core Concurrency Control Strategies for 500K CCUs
Tags: dotnetcore, dotnetframework, codenewbie
Published: 2023-07-15 20:42:13

Concurrency control is a concept which is well know in computer science. It defines how data is managed when several users are accessing it and editing simultaneously. Over the years I have found Concurrency control significance in Preventing Trouble like Lost Update problems. Basically an update has been made unknowingly by one user that another user below him/her edits it and makes changes on them causing trouble due to overwrite. In this post we will look at the issues related to concurrency problems incorporated into **Entity Framework Core (EF Core)**. We will also explore EF Core strategies and mechanisms against EF Core Concurrency problems head-on.

## What is Concurrency Control?
Let's try define concurrency control in database systems ensures the correct results for concurrent operations get generated while also ensuring that those results are delivered as soon as possible. **Concurrency control is indeed difficult with its work being to maintain isolation amongst concurrent transactions while at the same time making sure consistency within the integrity of the database gets achieved.**

## Optimistic Concurrency in EF Core

[I havened EF Core when architect the game which was need to support 500K CCU (mistake)](https://infinitymesh.com/blog/how-to-build-an-enterprise-game-platform-for-millions-of-players/). EF Core is by default optimistic concurrency control strategy. **_It does not believe there will be too much conflicts._** Hence, it allows several transactions o finish without any needless locking. It helps a great amount in increasing performance. But when the changes are saved, EF Core checks whether there is a conflict and throws an exception if one is found.

There are two kinds of conflicts. How version or timestamp is added not just to entity but also to them as such. When EF Core update DB while add WHERE clause in UPDATE statement will check out numbers being updated in DB from the version of the entity matched Version1 of the entity as already existing in the DB and rest on them were different. If so, those specific rows will be updated and application will continue once they have been written to the database. Rest (i.e., no change) will throw an exception.

## Implementing Concurrency Control in EF Core

In order to make well know examples I will analyze a more realistic but complex scenario of an e-commerce application where we have `Product` and `Order` entities. We'll implement a more detailed concurrency control scenario with a property that is not related directly to a database column, but instead is computed from other properties.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9acmjyzg6a9k6q2js0o.png)

In this case, the `StockValue` property of `Product` is marked with the `[ConcurrencyCheck]` attribute and is also specified as a concurrency token in the `OnModelCreating` method. This will inform EF Core to include this property while checking for concurrency conflicts.

Now let's look at a scenario where two users try to place an order for the same product concurrently:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g4b8qjfuh96y4ukuicaw.png)

In this scenario, User Haris will receive a `DbUpdateConcurrencyException` when trying to save changes. This happens because the `StockValue` of the `Product` entity has been changed by User Admir, and EF Core detects this during User Haris `SaveChanges` call.

## How to fix Concurrency Conflicts

Inconsistency in a buyers requisites and the availability of the product pose difficulties for an e-commerce company when executing concurrency. You might want to let the user know that available anymore, or you might want the purchase to proceed with a delay. Here's an example of how you might handle this:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovyu0xas05w9dmx6g87m.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihn2mghgp8b61tumeiln.png)

In this example, whenever a concurrency conflict occurs, the application will catch the `DbUpdateConcurrencyException`, notify the user, wait for a while before retrying the operation, and then refresh the conflicting entity from the database.

## In the end

I hope I have explained how concurrency control plays an important role in multi-user applications to maintain consistency, integrity of data and consistency. Entity Framework Core offers a fast and strong concurrency management with its optimistic concurrency controlling mechanism. 

If you understand how it works and choose wisely on how to handle the conflicts, implementing reliable and concurrent application won't be that difficult for you. **Every application is different!** Therefore, there is not one true solution to handling opposing concurrences in your own application. **You've got to somehow chose a right strategy proper for your application and business rules.**

If you believe I can help with something, don’t hesitate to contact me, and I will reach out as soon as possible. 

[admir.m@penzle.com](https://www.linkedin.com/in/admir-live/)

Cheers! 👋