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

📚 Interview question

Show how you implement optimistic concurrency in EF Core. Use a RowVersion or a concurrency token, explain the SQL EF Core sends, handle DbUpdateConcurrencyException with a client-wins, store-wins or merge strategy, and return the right HTTP response from an API.

Covers EF Core optimistic concurrency: [Timestamp]/IsRowVersion on SQL Server rowversion, app-managed concurrency tokens with IsConcurrencyToken, the UPDATE ... WHERE RowVersion = @original pattern, setting OriginalValue from the client, DbUpdateConcurrencyException with GetDatabaseValuesAsync and store-wins/client-wins/merge resolution, concurrency with ExecuteUpdate, and mapping to 409 or ETag/If-Match with 412.

Mid-Level Coding Intermediate aspnet-core concurrency ef-core etag rowversion sql-server

🎯 Key points

  • Optimistic concurrency: no locks; detect conflicts at write time by checking a version in the WHERE clause
  • [Timestamp] byte[] / IsRowVersion maps to SQL Server rowversion, changed automatically on every update
  • IsConcurrencyToken on a normal property when the app manages the version (e.g. a Guid set on each save)
  • For UPDATE and DELETE of a tracked entity EF Core adds every configured token to the WHERE (Id = @id AND RowVersion = @original); 0 rows affected throws DbUpdateConcurrencyException
  • Across HTTP, send the version to the client and set it as the entity's OriginalValue on the way back
  • Resolve with ex.Entries and GetDatabaseValuesAsync: null means the row was deleted (404/410); otherwise store wins (reload), client wins (OriginalValues.SetValues) or merge
  • ExecuteUpdate doesn't use tokens automatically: include the version in Where and check rows affected
  • API: 409 Conflict for a stale body version, or ETag + If-Match with 412 Precondition Failed; 428 when If-Match is required but missing

⏱ 30-second answer

Optimistic concurrency assumes conflicts are rare: nobody holds locks, and each write checks that the row hasn't changed since it was read. On SQL Server, add a [Timestamp] byte[] RowVersion (IsRowVersion()), which the database updates on every write; or mark an app-managed property with IsConcurrencyToken(). EF Core then sends UPDATE ... WHERE Id = @id AND RowVersion = @original; zero rows affected throws DbUpdateConcurrencyException. In an API, send the version to the client (often as an ETag), and on the way back set it as the entity's OriginalValue. On conflict, choose store wins (reload and tell the user), client wins (overwrite) or a merge, and return 409 Conflict (or 412 for a failed If-Match). The trade-off: no blocking and good scalability, at the cost of handling conflicts explicitly.

🗣 Full answer (senior)

How I would answer this in an interview

"Optimistic concurrency is about lost updates. Two people load the same record, both edit it, and without a check the second save silently overwrites the first. Instead of locking the row while someone has it open, which doesn't work across HTTP anyway, I keep a version on the row and make every update conditional on it.

On SQL Server the easy way is a rowversion column: [Timestamp] public byte[] RowVersion. SQL Server bumps it on every update, so I never set it myself. EF Core puts the original value it loaded into the WHERE clause and adds OUTPUT INSERTED.RowVersion to get the new one. If the row changed, the WHERE matches nothing, EF sees zero rows affected and throws DbUpdateConcurrencyException. If I can't use rowversion, I mark any property with IsConcurrencyToken() and change it myself on every save, a Guid for example.

The part people get wrong is the disconnected case. The request that saves isn't the request that loaded. So the GET returns the version, often as an ETag header, and the PUT sends it back. I load the entity, then set Entry(e).Property(x => x.RowVersion).OriginalValue to the client's value. Setting the current value does nothing useful, because EF compares using the original. When the exception fires, ex.Entries gives me the entity; GetDatabaseValuesAsync() gives the current row. Then it's a business decision: store wins means reload and return 409 with the latest state; client wins means copy the database values into OriginalValues and save again; merge means applying non-overlapping field changes. With ETags I use If-Match and return 412 when it doesn't match. The mistake I see is catching the exception and retrying blindly. That's just a slower lost update."


Version strategies

Strategy Config Who changes it Notes
rowversion [Timestamp] or IsRowVersion() SQL Server, every update 8 bytes, unique per database; the default choice
App-managed token IsConcurrencyToken() on e.g. Guid Version Your code, every save Works on any provider; easy to forget to change
Column as token IsConcurrencyToken() on Status Normal edits Detects conflicts on that column only

Resolution options

Option What you do Use when
Store wins Reload, return 409 with current state Default for user edits
Client wins entry.OriginalValues.SetValues(dbValues), save again Last writer genuinely should win (rare)
Merge Compare proposed, original and database values per property Different fields edited, low risk

HTTP mapping

Situation Response
Version in body is stale 409 Conflict (ProblemDetails, current version)
If-Match ETag doesn't match 412 Precondition Failed
If-Match required but missing 428 Precondition Required

Production example

Adding rowversion checks to a [rostering] API surfaced [~30] conflicts a day that had been silent overwrites; the UI showed 'someone else changed this shift' with a diff, and complaints about 'disappearing changes' stopped.

🔍 What the interviewer is checking

Checks the candidate can implement optimistic concurrency end to end in an EF Core API, including the disconnected case and conflict handling.

Green flags

  • Explains the WHERE RowVersion = @original mechanism and zero-rows detection.
  • Sets the client's version as OriginalValue.
  • Handles the exception with a deliberate strategy and returns 409/412.
  • Knows ExecuteUpdate needs the check by hand.

Red flags

  • Relies on transactions or locks to prevent lost updates across HTTP.
  • Retries blindly on conflict.
  • Sets the version as the current value.

📚 Learn in depth

1. The race without a check

T1  Alice  GET shift 7 (Start 09:00)
T2  Bob    GET shift 7 (Start 09:00)
T3  Alice  PUT Start 08:00  -> UPDATE ... SET Start='08:00' WHERE Id=7
T4  Bob    PUT Notes='x'    -> UPDATE ... SET Start='09:00', Notes='x' WHERE Id=7   (Alice's change lost)

2. The SQL with rowversion

UPDATE [Shifts] SET [Start] = @p0
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p1 AND [RowVersion] = @p2;   -- @p2 = original value

EF checks the affected row count per statement in the batch. Zero means conflict, and the whole SaveChanges transaction rolls back. Deletes are checked too (DELETE ... WHERE Id AND RowVersion).

3. Original vs current values

Entry(shift).Property(s => s.RowVersion)
   OriginalValue  -> goes in WHERE      <- set the client's version HERE
   CurrentValue   -> ignored for rowversion (store-generated)

4. Inside DbUpdateConcurrencyException

catch (DbUpdateConcurrencyException ex)
{
    var entry = ex.Entries.Single();
    var proposed = entry.CurrentValues;               // what we tried to write
    var original = entry.OriginalValues;              // what we thought was there
    var database = await entry.GetDatabaseValuesAsync(ct); // what is there now (null if deleted)
}

A null from GetDatabaseValuesAsync means the row was deleted: return 404 or 410.

5. ExecuteUpdate

ExecuteUpdateAsync doesn't go through the change tracker, so tokens aren't added automatically:

var rows = await db.Shifts.Where(s => s.Id == id && s.RowVersion == version)
    .ExecuteUpdateAsync(s => s.SetProperty(x => x.Start, start), ct);
if (rows == 0) /* conflict or not found */;

6. ETags

Encode the rowversion as Base64 in an ETag ("AAAAAAAAB9E="). GET returns ETag; PUT/PATCH sends If-Match. Standards-wise, a failed If-Match is 412. Weak vs strong ETags: use strong for writes. Caches and proxies can use the same ETag with If-None-Match for 304 responses on reads.

7. Optimistic vs pessimistic

Pessimistic (SELECT ... WITH (UPDLOCK, ROWLOCK) in a transaction) blocks others while you hold the lock: good for short, high-contention server-side operations like allocating stock, never across a user's think-time.

Try it yourself

  1. Add [Timestamp], load the same entity in two contexts, save both, and catch the exception.
  2. Set the client's version as the current value instead of the original and confirm the conflict is missed.
  3. Implement store wins, client wins and merge, and log GetDatabaseValuesAsync output.
  4. Use ExecuteUpdateAsync with the version in Where and check the row count.
  5. Add ETag/If-Match to a Minimal API endpoint and test 412 with two curl calls.

💻 Code

A Minimal API update with rowversion, ETag/If-Match and store-wins conflict handling.

namespace Rostering.Shifts;

using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

public sealed class Shift
{
    public int Id { get; set; }
    public TimeOnly Start { get; set; }
    public TimeOnly End { get; set; }
    public string? Notes { get; set; }

    [Timestamp] public byte[] RowVersion { get; set; } = [];   // SQL Server rowversion
}

public sealed record ShiftDto(int Id, TimeOnly Start, TimeOnly End, string? Notes);
public sealed record UpdateShift(TimeOnly Start, TimeOnly End, string? Notes);

public static class ShiftEndpoints
{
    public static void MapShifts(this IEndpointRouteBuilder app)
    {
        app.MapGet("/shifts/{id:int}", async (int id, RosterDbContext db, HttpContext http, CancellationToken ct) =>
        {
            var s = await db.Shifts.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, ct);
            if (s is null) return Results.NotFound();
            http.Response.Headers.ETag = $"\"{Convert.ToBase64String(s.RowVersion)}\"";
            return Results.Ok(new ShiftDto(s.Id, s.Start, s.End, s.Notes));
        });

        app.MapPut("/shifts/{id:int}", async (int id, UpdateShift req, RosterDbContext db, HttpContext http, CancellationToken ct) =>
        {
            var ifMatch = http.Request.Headers.IfMatch.ToString().Trim('"');
            if (string.IsNullOrEmpty(ifMatch)) return Results.StatusCode(StatusCodes.Status428PreconditionRequired);

            var shift = await db.Shifts.SingleOrDefaultAsync(x => x.Id == id, ct);
            if (shift is null) return Results.NotFound();

            // The client's version must be the ORIGINAL value: that is what goes in the WHERE clause.
            db.Entry(shift).Property(x => x.RowVersion).OriginalValue = Convert.FromBase64String(ifMatch);

            shift.Start = req.Start;
            shift.End = req.End;
            shift.Notes = req.Notes;

            try
            {
                await db.SaveChangesAsync(ct);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                // Store wins: tell the client what is there now; they decide what to do.
                var current = await ex.Entries.Single().GetDatabaseValuesAsync(ct);
                if (current is null) return Results.NotFound();
                http.Response.Headers.ETag = $"\"{Convert.ToBase64String(current.GetValue<byte[]>(nameof(Shift.RowVersion)))}\"";
                return Results.Problem("The shift was changed by someone else. Reload and reapply your changes.",
                    statusCode: StatusCodes.Status412PreconditionFailed);
            }

            http.Response.Headers.ETag = $"\"{Convert.ToBase64String(shift.RowVersion)}\""; // new version from OUTPUT
            return Results.NoContent();
        });
    }
}
// Client wins, for the rare case it is correct: refresh originals from the database and save again.
catch (DbUpdateConcurrencyException ex)
{
    foreach (var entry in ex.Entries)
    {
        var dbValues = await entry.GetDatabaseValuesAsync(ct);
        if (dbValues is null) continue;          // deleted: decide separately
        entry.OriginalValues.SetValues(dbValues); // next save's WHERE uses the latest version
    }
    await db.SaveChangesAsync(ct);
}

⚠ Common mistakes

  • Mistake: Setting the client's version as the current value. Why it is wrong: EF uses the original value in the WHERE, which is the freshly loaded version, so the check always passes. Instead: set Property(x => x.RowVersion).OriginalValue.
  • Mistake: Not sending the version to the client at all and only checking within one request. Why it is wrong: the window that matters is the user's think-time between GET and PUT. Instead: return the version (body or ETag) and require it on writes.
  • Mistake: Catching DbUpdateConcurrencyException and automatically re-running the same save with refreshed originals for user edits. Why it is wrong: that is client wins by accident: it overwrites the other user's change without anyone seeing it, which is the lost update you were preventing. Instead: retry automatically only where overwriting is correct by design (an idempotent sync job, or a server-side operation that re-reads and re-applies its logic to the fresh values); for user edits, surface the conflict.
  • Mistake: Ignoring a null from GetDatabaseValuesAsync. Why it is wrong: it means the row was deleted, and treating it as a normal conflict throws or re-inserts. Instead: return 404 or 410.
  • Mistake: Using an app-managed token but forgetting to change it on some update paths. Why it is wrong: conflicts on those paths are never detected. Instead: prefer rowversion, or set the token centrally in a SaveChangesInterceptor.
  • Mistake: Assuming ExecuteUpdate checks concurrency tokens. Why it is wrong: it bypasses the change tracker, so no version check is added. Instead: include the version in Where and check rows affected.
  • Mistake: Returning 500 for a concurrency conflict. Why it is wrong: it's an expected client-side condition, not a server error. Instead: 409 (or 412 for If-Match) with ProblemDetails.
  • Mistake: Using pessimistic locks held across user interaction. Why it is wrong: locks block others for minutes and leak when users walk away. Instead: optimistic concurrency for user edits; short pessimistic locks only server-side.

🏛 Senior insight: trade-offs

I make concurrency checks the default for every user-editable aggregate, not an add-on after the first incident. rowversion costs 8 bytes a row and one predicate; the bug it prevents is silent data loss that nobody notices until a customer does. The conflict strategy is a product decision: for most screens store wins with a clear message and a diff is right; merging is only worth it for high-collaboration records.

I also check the non-UI paths: background jobs updating the same rows need the same check or set-based ExecuteUpdate with the version in the predicate, and integration tests should prove a stale write fails. I watch the conflict rate per endpoint; a high rate suggests the aggregate is too coarse and should be split.

Option When it fits Cost When not to
rowversion + store wins User edits Conflict UX Never wrong as a default
Client wins Idempotent overwrites, sync jobs where last write is right Can hide real conflicts Shared human-edited records
Merge per field Collaborative records, low overlap Complexity, testing Financial values
Pessimistic lock (UPDLOCK) Short server-side critical sections Blocking, deadlocks Across user think-time

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions lost updates in update endpoints. Why: Checks spotting missing concurrency in a code review.
    How to answer

    I'd rank the findings by impact:

    1. Security: it loads by id with no ownership check (an IDOR), and mapping the whole DTO allows over-posting of fields like Status or OwnerId.
    2. Wrong data: no concurrency token, so concurrent edits are silently lost; and the mapper may replace child collections, orphaning or deleting lines.
    3. Waste: Update() on an already-tracked entity is redundant and marks every column modified.
    4. Robustness and design: a missing record throws a NullReferenceException (500, not 404), and it returns the entity instead of a DTO.

    The rewrite: a use-case DTO with only editable fields plus RowVersion, load filtered by owner, set the RowVersion original value, assign fields explicitly, SaveChangesAsync, and map DbUpdateConcurrencyException to 409. The trade-off is a few lines of explicit mapping in exchange for correct, minimal, secure updates.

  2. When: Candidate mentions Attach, Update or disconnected entities. Why: Checks disconnected update approaches that pair with concurrency tokens.
    How to answer

    All three walk the whole graph and set states based on whether each entity has a key value:

    • Add: everything becomes Added, so EF Core inserts it.
    • Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.
    • Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.

    That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.

  3. When: Candidate mentions OriginalValue or GetDatabaseValuesAsync. Why: Checks Entry API fluency for original values.
    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).

🛠 Real-world problems: how you handle them

Shift changes silently lost between two rostering managers
Situation
A [rostering] web app for [~200] aged-care sites in NSW; managers edit shifts in a SPA backed by an ASP.NET Core API and Azure SQL. No concurrency checks.
Signals
Weekly complaints that shift times 'reverted'; staff turning up at the wrong time; no errors logged; audit columns showed a second edit seconds after the first.
Investigation
Matched complaints to `ModifiedAt` values and request logs: two PUTs on the same shift within the same minute from different managers, each carrying the full DTO. Reproduced in a `WebApplicationFactory` test with two clients. The endpoint loaded the shift and copied all DTO fields, so the second save restored the first manager's old values.
Resolution
Immediately: added a `rowversion` column (a non-blocking migration), returned it as an ETag, required `If-Match` on PUT and returned 412 with the current state. Then: the SPA showed a 'changed by someone else' dialog with a diff and a reload; background roster jobs switched to `ExecuteUpdate` with the version in the predicate.
Prevention
Integration tests for stale writes on every update endpoint; a code-review checklist item for concurrency on aggregates; a dashboard of 412s per endpoint.

How to tell it (STAR)

**S:** At [company], managers using our [rostering] app kept reporting that shift times reverted, and [carers turned up at the wrong time]. **T:** I was asked to find out why, since nothing appeared in the error logs. **A:** Matching complaints to request logs showed two managers saving the same shift within seconds; the second save carried stale values for fields they hadn't touched. I added a rowversion column, sent it as an ETag, required If-Match on updates, returned 412 with the latest data, and worked with the front-end developer on a dialog that showed both versions. **R:** The complaints stopped within [two weeks], and the dashboard showed [~30] conflicts a day being caught that used to be silent overwrites.

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me