Development Playbook

Your agent's PUT endpoint silently overwrites other people's edits: add ETags, If-Match and seven tests that prove it

An agent-written update endpoint loses data the moment two clients edit the same record. Here's the failing test, the ETag and If-Match fix for ASP.NET Core and EF Core, and a guard that stops the next endpoint shipping without it. About 15 minutes to try.

A peach paper sheet almost completely covering an identical blue sheet, with a cut-out window in the middle showing nested layers

Two people open the same support ticket. One closes it. The other, still looking at the copy they loaded a minute ago, assigns it to a colleague and hits save. The PUT carries the whole ticket, status included, so the ticket is open again and the closure has vanished. No error, no log line, no failed test. The ticket just ended up in a state nobody chose.

Agents tend to write this endpoint the same way. Ask for “an endpoint to update a ticket” and the result is load the row, copy the fields across, save, return 200. It’s correct for one user and wrong for two. The diff looks tidy, the happy-path test passes, and the bug waits for a busy afternoon.

The fix is optimistic concurrency, and in HTTP terms it has been a solved problem for years: the server hands out an ETag on read, the client sends it back in If-Match on write, and the server refuses the write if the tag no longer matches. This Playbook builds that with ASP.NET Core minimal APIs and EF Core on SQLite, driven by xUnit tests that fail first. Along the way, three deliberate breakages show which part of the fix does which job, and one extra test makes the next endpoint an agent adds fail the build if it skips the protection. The tests, the prompt and the proof need nothing from any one agent: any tool that can read files and run dotnet test can do this.

Write the failing test before the fix

Start with the naive endpoint, which is what an unprompted agent produces. This is the whole PUT:

tickets.MapPut("/{id:guid}", async (Guid id, UpdateTicket body, TicketDb db) =>
{
    var t = await db.Tickets.FindAsync(id);
    if (t is null) return Results.NotFound();
    t.Title = body.Title;
    t.Status = body.Status;
    t.Assignee = body.Assignee;
    await db.SaveChangesAsync();
    return Results.Ok(TicketDto.From(t));
});

The first test plays out the scene above with two clients. Both read the ticket. Client A closes it. Client B, holding the old copy, assigns it to Dana. The test asserts that B’s write is refused and that the ticket is still closed afterwards. Against the naive endpoint it prints:

Failed LostUpdateTests.Second_writer_holding_a_stale_copy_is_rejected_not_applied [2 s]
  Error Message:
   Assert.NotEqual() Failure: Values are equal
Expected: Not OK
Actual:   OK

That’s the whole bug in one line: the second write got a 200. Before changing any production code, this is the point to hand the task to the agent, because the test now defines done.

The prompt

Give the agent the failing test, not a description of the pattern. Descriptions get you a version that looks right and isn’t.

Make LostUpdateTests pass without editing the tests.

Requirements:
- GET /tickets/{id} returns a strong ETag header (quoted, no W/ prefix).
- PUT /tickets/{id} requires If-Match. Missing header: 428. A tag that is
  not byte-for-byte the current one: 412 with a problem-details body.
  Success: 200 plus the new ETag.
- The database must enforce it too: use an EF Core concurrency token on
  Ticket, so two requests that both pass the header check cannot both save.
- Do not use the entity's current value as the "client" tag. The tag comes
  from the request.
Run `dotnet test` and paste the result.

The last requirement matters more than it looks, and the second experiment below shows why. Without it, agents often add a concurrency token, see the compiler and the happy-path tests stay green, and stop.

What the fix looks like

Here’s the working endpoint, trimmed to the parts that matter. The entity gets an application-managed token, since SQLite has no auto-updating rowversion equivalent (the EF Core docs say so explicitly, and describe a Guid marked with [ConcurrencyCheck] as the portable alternative):

public sealed class Ticket
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public string Title { get; set; } = "";
    public string Status { get; set; } = "open";
    public string? Assignee { get; set; }

    [ConcurrencyCheck]
    public Guid Version { get; set; } = Guid.NewGuid();

    public string ETag => $"\"{Version:N}\"";
}

Because the token isn’t database-generated, something has to change it on every update. The DbContext does that in one place, so no endpoint can forget:

public override Task<int> SaveChangesAsync(CancellationToken ct = default)
{
    foreach (var e in ChangeTracker.Entries<Ticket>().Where(e => e.State == EntityState.Modified))
        e.Entity.Version = Guid.NewGuid(); // EF still sends the original value in the WHERE clause
    return base.SaveChangesAsync(ct);
}

When EF saves a modified entity, the UPDATE carries WHERE Id = @id AND Version = @original. If another writer got in first, zero rows match and EF throws DbUpdateConcurrencyException.

The endpoint pair is where the HTTP semantics live:

tickets.MapGet("/{id:guid}", async (Guid id, TicketDb db, HttpResponse res) =>
{
    var t = await db.Tickets.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id);
    if (t is null) return Results.NotFound();
    res.Headers.ETag = t.ETag;
    return Results.Ok(TicketDto.From(t));
});

tickets.MapPut("/{id:guid}", async (Guid id, UpdateTicket body, TicketDb db, HttpContext ctx) =>
{
    var t = await db.Tickets.SingleOrDefaultAsync(x => x.Id == id);
    if (t is null) return Results.NotFound();

    // Strong comparison: the header must equal the current tag byte for byte.
    if (ctx.Request.Headers.IfMatch.ToString() != t.ETag) return Stale();

    t.Title = body.Title;
    t.Status = body.Status;
    t.Assignee = body.Assignee;
    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        return Stale(); // someone saved between our read and our write
    }
    ctx.Response.Headers.ETag = t.ETag;
    return Results.Ok(TicketDto.From(t));
}).RequireIfMatch();

static IResult Stale() => Results.Problem(
    statusCode: StatusCodes.Status412PreconditionFailed,
    title: "The ticket changed since you read it. GET it again and re-apply your edit.");

RequireIfMatch() is a small extension that adds an endpoint filter returning 428 when the header is absent, and tags the endpoint with a marker type, RequiresIfMatch, which the guard test uses later:

public sealed class RequiresIfMatch;

public static class IfMatchExtensions
{
    public static RouteHandlerBuilder RequireIfMatch(this RouteHandlerBuilder b) =>
        b.WithMetadata(new RequiresIfMatch())
         .AddEndpointFilter(async (ctx, next) =>
             ctx.HttpContext.Request.Headers.ContainsKey("If-Match")
                 ? await next(ctx)
                 : Results.Problem(statusCode: StatusCodes.Status428PreconditionRequired,
                       title: "Send the ETag you read in an If-Match header."));
}

The status codes aren’t arbitrary. RFC 9110 section 13.1.1 says a server must use the strong comparison function for If-Match, because the client’s intent is to prevent the method being applied if the representation changed at all. It also says a server that finds the condition false must not perform the method and may answer 412. RFC 6585 defines 428 Precondition Required as the server insisting that a request be conditional, with the lost update problem as the stated reason.

Seven tests, and what each one pins

The suite lives in one class on top of a WebApplicationFactory<Program> that points the app at a temporary SQLite file. A file, not :memory:, because the race test needs many connections.

The tests:

  • Get_returns_a_strong_quoted_etag: the tag starts with a quote and has no W/ prefix.
  • Second_writer_holding_a_stale_copy_gets_412_and_changes_nothing: the scene from the opening, now sending If-Match. Asserts 412 for B, and that the ticket still shows closed with no assignee.
  • Put_without_if_match_is_428.
  • A_weak_tag_is_not_accepted_for_writes: sends W/ plus the current tag and expects 412.
  • Success_returns_a_fresh_tag_that_the_next_write_can_use: the response ETag differs from the old one and works for a second write. Without this, clients are forced into a GET after every save.
  • Twenty_writers_with_the_same_tag_produce_exactly_one_winner: twenty parallel PUTs carrying the same tag, asserting one 200 and nineteen 412s.
  • Every_mutating_ticket_route_requires_if_match: the guard, covered below.

Run dotnet test and the suite prints:

Passed!  - Failed:     0, Passed:     7, Skipped:     0, Total:     7, Duration: 2 s - Tickets.Tests.dll (net10.0)

A green suite only counts if it can go red, so the next three sections break the code on purpose.

Experiment one: drop the header check

Delete the If-Match comparison and keep the EF concurrency token. If the token were doing the work, the suite should stay green. It doesn’t:

Failed LostUpdateTests.Second_writer_holding_a_stale_copy_gets_412_and_changes_nothing [1 s]
Expected: PreconditionFailed
Actual:   OK
Failed LostUpdateTests.Twenty_writers_with_the_same_tag_produce_exactly_one_winner [361 ms]
Expected: 1
Actual:   16
Failed LostUpdateTests.A_weak_tag_is_not_accepted_for_writes [11 ms]
Expected: PreconditionFailed
Actual:   OK
Failed!  - Failed:     3, Passed:     4, Skipped:     0, Total:     7, Duration: 2 s - Tickets.Tests.dll (net10.0)

Sixteen of twenty writers won. This is the mistake agents make most, and it’s worth being precise about why. In a stateless API each request loads the entity fresh, so the “original” value EF compares against is whatever is in the database right now, not what the client saw when it read. The token only protects the gap between this request’s read and this request’s write, a window of milliseconds. The long window, from the client’s GET to its PUT, can only be closed by the client sending back what it saw. That’s the job of If-Match.

Experiment two: drop the token, keep the header check

Now the reverse. Remove [ConcurrencyCheck] and leave the header comparison in place:

Failed LostUpdateTests.Twenty_writers_with_the_same_tag_produce_exactly_one_winner [172 ms]
Expected: 1
Actual:   2
Failed!  - Failed:     1, Passed:     6, Skipped:     0, Total:     7, Duration: 2 s - Tickets.Tests.dll (net10.0)

Six of seven tests pass, which is the dangerous part. Every sequential scenario looks fine. Only the race exposes it: two requests carrying the same valid tag both pass the header check against the same loaded row, and both save. The count of winners varies from run to run (this run printed 2) because it depends on timing, which is also why this bug survives code review and ordinary testing so well.

So the two layers do different jobs. The header comparison rejects stale clients. The concurrency token makes the database refuse the second of two writers who were both validly up to date a moment ago. The race test is the only one that notices when the second layer is missing, so keep it, and keep it deterministic by asserting the winner count rather than which writer wins.

Experiment three: the endpoint the agent adds next

The last protection is the one that scales. Next month the agent adds PATCH /tickets/{id}/assign, copying the style of its first draft. Nothing in the existing tests touches that route, so the unprotected endpoint would ship.

The guard test walks the route table instead of testing known routes:

[Fact]
public void Every_mutating_ticket_route_requires_if_match()
{
    var unguarded = api.Services.GetRequiredService<EndpointDataSource>()
        .Endpoints.OfType<RouteEndpoint>()
        .Where(e => e.RoutePattern.RawText!.StartsWith("/tickets"))
        .Where(e => e.Metadata.GetMetadata<HttpMethodMetadata>()!
            .HttpMethods.Any(m => m is "PUT" or "PATCH" or "DELETE"))
        .Where(e => e.Metadata.GetMetadata<RequiresIfMatch>() is null)
        .Select(e => e.DisplayName)
        .ToList();

    Assert.Empty(unguarded);
}

Add a naive MapPatch with no RequireIfMatch() and run the suite:

Failed LostUpdateTests.Every_mutating_ticket_route_requires_if_match [18 ms]
   Assert.Empty() Failure: Collection was not empty
Collection: ["HTTP: PATCH /tickets/{id:guid}/assign"]
Failed!  - Failed:     1, Passed:     6, Skipped:     0, Total:     7, Duration: 2 s - Tickets.Tests.dll (net10.0)

The failure names the exact route. That’s a message the agent can act on without a human reading the diff. It also checks the marker, not the behaviour, so it’s a tripwire and not a proof: a route can carry RequiresIfMatch and still compare the wrong thing. The behavioural tests cover that for the PUT; any new route needs its own stale-write test.

Make it yours

A few variations for other stacks.

SQL Server (documented behaviour, not run here). Swap the Guid for [Timestamp] byte[] Version, which maps to rowversion and changes in the database on every write, so the SaveChangesAsync override disappears. Format the ETag from Convert.ToBase64String(Version), quoted. The doc page above covers the mapping.

PATCH and DELETE. Same rule: require If-Match, compare, catch the exception. For DELETE EF throws DbUpdateConcurrencyException too, as the docs note, so the catch block carries over unchanged.

A UI that re-applies the edit. On 412 the client should GET again, show the user what changed, and let them redo the edit. The problem-details title in the example says exactly that, which is what a front-end developer (or an agent writing the client) needs. For automated callers, a capped re-read, re-apply and retry loop is the usual pattern. Don’t retry blindly with the old tag.

Pinning versions. .NET 11 was announced on 10 November 2026, and an unpinned dotnet add package Microsoft.EntityFrameworkCore.Sqlite now resolves to 11.0.0, which refuses to restore on net10.0 (error NU1202, supports net11.0 only). Pin with --version "10.*" until the project moves frameworks, and tell the agent to do the same.

What goes wrong

The tag has to change on every write that matters. If an agent adds a new update path that bypasses SaveChangesAsync (a raw ExecuteUpdateAsync, say), the Version isn’t regenerated and clients’ tags stay valid after the row changed. Keep bulk updates behind a code path that also sets the token, or forbid them on this entity.

Too-wide tokens cause false conflicts. A single version for the whole row means a change to an unimportant field invalidates everyone’s tag. Usually that’s what you want. If it isn’t, restrict regeneration to the fields that matter, which is the fine-grained control the EF docs describe for application-managed tokens.

Don’t bother with this for append-only data, for resources only one actor ever writes, or where last write wins is the stated product rule. It’s also overkill for a PUT that replaces a record wholesale by design and is retried idempotently. For those, an idempotency key (see the idempotency Playbook ) is the better tool, and the two solve different problems: one stops duplicates, the other stops overwrites.

First 15 minutes

Create a minimal API project and a WebApplicationFactory test project on net10.0, pin the EF Core SQLite package to 10.*, and write the first test only: two clients, one stale write, assert it is refused. Watch it fail against the naive PUT.

Then give the agent the prompt above, with the test file attached and the rule that it can’t edit the tests. When the suite is green, run the three experiments in this article against what it wrote. If any of them stays green, the suite has a hole, and that hole is the one to close next.