Optimistic Concurrency with ETags in ASP.NET Core
On this page
Learning Objective
Explain the lost update problem in a shared API, implement optimistic concurrency with ETags and the If-Match header, return the correct 412 and 428 responses, and handle the ETag header correctly from a cross-origin React client.
Concept Explanation
A frontend developer rarely worries about two people editing the same thing, because state lives in one tab. A server always has to. Imagine two users open the same note. Both read version 1. Alice saves a new title; Bob, working from stale data, saves a change to the body. If the server simply overwrites the whole record with each request, Bob's save silently erases Alice's change. This is the lost update problem, and it is not exotic: it happens whenever users, browser tabs, or background jobs edit the same record. The two classic solutions are pessimistic locking, where the first editor blocks everyone else, and optimistic concurrency, where everyone proceeds but the server detects conflicts at save time.
Optimistic concurrency fits HTTP well because HTTP already has the vocabulary. When the server returns a resource, it includes an ETag header, an opaque token identifying that exact version of the representation. When the client wants to update, it sends the token back in an If-Match header, meaning apply this change only if the resource still has this version. If the version still matches, the update proceeds and the response carries a new ETag. If someone else changed it in the meantime, the server refuses with 412 Precondition Failed and the client can reload, show a merge dialog, or ask the user. The behavior is defined in the core HTTP specification, RFC 9110, so standard clients and proxies understand it.
Two refinements make the system robust. First, require the header: an update sent without If-Match should be rejected with 428 Precondition Required, otherwise a careless or malicious client can skip the check and overwrite freely. Second, generate the ETag from a version that actually changes on every write, such as an integer counter, a row version column in the database, or a hash of the content. Do not derive it from just the last modified time, whose resolution can miss two quick edits. In Phase 4 you will see SQL Server's rowversion column and Entity Framework's concurrency tokens do exactly this at the database layer.
There is a cross-origin trap that catches nearly every full-stack developer once. When the React app on one origin calls the API on another, browser JavaScript can only read a few safelisted response headers, and ETag is not one of them. Your fetch code will see null for response.headers.get of ETag unless the server lists it in Access-Control-Expose-Headers. If you serve the API from the same origin through a proxy or the backend-for-frontend pattern of Day 46, the issue disappears, but whenever CORS is involved you must expose the header explicitly. The same goes for Location, Retry-After, and any custom header your client reads.
| Element | Role | Notes |
|---|---|---|
| ETag response header | Identifies the current version | Quoted opaque string, for example "7" |
| If-Match request header | Conditional update | Update only if the version still matches |
| 412 Precondition Failed | Version mismatch | Client must reload and retry or merge |
| 428 Precondition Required | Header missing | Forces clients to participate in the protocol |
| Access-Control-Expose-Headers | Lets browser JS read ETag | Required for cross-origin fetch |
| Database rowversion | Backing token in SQL Server | Covered in Day 37 |
Worked Example: A Versioned Note Update, End to End
The server keeps a Version integer on each note, returns it as an ETag, and enforces If-Match on updates. The React function reads the ETag from the GET and sends it back with the PUT.
public sealed class NoteEntity
{
public int Id { get; init; }
public string Title { get; set; } = "";
public string? Body { get; set; }
public int Version { get; set; } = 1; // incremented on every successful write
}
static string ETagFor(NoteEntity n) => $"\"{n.Version}\""; // strong ETag, quoted per the spec
app.MapGet("/api/notes/{id:int}", (int id, INoteStore store, HttpResponse res) =>
{
if (store.Find(id) is not { } note) return Results.NotFound();
res.Headers.ETag = ETagFor(note);
return Results.Ok(NoteDto.From(note));
});
app.MapPut("/api/notes/{id:int}", (int id, UpdateNoteRequest body, INoteStore store,
HttpRequest req, HttpResponse res) =>
{
var ifMatch = req.Headers.IfMatch.ToString();
if (string.IsNullOrEmpty(ifMatch))
return Results.Problem("If-Match header is required.", statusCode: StatusCodes.Status428PreconditionRequired);
lock (store.SyncRoot(id)) // a per-id lock object from the store: check and write must be one atomic step
{
if (store.Find(id) is not { } note) return Results.NotFound();
if (ifMatch != ETagFor(note))
return Results.Problem("The note was changed by someone else. Reload and try again.",
statusCode: StatusCodes.Status412PreconditionFailed);
note.Title = body.Title.Trim();
note.Body = body.Body;
note.Version++;
res.Headers.ETag = ETagFor(note);
return Results.Ok(NoteDto.From(note));
}
});
// Cross-origin: let browser JavaScript read the ETag header.
builder.Services.AddCors(o => o.AddPolicy("spa", p => p
.WithOrigins("https://app.example.com")
.WithMethods("GET", "PUT", "POST", "DELETE")
.WithHeaders("Content-Type", "If-Match", "Authorization")
.WithExposedHeaders("ETag", "Location")));// React client: remember the ETag from the read, send it back on the write.
async function loadNote(id: number) {
const res = await fetch(`/api/notes/${id}`);
const etag = res.headers.get('ETag'); // null unless exposed via CORS
return { note: await res.json(), etag };
}
async function saveNote(id: number, etag: string, changes: { title: string; body: string }) {
const res = await fetch(`/api/notes/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'If-Match': etag },
body: JSON.stringify(changes),
});
if (res.status === 412) throw new ConflictError(); // prompt the user to reload or merge
return res.json();
}In the real database version, the lock and version increment collapse into one conditional UPDATE statement or Entity Framework's built-in concurrency token, which is both safer and works across multiple server instances. The in-memory lock only protects a single process.
Real-World Examples
- Azure Cosmos DB and Azure Blob Storage both use ETags with If-Match for optimistic concurrency: a write carrying a stale ETag is rejected with a 412 status, and the Azure SDKs expose this as a condition option on update calls. It is the same pattern in the same protocol you are implementing, applied by the cloud platform you will deploy to later in this course.
- The GitHub REST API for updating repository file contents requires the current blob SHA of the file in the request, and returns a conflict error when the file has changed since that SHA was read. The design prevents a client from overwriting someone else's commit with a stale copy, using a version token in place of an ETag header.
Review Questions & Answers
Two clients read the same version of a record and each saves changes based on it; the later save overwrites the earlier one without knowing about it. Each client behaved correctly in isolation, but the server accepted a write based on stale data. Any system with more than one editor, including two browser tabs of the same person, is exposed.
If the header is optional, any client that omits it bypasses concurrency protection and can overwrite newer data, whether by accident or by design. Responding with 428 Precondition Required makes participation in the protocol mandatory, so every writer must prove which version it read. It turns an easy-to-forget convention into an enforced rule.
Cross-origin responses only expose a small safelist of headers to JavaScript, and ETag is not on it. The API must send Access-Control-Expose-Headers listing ETag, which in ASP.NET Core is done with WithExposedHeaders in the CORS policy. The network tab shows the raw response, but the fetch API applies the CORS filtering.
Timestamps have limited resolution, so two edits within the same tick can produce identical values and a stale writer would wrongly pass the check. They are also affected by clock differences across servers. A counter or database row version changes on every write without ambiguity.