Imagine two support agents with the same customer record open. The first fixes a typo in the email address and saves. A few minutes later, the second updates the phone number and saves too. The form the second agent submitted still held the old email, so their save quietly puts the typo back. Nobody sees an error, and the first agent's fix is simply gone.
This is the lost update problem, and most CRUD apps have it by default. The fix is optimistic concurrency: keep a version number on the record, send that version back with every save, and make the database update succeed only if the version hasn't changed since the user loaded the record. If it has, the API returns a conflict and the UI tells the user, instead of overwriting someone else's work. This article walks through it end to end for React, NestJS, and PostgreSQL, including two ORM behaviors that are easy to get wrong.
Why transactions and row locks don't catch this
The natural first thought is that the database should prevent it. It doesn't, because the edit isn't one database operation. It's two separate HTTP requests: a GET when the user opens the form, and a PUT or PATCH when they save, possibly minutes later. Each request runs its own short transaction.
The PostgreSQL documentation says "Read Committed is the default isolation level in PostgreSQL," and stricter levels only protect operations inside a single transaction. Row locks have the same limit. According to PostgreSQL's explicit locking documentation, a SELECT ... FOR UPDATE lock holds until the current transaction ends, so you can't keep one open while someone types. Holding database transactions open across user think time would also tie up connections.
FOR UPDATE is still the right tool when a single request reads a row, computes something, and writes it back. It just can't span the gap between two requests.
The fix: put the version check inside the UPDATE
Add an integer version column to the table. Every write increments it, and every save includes the version the user started from. The check and the write happen in one statement:
UPDATE customers SET email = $1, phone = $2, version = version + 1 WHERE id = $3 AND version = $4
If another save got there first, the version no longer matches, the WHERE clause matches nothing, and the statement affects zero rows. Your code checks the affected row count. One row means success, and zero rows means a conflict (or a record that no longer exists, which you can tell apart with a follow-up read).
This works at PostgreSQL's default isolation level. When two updates race for the same row under Read Committed, the PostgreSQL docs say the second command's WHERE clause is "re-evaluated to see if the updated version of the row still matches the search condition." The second update sees the incremented version and matches nothing, so you don't need a stricter isolation level for this pattern.
Three details decide whether it holds up:
- Don't check the version in application code first. Reading the row, comparing versions in JavaScript, and then saving leaves a gap where another save can land. The comparison has to be in the UPDATE's WHERE clause.
- Prefer an integer version over updatedAt. PostgreSQL timestamps have 1 microsecond resolution, while a JavaScript
Datehas milliseconds, so a timestamp round-tripped through your API may no longer equal the stored value. Two writes can also land in the same millisecond. Prisma's type system documentation says itsDateTimemaps to PostgreSQL'stimestamp(3)by default, which keeps three fractional digits of a second. An integer that only ever increments avoids all of this. - Every write path must bump the version. Bulk updates, admin scripts, background jobs, and raw SQL fixes all need
version = version + 1. A write that skips it can be silently overwritten by a client holding the old version.
TypeORM: @VersionColumn doesn't protect your save
This is the one most likely to surprise you. TypeORM's entity documentation describes @VersionColumn as a column "automatically set to the version of the entity (incremental number)" each time you call save. It increments the version, but it doesn't check it.
TypeORM's issue #2848, "Optimistic Locking doesn't work for update," shows this. One commenter puts it plainly: "save() itself knows nothing about the version and doesn't guard against updating a record that has a later version." A maintainer replied that "update executes a simple UPDATE query, no more than that." The issue was closed automatically for inactivity in September 2025, marked not planned, without a fix. As of TypeORM 1.1.2, the save path builds its WHERE clause from the primary key only.
TypeORM does have an optimistic lock mode, but it's a read-time check. The find options accept lock: { mode: "optimistic", version }, which "Can be used only in findOne and findOneBy methods," and the version mismatch error is thrown when the row is loaded. Another request can still save between that read and your save().
The pattern that works is a QueryBuilder update with the version in the WHERE clause:
- Call
createQueryBuilder().update(Customer), set the changed fields plusversion: () => "version + 1", and add.where("id = :id AND version = :version", { id, version }). - Execute it and check
affectedon the result. Zero means the version didn't match. Verify that your database driver populatesaffectedfor updates before relying on it. - On zero, look the row up by id to decide between "not found" and "conflict."
Prisma: filter the update on the version
Prisma supports the check directly, with one catch. The Prisma v6 Client reference says "You can filter on non-unique fields to perform optimistic concurrency control on update operations," and recommends a version field. Filtering update on a non-unique field became generally available in Prisma 5.0.0. The pattern looks like this:
update({ where: { id, version }, data: { ...changes, version: { increment: 1 } } })- If the version has changed, no record matches and Prisma throws error code P2025, which the reference describes as "Thrown if the record to update does not exist."
That's the catch: a conflict and a deleted record produce the same error. Catch P2025, then check whether the record still exists to choose between a 404 and a conflict response.
The alternative from Prisma's v6 transactions guide uses updateMany with id and version in the filter and treats count === 0 as a failed check. It doesn't throw, so you handle the zero count yourself. Either way, Prisma doesn't manage the version for you. You add the field, filter on it, and increment it. As of November 2026, Prisma's current documentation no longer shows this optimistic concurrency section on its transactions page, so the v6 pages are the clearest reference.
Choosing the HTTP response: 409, 412, or 428
There are two common API designs, and each has its own status code.
- Version in the request body: 409 Conflict. The client sends
versionwith the PUT or PATCH payload. RFC 9110 describes 409 for exactly this case: when "versioning were being used" and the request includes changes that conflict with an earlier request. - ETag and If-Match headers: 412 Precondition Failed. The GET response includes an
ETagheader, and the client sends it back inIf-Match. RFC 9110 says If-Match is used "to prevent accidental overwrites" and the "lost update" problem, and a failed precondition gets a 412. - 428 Precondition Required, to make the check mandatory. RFC 6585 says 428 means "the origin server requires the request to be conditional." Return it when a client tries to update without If-Match, so a forgotten header can't silently fall back to last-write-wins.
For PATCH, RFC 5789 says clients "SHOULD use a conditional request," recommends 412 when a sent precondition fails, and 409 when no precondition was sent.
NestJS has the pieces built in. Its exception list includes ConflictException (409) and PreconditionFailedException (412). There's no dedicated 428 class as of @nestjs/common 12.4, but HttpStatus.PRECONDITION_REQUIRED exists for a plain HttpException. Whichever you return, include the current version and, ideally, the current record in the error body, so the client can show what changed without another request.
Public guidelines differ on the design. Google's AIP-154 says resources "may include an etag field" in the body, while Zalando's guidelines compare the approaches and pair the version-number style with 409 and the ETag style with 412. Pick one and use it consistently across your API.
If you use ETags, don't reuse Express's default
NestJS on Express already sends ETag headers on many GET responses, which makes it tempting to reuse them. Don't. The Express settings say "true enables weak ETag. This is the default setting." Those weak ETags are hashes of the response body for caching, and RFC 9110 says a server "MUST use the strong comparison function when comparing entity tags for If-Match." A weak ETag, marked with a W/ prefix, never matches under strong comparison. Express also doesn't evaluate If-Match on writes for you.
Instead, generate the ETag from your version column, for example "7" for version 7, set it on the GET response, and in the update handler compare the incoming If-Match value with the version you pass to the conditional UPDATE. The database check is still what enforces it.
The browser side: CORS headers you'll need
If your React app and API are on different origins, the browser gets involved. The Fetch standard lists only GET, HEAD, and POST as CORS-safelisted methods, so PUT and PATCH already trigger a preflight request. For the ETag approach, two more headers matter:
- If-Match isn't a safelisted request header, so your CORS configuration must list it in the allowed request headers, or the preflight fails.
- ETag isn't a safelisted response header, so your API must send
Access-Control-Expose-Headers: ETag, or JavaScript can't read the value from the GET response even though it's there.
If you use the version-in-body design, neither header is needed, which is one practical reason teams choose it.
React: carry the version and handle the conflict
On the client, the version has to travel from the GET that filled the form to the save that submits it. Three things decide whether the check actually works:
- Capture the version when editing starts. Store it in the form's state alongside the field values. Don't read it from a live query at submit time. TanStack Query, for example, treats cached data as stale by default and refetches when the window regains focus. If the form picks up the new version from a background refetch but keeps the user's old field values, the check passes and you're back to overwriting.
- Show the conflict instead of hiding it. On a 409 or 412, keep the user's unsaved input and tell them the record changed while they were editing. Offer clear choices: reload the latest version, review what changed side by side, or reapply their changes on top of the new version and save again. Then refresh the cached query.
- Don't retry a conflict automatically. Retrying the same save with the new version is exactly the overwrite you set out to prevent. TanStack Query doesn't retry mutations by default ("By default, TanStack Query will not retry a mutation on error"), so keep it that way for these requests.
If your app already maps server errors into form messages, treat a conflict as a form-level error rather than a field error. It's about the whole record, not one input.
Smaller conflicts with PATCH, and when last-write-wins is fine
Sending only the fields the user changed shrinks the surface for conflicts but doesn't remove it. Two users can still change the same field. JSON Patch has a test operation that checks a value before applying changes, and the whole patch fails if any test fails, which gives you a per-field precondition. JSON Merge Patch is simpler but has no concurrency features: null removes a field and arrays are replaced whole.
Last-write-wins is a reasonable choice when it's deliberate. A user's own display preferences or a "last viewed" timestamp rarely need a conflict screen. What matters is choosing it per resource instead of getting it by default. Real-time co-editing, where several people type into the same document at once, is a different problem with different tools and isn't covered here.
A lost-update checklist
- Add an integer
versioncolumn to records people edit concurrently. - Put the version check in the UPDATE's WHERE clause and check the affected row count. Never compare first and save second.
- Increment the version on every write path, including scripts, jobs, and bulk updates.
- In TypeORM, don't rely on
save()with@VersionColumn. Use a conditional QueryBuilder update. - In Prisma, filter
updateonidandversion, and tell a P2025 conflict apart from a deleted record. - Return 409 for version-in-body or 412 for If-Match, and consider 428 to require the check.
- Include the current version or record in the conflict response.
- If you use ETags, generate strong ones from the version, not Express's default weak ETags.
- For cross-origin apps, allow If-Match and expose ETag in CORS.
- Capture the version when editing starts, show a clear conflict message, and never retry a conflict automatically.
- Choose last-write-wins deliberately, per resource, where conflicts don't matter.



