Skip to main content

Command Palette

Search for a command to run...

Handling Concurrency using EF Core (optimistic approach)

Ever wonder why EF defaults to optimistic approach when handling concurrency conflicts?

Published
2 min read
Handling Concurrency using EF Core (optimistic approach)
J

A software developer trying to write organic blogs in C# and .NET technologies.

Why does EF Core handle concurrency using the optimistic approach? Browsing through the documentation, you will see that handling concurrency conflicts on EF Core is handled by implementing an optimistic approach.

https://learn.microsoft.com/en-us/ef/core/saving/concurrency?tabs=data-annotations

You can implement it in various ways; here, I’ve used fluent configuration to set the concurrency token. There are multiple ways to do it; you can use the attribute using data annotations.

Image

Then I have an interceptor that sets the value of the concurrentToken to GUID. I’ve used reflection and created an

IHasConcurrencyToken

. I think it’s a very straightforward code. Now

Image

Now having this now will let your application throw

DbUpdateConcurrencyException

when a conflict occurs. Following the documentation you can create a logic like this where you can compare values and check whether what values are gonna be. You got three choices to handle this.

  • Throw the exception and show “Other users have modified the data please try again”.

  • Let the users choose which value to retain.

  • Compare the values and choose which value to retain.

Image

My question is, why does EF Core handle conflicts using an optimistic approach? Like there are lot of ways to handle concurrency conflicts, one with locks so it doesn’t happen on the first place.

Assuming concurrency conflicts on your app are rare, it will be most beneficial to implement an optimistic approach, because the problem with handling it pessimistically using lock isolation levels is that it blocks transactions when the data is being read. There are, of course, scenarios that I can think about on where pessimistic looks good.

  • Bank balance updates

  • Ticketing or reservation systems

  • Critical systems where first-come, first-served must be honored.

For now, I’ve just shown how to use an optimistic approach on handling concurrency. I think this is production-grade code and feel free to use it.