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.
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.
"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 anOrderLinerow and may not update theOrdersrow 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 catchesDbUpdateConcurrencyException; 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."
| 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.
| 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 |
| 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 |
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.
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
Red flags
lockAn aggregate root version turns write skew inside the aggregate into a same-row conflict, which optimistic concurrency detects.
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.IsConcurrencyToken() on a property you manage (Version int, a Guid) works on any provider.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.
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;.
| 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 |
DbContext instances load the same order, both change it, both save; assert the second throws.AddLine and watch the test pass when it should fail.Orders and query the history after a concurrent edit.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(); }
}
}
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.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.UPDLOCK only for short hot spots.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.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.