LESSON 16 OF 19

Concurrency Conflicts: When Two Users Update the Same Record

Learn how to configure optimistic concurrency in EF Core 10, reproduce DbUpdateConcurrencyException, and safely resolve conflicting updates.

35 dk 123

Introduction

Imagine two users editing the price of the same product at nearly the same time. User A reads the product at 100 USD. User B reads the same product, changes the price to 120 USD and saves it. User A still sees 100 USD on the screen and then saves 110 USD. What should happen? If the second update is accepted silently, User B's change is overwritten without warning.

This situation is known as optimistic concurrency. EF Core can detect it by checking whether the database row changed after it was originally loaded. If the row has changed, SaveChanges or SaveChangesAsync throws a DbUpdateConcurrencyException.

In this lesson, we will configure a concurrency token on a Product entity, reproduce a conflict with two independent DbContext instances, and correct the flawed save flow using three strategies: notifying the user, reloading database values, and performing a controlled retry.

How optimistic concurrency works

When EF Core loads an entity, it keeps the original value of the concurrency token in the change tracker. During an update, EF Core includes that original value in the SQL WHERE clause.

UPDATE Products
SET Name = @p0,
    Price = @p1,
    Version = @p2
WHERE Id = @id
  AND Version = @originalVersion;

The update succeeds only if the version is still the same as the value originally read by the application. If another user has already changed the row, the version is different and the command affects zero rows. EF Core interprets this result as a concurrency conflict and throws DbUpdateConcurrencyException.

This mechanism does not prevent two users from reading the same record. Instead, it prevents the later save from overwriting the earlier change without detection.

Configuring a concurrency token for Product

For this example, use a Guid property to represent the product version. The application will generate a new GUID after a successful logical update and EF Core will compare the original value during the save.

public sealed class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public int Stock { get; set; }

    public Guid Version { get; set; }
}

Configure the property with the Fluent API:

public sealed class AppDbContext : DbContext
{
    public DbSet<Product> Products => Set<Product>();

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>()
            .Property(product => product.Version)
            .IsConcurrencyToken();
    }
}

This tells EF Core that Version must be included in concurrency checks. Because this example uses an application-managed token, the service layer should assign a new value whenever the product is successfully modified.

Initial values and migration

A newly inserted product needs an initial version value. It can be created in application code or in the entity constructor:

var product = new Product
{
    Name = "Mechanical Keyboard",
    Price = 89.90m,
    Stock = 25,
    Version = Guid.NewGuid()
};

context.Products.Add(product);
await context.SaveChangesAsync();

After changing the model, create and apply a migration:

dotnet ef migrations add AddProductConcurrencyVersion
dotnet ef database update

If the migration does not provide a valid value for existing products, inspect both the migration and the database column definition. In production, prefer creating a new corrective migration instead of manually rewriting an already-applied migration.

Reproducing a conflict with two contexts

To reproduce a real conflict, read the same product through two independent contexts. Do not use one DbContext instance for parallel operations. Each context in this example represents a separate user request.

await using var context1 = await factory.CreateDbContextAsync();
await using var context2 = await factory.CreateDbContextAsync();

var product1 = await context1.Products
    .SingleAsync(product => product.Id == 1);

var product2 = await context2.Products
    .SingleAsync(product => product.Id == 1);

product1.Price = 110m;
product1.Version = Guid.NewGuid();
await context1.SaveChangesAsync();

product2.Price = 120m;
product2.Version = Guid.NewGuid();

await context2.SaveChangesAsync();

The second SaveChangesAsync call throws an exception because context2 loaded the product with the old version. Once context1 saved its update, the version stored in the database changed.

Catching the exception

try
{
    product2.Price = 120m;
    product2.Version = Guid.NewGuid();

    await context2.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    Console.WriteLine("The product was changed by another user.");
    Console.WriteLine($"Affected entities: {ex.Entries.Count}");
}

Catching the exception is only the first step. The application must explain the failure, load current database values, and apply a policy that is appropriate for the business operation.

Solution 1: Database wins and the user is notified

For manual editing screens, the safest default is often to avoid overwriting the other user's change automatically. Reload the current row, compare the submitted values with the database values, and ask the user to decide what to do.

try
{
    product.Price = requestedPrice;
    product.Version = Guid.NewGuid();

    await context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    var entry = ex.Entries.Single();
    var databaseValues = await entry.GetDatabaseValuesAsync();

    if (databaseValues is null)
    {
        return UpdateResult.Failed("The product no longer exists.");
    }

    var currentDatabaseProduct =
        (Product)databaseValues.ToObject();

    return UpdateResult.Conflict(
        currentDatabaseProduct,
        "The product was updated by another user.");
}

The UI can show the original value, the submitted value and the current database value. The user can accept the newer value or intentionally apply the change again after reviewing the conflict.

Solution 2: Database-wins behavior with Reload

Some workflows always prioritize the database value. For example, if stock is controlled by a central inventory process, the application may reload the current entity after a conflict.

try
{
    product.Stock = requestedStock;
    product.Version = Guid.NewGuid();

    await context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    foreach (var entry in ex.Entries)
    {
        await entry.ReloadAsync();
    }

    var freshProduct = await context.Products
        .AsNoTracking()
        .SingleAsync(product => product.Id == productId);

    return UpdateResult.Conflict(
        freshProduct,
        "The record changed. Current values were reloaded.");
}

ReloadAsync replaces the tracked entity values with values from the database. Because this discards pending user changes, the application should not do it silently on a user-facing form.

Solution 3: Controlled retry and merge

For automated operations, it may be appropriate to reload the current row and apply the operation again. However, retrying must have a strict limit and should reflect the business operation.

public async Task<Product> IncreaseStockAsync(
    int productId,
    int amount,
    CancellationToken cancellationToken)
{
    const int maxAttempts = 3;

    for (var attempt = 1; attempt <= maxAttempts; attempt++)
    {
        await using var context = await factory
            .CreateDbContextAsync(cancellationToken);

        var product = await context.Products
            .SingleAsync(p => p.Id == productId, cancellationToken);

        product.Stock += amount;
        product.Version = Guid.NewGuid();

        try
        {
            await context.SaveChangesAsync(cancellationToken);
            return product;
        }
        catch (DbUpdateConcurrencyException) when (attempt < maxAttempts)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(50 * attempt),
                cancellationToken);
        }
    }

    throw new InvalidOperationException(
        "The product update failed after the allowed retries.");
}

This example applies an increment operation rather than blindly assigning an absolute stock value. Each attempt reads the latest product and applies the increment again. Automatic merging may be safe for some additive operations, but it can be dangerous for fields such as price where a user must explicitly approve the final value.

Common mistakes

  • Defining a token but never changing it: With an application-managed token, assign a new value as part of every successful update.
  • Swallowing the exception: An empty catch block hides the conflict and leaves the user with an incorrect assumption about the saved data.
  • Retrying forever: A constantly changing row can produce an infinite loop, excessive load and unacceptable latency.
  • Using client-wins everywhere: Old client data may overwrite an important change made by another user.
  • Keeping a context alive for too long: Long-lived contexts may attempt to save using very old original values. A short-lived context per operation or request is usually easier to reason about.
  • Losing the original token in detached updates: If an API update model does not carry the version that the user originally read, the server cannot reliably detect the conflict.
  • Confusing concurrency with transactions: A concurrency token detects overwrites between operations. A transaction is still required when multiple database actions must be atomic.

Practice exercise

  1. Add a Guid property named Version to the Product entity and configure it with IsConcurrencyToken().
  2. Create a migration and update the database.
  3. Create two independent contexts and load the same product through both.
  4. Update the price through the first context and save it.
  5. Attempt to save the old version through the second context and catch DbUpdateConcurrencyException.
  6. Use GetDatabaseValuesAsync to return a conflict result containing current database values.
  7. Implement a stock-increase method that retries no more than three times.

Extend the exercise by displaying the original value, the submitted value and the current database value in a conflict DTO. Decide which fields can be merged automatically and which fields require explicit user confirmation.

Conclusion

Optimistic concurrency is a practical way to prevent silent data loss without locking every record while users are editing. EF Core places the original concurrency token in the update condition and throws DbUpdateConcurrencyException when the expected version is no longer present.

A robust solution catches the exception, identifies the affected entry, reads the current database values and applies a business-appropriate resolution policy. Manual edits should usually notify the user, while automated operations may use a bounded retry and carefully designed merge logic. This produces a clearer and more reliable data-access flow for production applications.

Sources