Writing Optimistic Locking Code With LLMs in November 2026: Add a Version Column, Make the Update Conditional, and Tell the User When Someone Else Saved First
Two people open the same record. One fixes the price, the other fixes the description. Both click Save. The second save quietly overwrites the first, and nobody finds out until a customer sees the old price. This is the lost update problem, and it is one of the most common bugs in CRUD apps, admin panels, and APIs.
Ask an LLM for an "edit product" endpoint and you will usually get code that reads the row, applies the changes, and writes the whole row back. It works perfectly in a demo with one user. It fails silently the moment two users, two browser tabs, or a user and a background job touch the same record. This post shows how to get optimistic locking out of an AI coding assistant, and how to check that what it wrote actually protects you.
On a single-track railway, only the train holding the token may enter the section. That is pessimistic locking. Optimistic locking skips the token and checks for a conflict at the moment of the write. Image: Exchanging single line token by James Petts, CC BY-SA 2.0, via Wikimedia Commons.
What optimistic locking is, in one paragraph
Every row gets a version number. When a client loads a record, it also gets the version it saw. When it saves, the server only applies the update if the version in the database is still the one the client saw, and bumps the version in the same statement. If someone else saved in between, the version no longer matches, the update touches zero rows, and the server reports a conflict instead of overwriting. Nobody holds a lock while a user is staring at a form, which is why it is called "optimistic": you assume conflicts are rare and detect them when they happen.
The alternative, pessimistic locking (SELECT ... FOR UPDATE), holds a database lock for the length of a transaction. That is the right tool for short server-side operations, but you should never hold a database lock while waiting for a human to finish editing a form.
Step 1: Tell the model the problem, not just the feature
If your prompt says "write an update endpoint for products," the model has no reason to think about concurrency. Name the failure you want to prevent and the mechanism you want. A prompt that works well:
Write a PATCH /products/:id endpoint in Express with PostgreSQL (node-postgres).
Requirements:
- The products table has an integer "version" column, NOT NULL DEFAULT 1.
- The client must send the version it last read. Reject requests without it.
- Apply the update with a single UPDATE ... WHERE id = $1 AND version = $2
that also sets version = version + 1, and use RETURNING to get the new row.
- If zero rows were updated, check whether the product exists:
404 if not, 409 Conflict with the current row if it does.
- Do not read the row first and then write it back.
- Return the new version in the response body.
The line "do not read the row first and then write it back" matters. Without it, a common LLM pattern is: SELECT the row, compare versions in application code, then UPDATE. That looks like optimistic locking, but there is a gap between the check and the write where another request can slip in. The version comparison has to be part of the UPDATE itself.
Step 2: Know what correct code looks like
Here is the core of a correct handler. Check that whatever your assistant produces has the same shape.
app.patch("/products/:id", async (req, res) => {
const id = Number(req.params.id);
const { version, name, price_cents } = req.body;
if (!Number.isInteger(version)) {
return res.status(428).json({ error: "version is required" });
}
const result = await pool.query(
`UPDATE products
SET name = COALESCE($3, name),
price_cents = COALESCE($4, price_cents),
version = version + 1,
updated_at = now()
WHERE id = $1 AND version = $2
RETURNING id, name, price_cents, version`,
[id, version, name ?? null, price_cents ?? null]
);
if (result.rowCount === 1) {
return res.json(result.rows[0]);
}
const current = await pool.query(
"SELECT id, name, price_cents, version FROM products WHERE id = $1",
[id]
);
if (current.rowCount === 0) {
return res.status(404).json({ error: "not found" });
}
return res.status(409).json({
error: "This product was changed by someone else.",
current: current.rows[0],
});
});
Things to verify line by line:
- The version check is in the
WHEREclause. Not in anifbefore the query. - The increment is in the same statement.
version = version + 1, computed by the database, notversion = $5with a number the client sent. - The row count is checked. An
UPDATEthat matches nothing is not an error in SQL. If the code never looks atrowCount(or your driver's equivalent), the conflict is silently ignored and the client is told the save worked. - A missing version is rejected. If the handler treats a missing version as "skip the check," every old client and every careless script bypasses the protection.
- The follow-up
SELECTis only for building the error response. It is fine that it is a separate query, because it does not decide whether a write happens.
Step 3: Use your ORM's built-in support when it has one
Many ORMs already implement this, and the model should use the built-in feature rather than reinvent it. Tell it which ORM and version you are on, and ask it to use the native mechanism:
- Ruby on Rails (Active Record): add an integer
lock_versioncolumn and Rails checks it automatically, raisingActiveRecord::StaleObjectErroron conflict. The form must carrylock_versionas a hidden field, or the check compares against the freshly loaded value and never fails. - JPA / Hibernate: a field annotated with
@Version; a conflicting update throws an optimistic lock exception. - SQLAlchemy: configure
version_id_colin the mapper; a stale update raisesStaleDataError. - Entity Framework Core: mark a property as a concurrency token (or use a SQL Server
rowversioncolumn) and catchDbUpdateConcurrencyException. - Django: the core ORM has no built-in version field. Either use a conditional
QuerySet.filter(pk=..., version=...).update(..., version=F("version") + 1)and check the returned count, or use a third-party package you have reviewed.
The trap that shows up again and again with ORMs is the web layer, not the database layer. The ORM compares against the version it loaded. If your handler loads the record fresh on every request and copies the form fields onto it, the loaded version is always current and the check always passes. The version the user saw has to travel from the edit form back to the server and be assigned onto the entity before saving. Ask the model explicitly: "Show me where the client's version is set on the entity before save."
A version column is just a counter the database clicks forward on every successful save. A stale number means someone else saved first. Image: Hand Tally Counter by Ajay Kumar Chaurasiya, CC BY-SA 4.0, via Wikimedia Commons.
Step 4: Carry the version over HTTP properly
For a JSON API, putting version in the request body is simple and works. HTTP also has a standard mechanism for this: the server sends an ETag header with the resource, and the client sends it back in an If-Match header on PUT or PATCH. If the ETag no longer matches, the server responds 412 Precondition Failed. If you want to require the header, 428 Precondition Required exists for that.
Either approach is fine. What matters is consistency: pick one, document it, and make sure every write endpoint for that resource uses it. If you ask an LLM to "add ETag support," check that it uses ETags on writes and not only for caching on reads, which is the more common example in its training data. An ETag derived from the version number (for example W/"17" or "17") is easier to reason about than a hash of the whole response body.
Step 5: Decide what the user sees on a conflict
A 409 that says "conflict" and throws away the user's typing is technically correct and practically hostile. Decide up front, and put the decision in your prompt:
- Show both versions. Return the current record with the error, keep the user's unsaved input in the form, and highlight fields that differ. The user decides.
- Auto-merge disjoint fields. If the other person changed the description and this user changed the price, you can reapply this user's changes on top of the new version. Only do this if you track which fields the user actually edited, not every field in the form.
- Last write wins, on purpose. For some data (a user's own preferences, a draft only they can see), overwriting is acceptable. Write that down so the next developer, or the next prompt, does not "fix" it.
Never let the frontend respond to a conflict by silently refetching and resubmitting with the new version. That is exactly the overwrite you were trying to prevent, now with extra steps. If an LLM writes a retry loop around a 409, remove it.
Step 6: Do not confuse optimistic locking with atomic updates
Some lost-update bugs do not need versions at all. If the operation is "decrement stock by one" or "add 10 to a balance," the fix is to let the database do the arithmetic:
UPDATE products
SET stock = stock - 1
WHERE id = $1 AND stock >= 1
RETURNING stock;
Zero rows back means out of stock. LLMs frequently generate the read-modify-write version instead (SELECT stock, subtract in code, UPDATE SET stock = $2), which loses decrements under concurrent requests. When you review generated code, look for any value that is read, changed in application code, and written back. Each one is either an atomic update, a versioned update, or a bug.
Step 7: Avoid weak version columns
A tempting shortcut is to use updated_at as the version. Models suggest it because the column usually exists already. It has problems: two writes can land in the same timestamp at the precision your database or driver keeps, timestamps can be rounded when serialized to JSON and back so the client's value never matches again, and clock adjustments on application servers can move values backwards if the app sets the timestamp instead of the database. An integer that the database increments has none of these issues. If you must use a timestamp, have the database set it and compare at full precision, and test the round trip through your API.
Step 8: Test it with real concurrency
A unit test that calls the handler once proves nothing about concurrency. Ask the model to write tests like these, then run them against a real database, not a mock:
- Stale write is rejected. Load version 1, save successfully (now version 2), then save again with version 1. Expect 409 (or 412) and confirm the database still holds the first save's values.
- Missing version is rejected. Send an update with no version or no
If-Match. Expect 428 or 400, not 200. - Parallel saves. Fire 20 updates with the same starting version at the same time. Exactly one should succeed and 19 should conflict. Final version should be 2.
- Atomic counters. Start stock at 10, fire 50 concurrent decrements. Expect exactly 10 successes and a final stock of 0, never negative.
- Not found versus conflict. Update a nonexistent ID and confirm a 404, not a 409.
The parallel tests are the ones that catch the check-then-write gap. If they pass reliably across many runs, your locking is doing its job. If they pass "most of the time," something is still reading before writing.
A short review checklist
- Every editable table that humans touch has an integer version column.
- Every update includes
AND version = ?andversion = version + 1in one statement, or uses the ORM's native mechanism. - The code checks affected row count and turns zero into a conflict or not-found.
- The client's version comes from what it loaded, travels through the form or
If-Match, and is required. - Counters and balances use atomic SQL, not read-modify-write.
- Conflicts keep the user's input and show the current data. No automatic resubmit.
- Concurrency tests run against a real database.
Optimistic locking is a small amount of code, but it only works if every piece is in place. LLMs are good at producing the pieces when you name them, and bad at noticing they are missing when you do not. Name the failure, ask for the conditional update, and test with parallel requests before you trust it.
Comments
Post a Comment