ETags and conditional requests: strong vs weak validators, If-None-Match and 304 for bandwidth, If-Match, 412 and 428 for optimistic concurrency, and mapping a SQL Server rowversion through EF Core to ETag headers.
An ETag is an opaque version identifier for a representation of a resource, returned in the ETag header. Clients send it back in conditional requests. On a GET, If-None-Match lets the server answer 304 Not Modified with no body when nothing changed, saving bandwidth. On a PUT, PATCH or DELETE, If-Match makes the write conditional: if someone else changed the resource since the client read it, the server returns 412 Precondition Failed instead of silently overwriting their change (the lost update problem). A SQL Server rowversion column, mapped with EF Core's IsRowVersion, makes a natural strong ETag. The trade-off: clients must read before they write and handle 412 by refreshing and retrying.
"An ETag is a validator: the server says 'this is version X of this resource' in the
ETagheader, and the client can later say 'only do this if it's still version X'. There are two uses. For reads, the client sendsIf-None-Matchwith the ETag it has cached; if it still matches, I return 304 Not Modified with no body, so a 50 KB product document becomes a few hundred bytes. For writes, the client sendsIf-Match; if the resource has changed since they read it, I return 412 Precondition Failed. That's optimistic concurrency over HTTP, and it prevents the lost update where two staff edit the same record and the second save silently wipes the first.In .NET the natural backing is a SQL Server
rowversioncolumn. SQL Server changes it on every update, EF Core maps it withIsRowVersion()as a concurrency token, and I base64-encode it as a strong ETag. On a PUT, I set the entity's original row version to the value fromIf-Match, so EF Core addsWHERE RowVersion = @originalto the UPDATE. If no row is affected, EF throwsDbUpdateConcurrencyException, which I map to 412. If the client didn't sendIf-Matchat all on an endpoint where conflicts matter, I return 428 Precondition Required.The mistake I see is generating ETags by hashing the response body after doing all the work. That still gives a 304 and saves bandwidth, but the database query and serialisation have already happened. If the goal is to save server work, the ETag has to come from something cheap, such as a row version or a last-modified value I can check without building the response."
| Request header | Typical method | Match -> | No match -> |
|---|---|---|---|
If-None-Match: "abc" |
GET, HEAD | 304 Not Modified | 200 with body and new ETag |
If-Match: "abc" |
PUT, PATCH, DELETE | Perform the write, 200/204 with new ETag | 412 Precondition Failed |
If-None-Match: * |
PUT (create only) | 412 if it already exists | Create |
If-Modified-Since / If-Unmodified-Since |
GET / writes | Date-based equivalents, 1-second precision |
Strong "abc" |
Weak W/"abc" |
|
|---|---|---|
| Meaning | Byte-for-byte identical | Semantically equivalent (e.g. gzip vs identity) |
If-None-Match |
Weak comparison allowed | Allowed |
If-Match |
Strong comparison required | Never matches |
In a [case management API] used by [300] staff, two users editing the same case lost changes about [15] times a week. Adding a rowversion-backed ETag and requiring If-Match on PUT turned silent overwrites into 412 responses that the UI handled with a "this case changed, review the differences" dialog; lost-update complaints went to zero, and 304s on the case list cut response bandwidth by about 40%.
Checks whether the candidate understands conditional requests as one mechanism that gives an API both efficient caching and safe concurrent updates, and can implement them with EF Core and design how clients and users handle conflicts.
Green flags
Red flags
Alice: GET /cases/7 (status=Open, notes="A") ETag "v1"
Bob: GET /cases/7 (status=Open, notes="A") ETag "v1"
Alice: PUT /cases/7 notes="A + Alice" -> 200, ETag "v2"
Bob: PUT /cases/7 status=Closed, notes="A" -> without If-Match: Alice's note lost
-> with If-Match "v1": 412
Pessimistic locking (holding a DB lock while a user edits) doesn't work over stateless HTTP; optimistic concurrency checks at write time.
An ETag is an opaque quoted string; clients must not parse it. The server chooses what it encodes: a rowversion, a hash, a version number. Last-Modified is the older date-based validator with 1-second resolution, too coarse for busy resources.
rowversion is an 8-byte, database-wide, monotonically increasing value that SQL Server updates automatically on every row change. It is not a timestamp. EF Core:
UPDATE Cases SET Notes = @p0
WHERE Id = @p1 AND RowVersion = @p2; -- @p2 = OriginalValue from If-Match
SELECT RowVersion FROM Cases WHERE @@ROWCOUNT = 1 AND Id = @p1;
Zero rows affected -> DbUpdateConcurrencyException. On Azure SQL and SQL Server this is the cheapest correct concurrency token.
If a response combines several rows (a case plus its notes), a single row's rowversion isn't enough: hash the relevant versions together, or keep a version on the aggregate root that every child change bumps. A projection that hides fields can use the same ETag only if the hidden fields don't change the representation; otherwise ETags differ per representation (and Vary matters for caches).
If-None-Match automatically.If-None-Match with 304 from the cache.Response.Headers.ETag and check Request.Headers.IfMatch / IfNoneMatch yourself, usually in a small helper or endpoint filter.Browsers handle If-None-Match automatically for cached GETs. API clients must store ETags and send If-Match explicitly; on 412 they re-GET, show or merge differences, and retry. CORS: expose the header with WithExposedHeaders("ETag") or browser JavaScript can't read it.
curl -i a case, then repeat with -H 'If-None-Match: "<etag>"' and confirm the 304.If-Match and confirm the 428.A rowversion-backed ETag with 304 on reads, 412/428 on writes:
using Microsoft.EntityFrameworkCore;
namespace Cases;
public sealed class Case
{
public int Id { get; set; }
public required string Status { get; set; }
public string Notes { get; set; } = "";
public byte[] RowVersion { get; set; } = [];
}
public sealed record CaseDto(int Id, string Status, string Notes);
public sealed record UpdateCase(string Status, string Notes);
public sealed class CasesDb(DbContextOptions<CasesDb> options) : DbContext(options)
{
public DbSet<Case> Cases => Set<Case>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Case>().Property(c => c.RowVersion).IsRowVersion(); // SQL Server rowversion, concurrency token
}
public static class CaseEndpoints
{
private static string ToETag(byte[] rowVersion) => $"\"{Convert.ToBase64String(rowVersion)}\"";
public static void MapCases(this WebApplication app)
{
app.MapGet("/cases/{id:int}", async (int id, HttpContext http, CasesDb db, CancellationToken ct) =>
{
// Cheap check first: read only the version.
var version = await db.Cases.Where(c => c.Id == id).Select(c => c.RowVersion).SingleOrDefaultAsync(ct);
if (version is null) return Results.NotFound();
string etag = ToETag(version);
http.Response.Headers.ETag = etag;
if (http.Request.Headers.IfNoneMatch.Contains(etag))
return Results.StatusCode(StatusCodes.Status304NotModified); // no body, no full query
var dto = await db.Cases.AsNoTracking().Where(c => c.Id == id)
.Select(c => new CaseDto(c.Id, c.Status, c.Notes)).SingleAsync(ct);
return Results.Ok(dto);
});
app.MapPut("/cases/{id:int}", async (int id, UpdateCase body, HttpContext http, CasesDb db, CancellationToken ct) =>
{
string? ifMatch = http.Request.Headers.IfMatch.FirstOrDefault();
if (string.IsNullOrEmpty(ifMatch))
return Results.Problem("Send If-Match with the ETag you last read.", statusCode: 428);
var entity = await db.Cases.SingleOrDefaultAsync(c => c.Id == id, ct);
if (entity is null) return Results.NotFound();
byte[] clientVersion;
try { clientVersion = Convert.FromBase64String(ifMatch.Trim('"')); }
catch (FormatException) { return Results.Problem("Invalid ETag.", statusCode: 412); }
// Make EF compare against the version the CLIENT saw, not the one we just loaded.
db.Entry(entity).Property(c => c.RowVersion).OriginalValue = clientVersion;
entity.Status = body.Status;
entity.Notes = body.Notes;
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException)
{
return Results.Problem("The case was changed by someone else. Reload and try again.", statusCode: 412);
}
http.Response.Headers.ETag = ToETag(entity.RowVersion);
return Results.NoContent();
});
}
}
If-Match on resources several people edit. Why it is wrong: last write wins and changes disappear silently. Instead: require If-Match and return 428 when it is missing.OriginalValue to the version from If-Match.If-Match, and generic clients rely on it. Instead: 412 for precondition failure, 409 for business-state conflicts.If-Match. Why it is wrong: weak validators never match under strong comparison, so every write fails. Instead: use strong ETags for concurrency.ETag in CORS. Why it is wrong: browser JavaScript can't read it, so the SPA can't send If-Match. Instead: WithExposedHeaders("ETag").Last-Modified alone for concurrency. Why it is wrong: its 1-second precision misses two updates within the same second. Instead: use an ETag backed by rowversion or a version number.I treat If-Match as the HTTP face of the same optimistic concurrency the database already supports. The win is that conflicts become explicit and the client decides what to do, instead of the server silently picking a winner. Not every resource needs it: append-only or single-owner resources can skip it, while anything edited by several people, or by both a human and an automated process, should require it.
For read caching, the value of 304 depends on how cheap the version check is. With a rowversion lookup on the primary key it's a sub-millisecond seek; with a hash of a 30-table report it isn't. Measure response bytes and server time per endpoint in Application Insights before and after.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| rowversion ETag + If-Match required | Shared, editable resources | Clients must handle 412 and 428 | Append-only data, single-writer resources |
| Last-write-wins | Low-value data, single editor | Silent data loss | Anything people edit together |
| Pessimistic lock (check-out) | Long edits that must not conflict, e.g. legal documents | Stale locks, lock timeouts | Most web APIs |
| Body-hash ETag for 304 only | Large, rarely changing responses where bandwidth matters | Full server work per request | When server CPU or DB is the bottleneck |
db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:
State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).
HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.
GET/HEAD/OPTIONS are safe; GET, PUT, DELETE are idempotent (repeating has the same effect); POST and usually PATCH are not, so retries need an idempotency key.Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.412 means a precondition the client sent (If-Match, If-Unmodified-Since, If-None-Match on a write) evaluated false: the resource isn't in the version the client expected. 409 means the request conflicts with the current state for a business reason regardless of version, such as cancelling an already-shipped order or creating a username that exists. A client handles 412 by re-reading and retrying; it handles 409 by changing the request.
How to tell it (STAR)
**S:** At [company], staff kept losing edits to cases when two people worked on the same one, about [15] times a week. **T:** I had to stop silent overwrites without adding locking that would get in people's way. **A:** Using temporal table history I proved they were lost updates from last-write-wins PUTs. I added a rowversion-backed ETag, made PUT require If-Match, returned 412 on a mismatch and 428 when it was missing, and worked with the front-end team on a dialog that showed what had changed. **R:** Lost-update complaints went to [zero], and as a bonus 304 responses cut bandwidth on the case list by about [40%].
Last updated 23 Nov 2026.