Preventing lost updates: optimistic concurrency with ETag and If-Match

Difficulty: Advanced

Question

Two users edit the same record at the same time via your API. How do you prevent one from silently overwriting the other?

Answer

This is the lost update problem, the classic issue that hides behind harmless looking PUT endpoints. Imagine a shared document. Priya opens it and starts editing the title. Rahul opens it and edits the description. Priya saves, then Rahul saves a full-object PUT that still contains Priya's old title, silently wiping her change. Neither request failed, and no error was logged, yet data was lost. Interviewers like this question because it tests whether you think beyond the single-request happy path.

Two families of solutions exist. Pessimistic locking acquires a lock when a user begins editing and holds it until they finish. It is safe but awkward over stateless HTTP: locks need timeouts, abandoned sessions leave stale locks, and it hurts scalability. Optimistic concurrency assumes conflicts are rare, lets everyone read freely, and detects conflicts at write time. It fits REST and web scale far better.

The HTTP-native mechanism uses validators. When the client reads a resource, the server returns an ETag or a version number. When the client updates, it sends that value back in If-Match. The server compares it to the current version. If they match, the update proceeds and the version is bumped, with a new ETag in the response. If they differ, someone else changed the resource, and the server rejects the write with 412 Precondition Failed. The client then reloads, merges or asks the user to resolve the conflict, and retries with the new version. If a client omits If-Match on an endpoint that requires it, return 428 Precondition Required, which forces every client to opt into safe behaviour.

At the database level, implement the check atomically. The naive approach of SELECT the row, compare versions in application code and then UPDATE has a race. Instead, embed the version in the UPDATE itself: UPDATE docs SET title = $1, version = version + 1 WHERE id = $2 AND version = $3, and check the affected row count. Zero rows means a conflict. Many ORMs provide this: Hibernate's @Version, Rails' lock_version, or a Prisma version field used in the where clause. Alternatively use an updated_at timestamp, but version integers are safer since timestamps can collide at low precision.

Status code debate: 412 is the correct code when using If-Match. Some APIs, lacking header support, return 409 Conflict with the current representation in the body, so clients can merge. Both are acceptable; be consistent and document. Also note that PATCH reduces the conflict surface because independent fields do not clobber each other, but PATCH on the same field, or invariants that span fields, still need version checks.

Merge strategies: last writer wins is simplest but loses data; field-level merge works when changes touch different fields; operational transforms or CRDTs power collaborative editors like Google Docs and are overkill for CRUD APIs. For counters and balances, avoid read-modify-write altogether and use atomic operations such as UPDATE SET balance = balance - 100 WHERE balance >= 100.

Summing up: send a version with every read, require it on every write, verify atomically in the database, and answer 412 or 409 with enough information for the client to resolve.

Code examples

Conditional update flow

GET /v1/docs/7 HTTP/1.1

HTTP/1.1 200 OK
ETag: "5"
{ "id": 7, "title": "Draft", "body": "..." }

# Rahul saves, but Priya already saved version 5 -> 6
PUT /v1/docs/7 HTTP/1.1
If-Match: "5"
{ "title": "Draft", "body": "Rahul's text" }

HTTP/1.1 412 Precondition Failed
Content-Type: application/problem+json
{ "title": "Resource was modified", "status": 412, "current_version": "6" }

Rahul's stale write is rejected instead of silently overwriting Priya's edit.

Atomic version check in SQL

const { rowCount } = await db.query(
  'UPDATE docs SET title=$1, body=$2, version=version+1 WHERE id=$3 AND version=$4',
  [title, body, id, expectedVersion]
);
if (rowCount === 0) {
  return res.status(412).json({ title: 'Resource was modified', status: 412 });
}

Compare-and-set in one statement avoids the read-then-write race.

Key points

Common follow-up questions

Interview tips

Concepts covered

concurrency, lost update, ETag, If-Match

More API Design questions