Two people edited the same invoice

A customer calls on Monday and asks for two more weeks to pay. Alice in accounts opens invoice INV-3001, moves the due date from 30 September to 15 October and saves. The screen says "Saved".

Bob has had the same invoice open in another tab since the morning. The customer's purchase order number has just arrived by email. He types it in and saves. The screen says "Saved".

On 1 October the system sends a payment reminder to a customer who was promised until the 15th.

Bob did not touch the due date. His form sent the whole invoice back, with the due date as it was when he opened it, and the API saved what it received. Alice's change was on the record for about a minute. No error was logged, because none occurred.

This article shows why an update endpoint loses changes without ever failing, why the usual fixes miss, and how a version number carried by two standard HTTP headers makes the second save fail loudly, not silently. Examples use ASP.NET Core, EF Core and PostgreSQL, but the HTTP part holds for any stack.

The whole argument in 40 seconds.

The version everyone writes first

Load nothing, check nothing, save what arrived:

app.MapPut("/invoices/{id:int}", async (int id, InvoiceUpdate update, AppDb db, CancellationToken ct) =>
{
    var changed = await db.Invoices.Where(i => i.Id == id).ExecuteUpdateAsync(s => s
        .SetProperty(i => i.Customer, update.Customer)
        .SetProperty(i => i.PoNumber, update.PoNumber)
        .SetProperty(i => i.DueDate, update.DueDate)
        .SetProperty(i => i.Total, update.Total), ct);

    return changed == 1 ? Results.NoContent() : Results.NotFound();
});

This is what PUT means: replace the resource with the representation in the request. It is correct for every request it receives. It can't know that the representation was read an hour ago.

Martial wrote a couplet to go with a gift of parchment writing tablets: think of them as wax, he says, for you will rub out as often as you wish to write afresh (delebis, quotiens scripta novare voles). That is this endpoint. Whatever was written before is wiped by whoever writes next, and the tablet keeps no memory of it.

Why it fails

Editing is three steps: read, change, write. The read and the write are two separate requests, and between them is a person: a phone call, a coffee, a tab left open since the morning.

Two sequences. Without a version check, Alice and Bob both read the invoice, Alice saves a new due date, Bob saves a PO number with the old due date, and Alice's change is overwritten. With If-Match, Bob's save carries the version he read and is refused with 412.

Time Alice Bob Saved due date
09:10 Opens the invoice 30 September
14:02 Opens the invoice 30 September
14:03 Saves: due 15 October 15 October
14:04 Saves: PO-7781, due 30 September 30 September

This is called a lost update. It has nothing to do with database isolation: each UPDATE ran alone, in its own transaction, and committed correctly. No transaction can span the minutes a person spends looking at a form.

Two common fixes don't close the gap:

The server can't see what a client read. So the client has to tell it.

The fix: say which version you edited

1. Hand out a version with every read

GET /invoices/3001

HTTP/1.1 200 OK
ETag: "838"

{"id":3001,"number":"INV-3001","customer":"Acme Ltd","poNumber":null,"dueDate":"2026-09-30","total":100.00}

An ETag is HTTP's name for "this exact version of the resource". The value is opaque to the client. Here it comes from PostgreSQL's xmin, a system column that changes every time a row is written, mapped in EF Core as a row version:

public uint Version { get; set; }

// in OnModelCreating
b.Entity<Invoice>().Property(i => i.Version).IsRowVersion();

2. Require it on every write

PUT /invoices/3001
If-Match: "838"

{"customer":"Acme Ltd","poNumber":"PO-7781","dueDate":"2026-09-30","total":100.00}

If-Match makes the request conditional: do this only if the resource is still at this version. A request without the header gets 428 Precondition Required, the status code defined for exactly this refusal. If the header were optional, the clients most likely to lose updates would be the ones that leave it out.

3. Compare in the statement that writes

if (invoice.Version != version)
{
    return Stale();   // 412 Precondition Failed
}

invoice.Customer = update.Customer;
invoice.PoNumber = update.PoNumber;
invoice.DueDate = update.DueDate;
invoice.Total = update.Total;

try
{
    await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException)
{
    return Stale();
}

There are two checks, and both are needed.

The second one is the guarantee, and it has no line of its own in this code. Because Version is mapped as a row version, EF Core sends UPDATE ... WHERE id = @id AND xmin = @version, with the version it read, which the first check has just shown to be the one the client edited. The database compares and writes in one statement, so two requests that arrive together can't both pass. This is the lesson of A database constraint beats an async validator again: a check in application code followed by a write is a race, and only the database can do both at once.

The first one covers a case I found by getting it wrong. If the row already holds exactly the values in the request, EF Core sees nothing to change and sends no UPDATE, so the database is never asked. In the sample's first version, twenty people added 10.00 to the same total from the same stale copy, and seven of them got 200: one real save, and six requests whose target value was already there. Each of those six had asked for an increase that never happened. The explicit comparison answers them 412.

4. Answer the stale save with 412

HTTP/1.1 412 Precondition Failed
Content-Type: application/problem+json

{
  "type": "https://errors.acme.example/invoice-changed",
  "title": "The invoice was changed by someone else",
  "status": 412,
  "detail": "Read it again, apply your change to the current version and retry."
}

412 is the status for a precondition in the request headers that turned out to be false. If the version travels in the body, 409 is the usual answer, since there is no header precondition to fail; that fits the reasoning in 400 or 422?, where 409 means the resource's current state says no. Pick one of the two designs and document it. The headers have one advantage: every HTTP client, proxy and API tool already knows what they mean.

What the client does with a 412 depends on who is behind it. A program reads again, applies its change to the current version and retries. A screen shows the person what changed and lets them decide.

In Athens, Aeschines says, the law required the magistrates to review the laws every year, and where two contradicted each other, to bring both before the people, who voted to keep one, so that for each matter there would be one law and no more. A 412 does the same with two edits. It can't know which one is right, so it refuses to choose in silence and sends the question back to someone who can.

What the sample counts

Twenty people each add 10.00 to an invoice of 100.00 at the same moment. The total should end at 300.00.

Four bars for the final total after twenty simultaneous edits of 10.00 each. No version check: 110.00, nineteen updates lost silently. If-Match: 110.00, nineteen refused with 412. If-Match with retry: 300.00. One UPDATE statement: 300.00.

Approach Answers Final total Changes not applied
No version check 20 × 204 110.00 19, and nobody knows
If-Match 1 × 200, 19 × 412 110.00 19, and each client knows
If-Match, client retries on 412 20 × 200 after 86 attempts 300.00 0
One UPDATE that adds 10.00 20 × 204 300.00 0

The first two rows end at the same total, and they are completely different outcomes. In the first, nineteen people were told their change was saved. Propertius once lost his writing tablets and mourned what went with them: scripta quibus pariter tot periere bona, so many good things written on them, lost together. He at least knew they were gone, and offered a reward.

What the version asks of you

When you don't need a version

Situation Smaller answer
The change is relative: add an amount, increment a counter One UPDATE ... SET total = total + @amount. The database serialises the writers
The change adds something: a line, a comment, a payment Insert a row. Two inserts don't overwrite each other
One writer per resource, such as a user's own profile Nothing, as long as the same user in two tabs is acceptable
The last value is all that matters, such as a "last seen" time Last write wins is the correct behaviour

Reach for the version when people edit shared records through forms, which is most business software.

The rule

  1. A save without a version is a guess about what the client saw. The read and the write are minutes apart, and no transaction covers them.
  2. Hand out a version on every read and require it on every write. ETag out, If-Match in, 428 when it is missing.
  3. Refuse the stale save where the write happens, and say so. Compare in the UPDATE itself and answer 412, so that losing a change is a decision somebody makes.

Run it yourself

The companion sample is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. A small client plays Alice and Bob, then twenty simultaneous editors.

docker compose up -d --build
docker compose run --rm demo

The output on my machine:

1. Alice and Bob open the same invoice. Alice changes the due date, then Bob adds a PO number.
   no version check:  Alice 204, Bob 204. Saved: due 2026-09-30, PO PO-7781   <- Alice's change is gone
   If-Match:          Alice 200, Bob 412. Saved: due 2026-10-15, PO none   <- Bob is told to reload

2. 20 people each add 10.00 to an invoice of 100.00 at the same moment. The total should be 300.00.
   no version check:      20 x 204. Total: 110.00, 19 update(s) not applied
   If-Match:              1 x 200, 19 x 412. Total: 110.00, 19 update(s) not applied
   If-Match + retry:      20 x 200 after 86 attempts in total
                          Total: 300.00, 0 update(s) not applied
   one UPDATE statement:  20 x 204. Total: 300.00, 0 update(s) not applied

3. A save that does not say which version it edited
   PUT /invoices/2 without If-Match: 428

The number of attempts in the retry line changes from run to run; the client checks everything else and exits with code 1 if anything differs.

The demo has limits. Its editors are programs that all read first and then all write, which is the worst case arranged on purpose. The retrying client simply reapplies its change; a real screen would show the person what changed. The README explains the two checks and the xmin caveats.

Further reading


This article is part of Justified Complexity: Building Backends One Decision at a Time.

Updated 2026-11-12, after a review: the code set the row version's original value before saving, and the text credited that line with the AND xmin = ... in the UPDATE. The row-version mapping does that; after the explicit comparison the line changed nothing, so it is removed here and in the sample.