Back to all posts
·8 min read

Optimistic concurrency in EF Core: preventing lost updates with versions and ETags

Two people open the same product in an admin panel at the same time. One corrects the price and saves. A few minutes later the other fixes a typo in the description and saves. Because the old price is still on their screen, the second save writes the price back to its old value. No error occurs, the logs are clean, the tests are green. One change simply disappears without a trace.

This problem is called a "lost update", and most CRUD applications have it by default. In this post I describe how to make it visible with EF Core and ASP.NET Core: keep a version value in the database, check that version when saving, and carry the same version to the client over HTTP.

Why lost updates go unnoticed

A typical update flow has three steps: read the record, show it to the user, update the record with the values the user sends back. The problem is the time between the first and the third step. In a web application that can be minutes rather than seconds; the user may leave the form open and go get a coffee.

From the database's point of view both UPDATE statements are perfectly valid. Transactions do not help either, because the read and the write do not happen in the same transaction but in separate HTTP requests. So the problem is not the database; it is that the application never asks "is the data the user saw still current?"

Checking the version instead of locking

There are two classic answers to that question. The pessimistic approach locks the record for the duration of the edit, so nobody else can write. In web applications this is usually a poor choice: it is unclear who releases the lock and when, and a user who closes the browser tab can leave it held.

The optimistic approach assumes conflicts are rare. It blocks nobody; instead, when saving, it checks "is the version I read still the latest one?" The check is done with a single conditional statement:

UPDATE Products
SET Name = @name, Price = @price
WHERE Id = @id AND RowVersion = @originalRowVersion;

If the number of affected rows is zero, someone else changed the record in the meantime. Because the check and the write happen in a single atomic operation, no race window is left in between.

Defining a concurrency token in EF Core

EF Core generates this condition for you; all you have to do is mark a property as a concurrency token. On SQL Server the most practical option is a rowversion column, which the database increments on every update by itself:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; } = [];
}

If you prefer the Fluent API, the same is done with builder.Property(p => p.RowVersion).IsRowVersion(). From then on, EF Core adds the RowVersion condition to every UPDATE and DELETE it generates for this entity.

Where the database does not generate versions automatically, as with some providers, you can manage the version in the application. Mark a Guid or integer property with IsConcurrencyToken() and assign a new value on every change. If you use PostgreSQL, the Npgsql provider supports using the xmin system column as a token; the provider's documentation for the version you use is the best reference.

Handling DbUpdateConcurrencyException

When the condition does not hold, EF Core throws DbUpdateConcurrencyException from SaveChangesAsync. This is not a bug but a decision point: the application now has to decide which of the two changes wins.

There is a common mistake here. If you load the record from the database in the same request and update it right away, the "original" version EF Core compares against is not the version the user saw when they opened the form, but the one this request has just read. The check then catches almost nothing. You need to supply the version the user saw explicitly as the original value:

db.Entry(product).Property(p => p.RowVersion).OriginalValue = clientVersion;

This single line decides whether optimistic concurrency actually works. It also matters that the check stays in the database statement rather than in the web layer; comparing two versions in application code still leaves the short race between read and write open.

Carrying the version to the client: ETag and If-Match

The version the user saw has to come from somewhere. HTTP offers a ready-made mechanism: in the GET response the server sends the resource's version in the ETag header, and when updating, the client sends the same value back in the If-Match header. If the versions do not match, the server returns 412 Precondition Failed. Returning 428 Precondition Required when the client sends no header at all rules out unconditional updates from the start.

app.MapPut("/products/{id:int}", async (
    int id, UpdateProductRequest request, HttpContext http, AppDbContext db) =>
{
    var ifMatch = http.Request.Headers.IfMatch.ToString();
    if (string.IsNullOrEmpty(ifMatch))
        return Results.Problem(statusCode: StatusCodes.Status428PreconditionRequired,
            title: "An If-Match header is required for updates.");

    if (!ETag.TryParse(ifMatch, out var clientVersion))
        return Results.Problem(statusCode: StatusCodes.Status400BadRequest,
            title: "The If-Match value is invalid.");

    var product = await db.Products.FindAsync(id);
    if (product is null) return Results.NotFound();

    db.Entry(product).Property(p => p.RowVersion).OriginalValue = clientVersion;
    product.Name = request.Name;
    product.Price = request.Price;

    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        return Results.Problem(statusCode: StatusCodes.Status412PreconditionFailed,
            title: "The record changed while you were editing it. Reload it and try again.");
    }

    http.Response.Headers.ETag = ETag.From(product.RowVersion);
    return Results.NoContent();
});

static class ETag
{
    public static string From(byte[] version) => $"\"{Convert.ToBase64String(version)}\"";

    public static bool TryParse(string value, out byte[] version)
    {
        version = [];
        if (value.Length < 2 || value[0] != '"' || value[^1] != '"') return false;
        try { version = Convert.FromBase64String(value[1..^1]); return true; }
        catch (FormatException) { return false; }
    }
}

After SaveChangesAsync succeeds, EF Core reads the new RowVersion generated by the database back into the entity, so the ETag written to the response is always the new version. The client can store it and use it for the next update.

If you would rather not use HTTP headers, you can also carry the version as a field in the request body. In that case returning 409 Conflict for a mismatch is more common. What matters is not the mechanism itself, but that the version travels to the client and comes back.

What to do when a conflict happens

Catching the conflict is half the job; what to show the user is a separate design decision. There are three common strategies:

  • Leave it to the client: The simplest, and enough for most admin screens. You tell the user the record has changed, load the current data and ask them to reapply their changes. Showing the changed fields highlighted, without wiping the values in the form, makes the experience noticeably better.
  • Retry on the server: Suitable for operations that do not depend on user input, for example a background job updating a status field. You reload the entity, apply the rule again and retry a limited number of times. Through DbUpdateConcurrencyException.Entries you can reach the current database values with GetDatabaseValuesAsync.
  • Merge per field: If two users changed different fields, keep both. It sounds attractive, but knowing which fields are independent of each other requires business rules. Choose it only when there is a real need.

"Last writer wins" is also a legitimate strategy when chosen deliberately. The problem is when this behaviour happens unnoticed as the default.

Limits and things to watch for

Optimistic concurrency does not solve everything. A few points are worth knowing:

  • Bulk updates do not check the token. ExecuteUpdateAsync and ExecuteDeleteAsync bypass the change tracker, so they do not add the version condition on their own. If you need it, write the condition into Where yourself and check the returned number of affected rows.
  • Counters are better served by atomic updates. For operations such as decrementing stock or incrementing a view count, a single statement like SET Stock = Stock - 1 WHERE Stock > 0 gives the correct result without producing conflicts, instead of read-modify-write.
  • A version protects a single row, not an aggregate. For data that must stay consistent together, such as an order and its order lines, you also need to bump the root entity's version on every child change.
  • A high conflict rate is a design signal. If the same record conflicts constantly, the problem is not concurrency control but how the data is partitioned.

Closing

Lost updates are among the data corruptions noticed last, because they produce no errors. The good news is that the countermeasures are small: a version column, supplying the correct original value when saving, and carrying that version to the client with an ETag. Once these three pieces are in place, "who overwrote what" stops being silent data loss and becomes a situation the application handles explicitly. And the question to ask yourself when writing a new update endpoint is simple: what should happen if the record changes after the user has opened this form?