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

📚 Interview question

Two account managers edit the same order at the same time. One removes a line, the other applies a discount based on the old total, and the saved order now breaks the rule that discounts never exceed 20% of the total. Nobody got an error. How do you diagnose this lost update and fix it with optimistic concurrency at the aggregate level?

Covers diagnosing a lost update that breaks an aggregate invariant under concurrent edits, and fixing it with a rowversion on the aggregate root, touching the root on child changes, ETags over HTTP and conflict handling.

Senior Debugging Advanced aggregates architecture domain-driven-design ef-core etag optimistic-concurrency

🎯 Key points

  • Symptom: each request checked the invariant against its own stale copy; both commits succeeded (write skew / lost update)
  • Root cause: no concurrency token, or token only on child rows, so EF Core 10's UPDATE had no version check
  • Fix: rowversion on the aggregate root (IsRowVersion, EF Core 10 on .NET 10) and every behaviour method modifies the root so its version changes
  • EF Core adds WHERE RowVersion = @original; 0 rows affected throws DbUpdateConcurrencyException
  • Carry the version to the client: ETag on GET, If-Match on PUT/PATCH, 412 Precondition Failed on mismatch
  • Resolve conflicts by reloading and re-applying the command or asking the user; never overwrite with the stale client values ('client wins')
  • Isolation levels do not fix it: read committed and RCSI allow it, snapshot catches same-row conflicts only, serializable blocks heavily
  • Pessimistic UPDLOCK only for short transactions on very hot rows (e.g. a stock counter decremented hundreds of times a second)

⏱ 30-second answer

This is a lost update / write skew: both requests loaded the order, each checked the 20% rule against its own copy, and both saved. Removing the line lowered the total; the discount was checked against the old total. Each change was valid alone; together they broke the invariant. EF Core only sends the changed columns, so neither UPDATE noticed the other.

The fix is optimistic concurrency on the aggregate root: a rowversion column configured with IsRowVersion(), and every behaviour method (including removing a child line) modifies the root so its version changes. EF Core then adds WHERE RowVersion = @original and throws DbUpdateConcurrencyException when 0 rows are affected. Carry the version to clients as an ETag and require If-Match, returning 412. On conflict, reload and re-run the command or ask the user. The trade-off: occasional retries in exchange for no silent corruption.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I'd do is confirm it's a concurrency problem and not a logic bug. I'd pull the audit or temporal history for that order and the request logs: if I see two updates within a second or two, from two users, each of which was valid on its own, that's a lost update. Strictly it's write skew: user A removed a line, which lowered the total; user B applied a discount checked against the old, higher total; both transactions committed. The aggregate's rule was checked twice, but each time against a stale in-memory copy, so the database ended up in a state no single request would have allowed.

The reason nobody got an error is that EF Core, by default, generates UPDATE ... SET Discount = @p WHERE Id = @id. No version check. And even teams that add a rowversion often put it on the wrong row: removing a line deletes an OrderLine row and may not update the Orders row at all, so the root's rowversion doesn't change and the second save still succeeds.

For example, at [company] we had exactly this on [quotes]: [a handful] of quotes a month went out with discounts above policy. The fix was three parts. One: a rowversion on the aggregate root, and every behaviour method updates the root, here the recalculated Total, so any change to the aggregate bumps its version. Two: the API exposes that version as an ETag on GET and requires If-Match on updates, so a user editing a screen they loaded five minutes ago gets a 412 instead of overwriting. Three: the handler catches DbUpdateConcurrencyException; for commands that are safe to replay, like 'add line', it reloads and re-runs the command once, and the invariant is re-checked against fresh data; otherwise it returns a conflict so the user sees the latest. We added an integration test with two DbContexts against SQL Server in Testcontainers, and [over-policy discounts went to zero]. The mistake I see is fixing this with a lock in the application, which only works on one instance, or with serializable isolation everywhere."


Why each request looked valid

Time User A (remove line) User B (discount) DB total / discount
t0 Load: total 1,000, version 7 Load: total 1,000, version 7 1,000 / 0
t1 Remove a 400 line → total 600 Discount 200 (20% of 1,000 ✓)
t2 Save (version 7 → 8) 600 / 0
t3 Save: no version check → succeeds 600 / 200 = 33% ✗

B decided on a total that no longer existed. With a root version, B's save at t3 finds version 8, not 7, and fails.

Concurrency options

Option How Fits Cost
Optimistic, rowversion on root IsRowVersion(), touch root Most aggregates Retries on conflict
Optimistic + ETag/If-Match Version over HTTP Edit screens, public APIs Client must send the header
Pessimistic UPDLOCK, ROWLOCK Lock the root row in a short transaction Very hot rows updated many times a second (stock counter, seat count) Blocking, deadlock risk
Serializable isolation Range locks Rarely; small critical sections Heavy blocking

Isolation levels do not solve this alone

Level Prevents this? Why
Read committed / RCSI (Azure SQL default) No Each transaction reads committed data, then writes without checking it changed
Snapshot Partly Detects update conflicts on the same row; misses skew across different rows
Serializable Yes, at a cost Holds locks on everything read until commit; blocking and deadlocks under load
Optimistic token on root Yes Turns any change to the aggregate into a same-row version conflict

Production example

After adding a root rowversion and ETags on the [quote editor], conflicts surfaced as [~0.3%] of saves at month-end peaks, each shown to the user with the latest data. Over-policy discounts dropped from [about 6 a month] to [zero], and the conflict rate was low enough that no locking was needed.

🔍 What the interviewer is checking

Checks that the candidate can diagnose a concurrency bug from symptoms and fix it correctly at the aggregate level, end to end through the API.

Green flags

  • Names lost update / write skew and explains why each request looked valid
  • Puts the version on the root and touches the root on child changes
  • Carries the version to the client with ETag / If-Match
  • Has a clear conflict-resolution strategy and a concurrency test

Red flags

  • Suggests an in-process lock
  • Thinks transactions alone prevent this
  • Resolves conflicts with "last write wins"

📚 Learn in depth

1. Lost update vs write skew

  • Lost update: two transactions update the same field; the second overwrites the first.
  • Write skew: two transactions read overlapping data, update different fields, and together violate a rule. Read committed and RCSI do not prevent either; SQL Server snapshot isolation detects update conflicts on the same row but not write skew across rows.

An aggregate root version turns write skew inside the aggregate into a same-row conflict, which optimistic concurrency detects.

2. How EF Core implements optimistic concurrency

Load:   SELECT Id, Total, Discount, RowVersion FROM Orders WHERE Id=@id   -> RowVersion = 0x...07
Save:   UPDATE Orders SET Discount=@d
        OUTPUT INSERTED.RowVersion
        WHERE Id=@id AND RowVersion=0x...07
        -> 0 rows => DbUpdateConcurrencyException
  • IsRowVersion() maps a byte[] to SQL Server rowversion, which the database bumps on every update of the row.
  • Alternatively, IsConcurrencyToken() on a property you manage (Version int, a Guid) works on any provider.

3. Touch the root

Adding an OrderLine inserts a child row; if no root column changes, EF Core does not update Orders, so the rowversion does not move. Every behaviour method should change something on the root: a recalculated total, a Version++, or a LastModified. Some teams force it in a SaveChangesInterceptor that marks the root modified when any owned child changes.

4. Carrying the version over HTTP

GET  /orders/42          -> 200, ETag: "AAAAAAAAB9E="
PUT  /orders/42/discount    If-Match: "AAAAAAAAB9E="
     -> version matches   -> 204, new ETag
     -> version differs   -> 412 Precondition Failed (client reloads)

Set the original value from the header before saving: db.Entry(order).Property(o => o.RowVersion).OriginalValue = fromIfMatch;.

5. Resolving conflicts

Strategy When
Reload and replay the command Commands that express intent ("add 2 units") and re-check invariants
Return 409/412 and show the latest User edits of fields, where intent depends on what they saw
Merge field by field Rarely; only with clear rules per field
Last write wins Never silently for aggregates with invariants

6. Diagnosing in production

  • Temporal tables or an audit log: two versions seconds apart from different users.
  • Application Insights: two requests for the same order id overlapping in time.
  • Query Store / Extended Events: UPDATE statements without a version predicate.

Try it yourself

  1. Write an integration test: two DbContext instances load the same order, both change it, both save; assert the second throws.
  2. Remove the "touch root" line from AddLine and watch the test pass when it should fail.
  3. Add ETag/If-Match to a Minimal API endpoint and test the 412 path.
  4. Turn on a temporal table for Orders and query the history after a concurrent edit.

💻 Code

Root rowversion, touching the root, ETag/If-Match, and conflict handling with replay.

namespace Sales.Domain;

public sealed class Order
{
    private readonly List<OrderLine> _lines = [];
    private Order() { }

    public Guid Id { get; private set; } = Guid.CreateVersion7();
    public decimal Total { get; private set; }
    public decimal Discount { get; private set; }
    public byte[] RowVersion { get; private set; } = [];
    public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly();

    public void AddLine(string sku, int qty, decimal price)
    {
        _lines.Add(new OrderLine(sku, qty, price));
        Recalculate(); // touches the root row, so its rowversion changes
    }

    public void RemoveLine(string sku)
    {
        _lines.RemoveAll(l => l.Sku == sku);
        Recalculate();
    }

    public void ApplyDiscount(decimal amount)
    {
        if (amount < 0 || amount > Total * 0.20m)
            throw new InvalidOperationException("Discount cannot exceed 20% of the total.");
        Discount = amount;
    }

    private void Recalculate()
    {
        Total = _lines.Sum(l => l.Qty * l.Price);
        if (Discount > Total * 0.20m) Discount = Total * 0.20m; // keep the invariant when lines change
    }
}

public sealed record OrderLine(string Sku, int Qty, decimal Price);
// Mapping: rowversion on the root.
b.Entity<Order>(e =>
{
    e.Property(o => o.RowVersion).IsRowVersion();
    e.Property(o => o.Total).HasPrecision(18, 2);
    e.Property(o => o.Discount).HasPrecision(18, 2);
    e.OwnsMany(o => o.Lines, l => l.Property(x => x.Price).HasPrecision(18, 2));
});
// API: ETag on GET, If-Match on update, 412 on mismatch, replay-safe retry for commands.
app.MapGet("/orders/{id:guid}", async (Guid id, SalesDbContext db, HttpContext http, CancellationToken ct) =>
{
    var o = await db.Orders.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, ct);
    if (o is null) return Results.NotFound();
    http.Response.Headers.ETag = $"\"{Convert.ToBase64String(o.RowVersion)}\"";
    return Results.Ok(new { o.Id, o.Total, o.Discount });
});

app.MapPut("/orders/{id:guid}/discount", async (Guid id, decimal amount, HttpRequest req, SalesDbContext db, CancellationToken ct) =>
{
    if (req.Headers.IfMatch.Count == 0) return Results.StatusCode(428); // Precondition Required
    var expected = Convert.FromBase64String(req.Headers.IfMatch.ToString().Trim('"'));

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

    // Compare against what the user saw, not what we just loaded.
    db.Entry(order).Property(o => o.RowVersion).OriginalValue = expected;
    order.ApplyDiscount(amount);

    try { await db.SaveChangesAsync(ct); }
    catch (DbUpdateConcurrencyException) { return Results.StatusCode(412); } // user must reload
    return Results.NoContent();
});

// For intent-style commands (add line), reload and replay once instead of failing.
static async Task AddLineWithRetryAsync(SalesDbContext db, Guid id, string sku, int qty, decimal price, CancellationToken ct)
{
    for (var attempt = 0; ; attempt++)
    {
        var order = await db.Orders.SingleAsync(o => o.Id == id, ct);
        order.AddLine(sku, qty, price);
        try { await db.SaveChangesAsync(ct); return; }
        catch (DbUpdateConcurrencyException) when (attempt == 0) { db.ChangeTracker.Clear(); }
    }
}

⚠ Common mistakes

  • Mistake: No concurrency token at all. Why it is wrong: EF Core's UPDATE has no version predicate, so concurrent changes silently overwrite or skew. Instead: rowversion on every aggregate root.
  • Mistake: Rowversion on child rows only. Why it is wrong: changes to different children never conflict, so aggregate-wide rules break. Instead: version the root and touch it in every behaviour method.
  • Mistake: Checking the version against the freshly loaded entity in a stateless API. Why it is wrong: the load happens after the other user's save, so the check always passes. Instead: carry the version the user saw (ETag) and set it as the original value.
  • Mistake: lock or SemaphoreSlim in the application. Why it is wrong: it works on one instance only and does nothing across scaled-out App Service instances. Instead: database-level optimistic concurrency.
  • Mistake: Resolving a conflict with "client wins": catching DbUpdateConcurrencyException, copying the database's current version into the entity's original values and saving the user's stale values again. Why it is wrong: it forces the overwrite through and reintroduces exactly the lost update the token detected. Instead: reload and replay the command against fresh data, or return 412/409 and let the user decide.
  • Mistake: Serializable isolation everywhere to "be safe". Why it is wrong: heavy blocking and deadlocks under load. Instead: optimistic concurrency; pessimistic UPDLOCK only for short hot spots.
  • Mistake: No test for concurrency. Why it is wrong: the bug only appears under real parallel use. Instead: an integration test with two contexts against real SQL Server (Testcontainers).
  • Mistake: Relying on rowversion for changes made outside EF Core (ExecuteUpdate, stored procedures, imports). Why it is wrong: those paths may skip the domain checks even though SQL Server bumps the rowversion. Instead: route business changes through the aggregate, or add the version predicate to the bulk statement explicitly.

🏛 Senior insight: trade-offs

The deeper lesson is that the aggregate boundary and the concurrency boundary must be the same thing. If the invariant spans the order and its lines, the version must cover the order and its lines, which in practice means one version on the root that changes whenever anything inside changes. If you find yourself wanting to version two aggregates together, the boundary is probably wrong.

Approach When it fits Cost When not to
Root rowversion + replay Intent-style commands, moderate contention A retry loop User edits where intent depends on what was seen
Root rowversion + ETag (412) Edit screens, public APIs Clients must handle 412 Fire-and-forget background jobs
Pessimistic lock Very hot single rows, short transactions Blocking, deadlocks Long-running user edits

I watch the conflict rate (count of DbUpdateConcurrencyException per minute in Application Insights); a sustained rise means an aggregate is too big or a hot spot needs a different design.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions race conditions in general. Why: Checks broader understanding of races across threads, async and databases.
    How to answer

    A race condition is a bug where the result depends on the timing of concurrent operations. Classic forms are read-modify-write (count++ from two threads), check-then-act (if (!dict.ContainsKey(k)) dict.Add(k, v)), and unsafe publication. In .NET they also appear with non-thread-safe collections (a shared Dictionary or List corrupted under concurrent writes), in async code that interleaves at await points even on one thread, and in databases as lost updates when two requests read, modify and save the same row. Fixes: atomic operations, locks, concurrent collections, immutability, single-writer designs, and in databases optimistic concurrency tokens, unique constraints and idempotency.

  2. When: Candidate suggests changing the isolation level. Why: Checks they know which anomalies each isolation level prevents.
    How to answer

    Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.

    The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.

  3. When: Candidate says the version must cover the whole aggregate. Why: Checks aggregate boundary design.
    How to answer

    An aggregate is a cluster of entities and value objects that must stay consistent together, with one entity as the aggregate root. Outside code talks only to the root, so the root can enforce the invariants: rules that must be true whenever the transaction commits (an order's total equals its lines; a booking never exceeds capacity).

    Keep aggregates small: draw the boundary around real invariants, not around every relationship. Reference other aggregates by id (CustomerId), not by object, so loading an order does not drag in the customer. Change one aggregate per transaction; when another aggregate must react, publish a domain event and update it in a separate transaction. The trade-off is eventual consistency between aggregates in exchange for low contention and clear ownership.

🛠 Real-world problems: how you handle them

Quotes sent with discounts above policy after concurrent edits
Situation
A [B2B sales] system let account managers and pricing analysts edit quotes concurrently, [~800] quotes a day, peaking at month-end. Discounts above 20% need director approval.
Signals
Finance found [about 6] quotes a month with discounts over 20% and no approval; no errors in logs; each quote had two updates seconds apart from different users.
Investigation
Queried the temporal history of `Quotes` for over-policy rows, matched timestamps with Application Insights requests from two users, reproduced it with a two-context integration test, and confirmed the UPDATE had no version predicate (EF Core logging).
Resolution
Added a rowversion to the `Quote` root and made every behaviour method recalculate the root, exposed it as an ETag and required If-Match on edits (412 on mismatch), and replayed intent-style commands once on conflict.
Prevention
Concurrency integration tests per aggregate in CI, an architecture test that every aggregate root has a concurrency token, and a dashboard of conflict rates.

How to tell it (STAR)

**S:** At [company], finance found [about 6] quotes a month with discounts over policy, and nobody had seen an error. **T:** I took [the investigation]. **A:** Temporal history showed two edits seconds apart on every bad quote, so I reproduced it in a test with two DbContexts. I added a rowversion on the aggregate root, made every change touch the root, and added ETags so stale screens got a 412. I wrote an ADR making a concurrency token mandatory for aggregate roots. **R:** Over-policy discounts went to [zero], conflicts were [~0.3%] of saves, and the architecture test caught [two] new aggregates missing a token.

↩ Usually asked after

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me