📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do ETags and conditional requests work in an HTTP API? Explain strong vs weak ETags, If-None-Match with 304 Not Modified for caching, and If-Match with 412 Precondition Failed for optimistic concurrency, and show how you would back an ETag with a SQL Server rowversion in ASP.NET Core.

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.

Mid-Level Theory Intermediate conditional-requests ef-core etags optimistic-concurrency rowversion web-api

🎯 Key points

  • An ETag is an opaque validator for one representation of a resource (RFC 9110): one mechanism serving both caching and concurrency
  • Strong ETag = byte-identical; weak (W/"...") = semantically equivalent; If-Match needs strong comparison
  • GET with If-None-Match: 304 Not Modified with no body when the ETag matches (bandwidth, and server work if the check is cheap)
  • PUT/PATCH/DELETE with If-Match: 412 Precondition Failed when the resource changed (lost update prevention)
  • 428 Precondition Required (RFC 6585) when the API demands If-Match and it is missing
  • Back the ETag with rowversion: EF Core IsRowVersion, set OriginalValue, DbUpdateConcurrencyException -> 412
  • Design the 412 experience: the client re-reads, shows what changed and lets the user merge or retry
  • ASP.NET Core doesn't add ETags to API responses for you (static files and output cache are exceptions)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"An ETag is a validator: the server says 'this is version X of this resource' in the ETag header, and the client can later say 'only do this if it's still version X'. There are two uses. For reads, the client sends If-None-Match with 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 sends If-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 rowversion column. SQL Server changes it on every update, EF Core maps it with IsRowVersion() 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 from If-Match, so EF Core adds WHERE RowVersion = @original to the UPDATE. If no row is affected, EF throws DbUpdateConcurrencyException, which I map to 412. If the client didn't send If-Match at 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."


Conditional headers

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 vs weak

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

Production example

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%.

🔍 What the interviewer is checking

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

  • Explains the lost update problem and how If-Match prevents it
  • Correct status codes: 304, 412, 428
  • Knows strong vs weak comparison rules
  • Sets OriginalValue from the client's ETag with rowversion
  • Describes how the client handles a 412 for the user, and notes that hashing the body saves bandwidth, not server work

Red flags

  • Thinks ETags are only for browser caching
  • Compares against the freshly loaded version
  • Uses 409 or 400 for failed preconditions

📚 Learn in depth

1. The lost update problem

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.

2. Validators in RFC 9110

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.

3. rowversion

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.

4. ETags for representations, not rows

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).

5. Where ASP.NET Core helps

  • Static files middleware sends ETags and handles If-None-Match automatically.
  • Output caching stores ETags you set and can answer If-None-Match with 304 from the cache.
  • MVC and Minimal APIs don't generate ETags for your endpoints: you set Response.Headers.ETag and check Request.Headers.IfMatch / IfNoneMatch yourself, usually in a small helper or endpoint filter.

6. Client behaviour

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.

Try it yourself

  1. Run the example, curl -i a case, then repeat with -H 'If-None-Match: "<etag>"' and confirm the 304.
  2. Open two terminals, GET the same case, PUT from both with the original ETag; the second gets 412.
  3. Omit If-Match and confirm the 428.
  4. Capture the UPDATE statement with EF Core logging and look at the WHERE clause.
  5. In SSMS, update the row directly and watch the rowversion change.

💻 Code

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();
        });
    }
}

⚠ Common mistakes

  • Mistake: Accepting writes without 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.
  • Mistake: Loading the entity and letting EF compare against the freshly loaded rowversion. Why it is wrong: the check passes even if the client's copy is stale. Instead: set OriginalValue to the version from If-Match.
  • Mistake: Returning 409 for a failed precondition. Why it is wrong: RFC 9110 defines 412 for a failed If-Match, and generic clients rely on it. Instead: 412 for precondition failure, 409 for business-state conflicts.
  • Mistake: Surfacing a 412 to users as a generic "Save failed" error. Why it is wrong: the user loses their typed changes and doesn't know why; they retry blindly or give up, and concurrency control gets blamed as a bug. Instead: on 412 the client re-reads the resource, shows what the other person changed next to the user's edits, and lets them merge and resubmit with the new ETag; ProblemDetails can say who changed it and when.
  • Mistake: Hashing the full response to build an ETag and calling it a performance feature. Why it is wrong: the expensive work already happened; only bandwidth is saved. Instead: derive ETags from cheap version data.
  • Mistake: Using a weak ETag with If-Match. Why it is wrong: weak validators never match under strong comparison, so every write fails. Instead: use strong ETags for concurrency.
  • Mistake: Forgetting to expose ETag in CORS. Why it is wrong: browser JavaScript can't read it, so the SPA can't send If-Match. Instead: WithExposedHeaders("ETag").
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions setting OriginalValue on the EF Core entry Why: Checks depth on the EF Core Entry API and concurrency tokens
    How to answer

    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).

  2. When: Candidate refers to RFC 9110 headers and status codes Why: Checks broader HTTP semantics knowledge
    How to answer

    HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.

    • Methods: 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.
    • Status codes: 2xx success, 3xx redirect/not modified, 4xx client error (400, 401 vs 403, 404, 409, 422, 429), 5xx server error (500, and 502/503/504 usually from proxies or gateways).
    • Headers: Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.
    • Versions: HTTP/1.1 is text with one request at a time per connection; HTTP/2 is binary with multiplexed streams and header compression on one TCP connection; HTTP/3 does the same over QUIC/UDP, removing TCP head-of-line blocking.
  3. When: Candidate uses both status codes Why: Checks precise status code semantics
    How to answer

    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.

🛠 Real-world problems: how you handle them

Two staff overwrite each other's case notes
Situation
A [case management API] with an Angular front end used by [300] staff; cases are often edited by a case worker and a supervisor at the same time.
Signals
Complaints that notes or status changes 'disappeared', about [15] a week; audit log showing two PUTs on the same case seconds apart with the second containing stale fields.
Investigation
Compared temporal table history for affected cases to see overwritten values, traced both PUTs in Application Insights, and confirmed the API used last-write-wins with full-object PUT and no concurrency token.
Resolution
Added a rowversion column and EF Core concurrency token, ETags on GET, required If-Match on PUT with 428 when missing and 412 on mismatch, exposed ETag through CORS, and built a UI dialog showing the other user's changes on 412.
Prevention
Integration tests for concurrent updates, a contract test asserting 428 without If-Match, API guidelines requiring ETags on shared editable resources, and a dashboard of 412 rates per endpoint.

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%].

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me