How-To Guide

How to Implement Optimistic Locking with Version Columns

Prevent lost updates without holding locks by adding a version column and rejecting writes based on a stale version.

On this page

  1. Introduction
  2. The Lost Update Problem
  3. The Version Column
  4. The Update Flow
  5. Choosing Between Optimistic and Pessimistic
  6. Handling the Conflict
  7. Testing Optimistic Locking
  8. Conclusion

Introduction

Two users open the same record, both edit it, and both save. Whichever save runs last wins, and the first user’s changes vanish silently. That is a lost update, and it is one of the classic concurrency bugs. Pessimistic locking prevents it by holding a lock across the read-modify-write, which works but serializes and risks deadlocks and long-held locks. Optimistic locking prevents it differently: it lets both edits proceed and rejects the second save because the record changed since it was read. This article shows how to add a version column, make the update conditional on the version, and handle the conflict the user creation path needs.

The Lost Update Problem

Read-modify-write is where the bug lives: read a row, compute a new value in the application, write it back. Between the read and the write, another transaction can change the row, and the write overwrites that change with a value based on the old read. Both users believe they saved; one user’s work is gone. The bug is invisible in development because it needs concurrency, and invisible in logs because both commits succeeded.

Pessimistic locking avoids the bug by locking the row for the duration of the read-modify-write, so the second transaction waits until the first finishes. That works but holds a lock across application logic, which can be slow and can deadlock with other locks. Optimistic locking avoids the bug without holding a lock: it detects that the row changed and refuses the stale write, leaving the application to decide whether to retry or to surface a conflict.

The Version Column

Add an integer or timestamp column that the database increments on every update. A read returns the current version, and the write includes it in the WHERE clause: update only if the stored version still equals the version the reader saw. If another transaction updated the row first, the version no longer matches, the update affects zero rows, and the application knows its edit was based on stale data.

ALTER TABLE documents ADD COLUMN version int NOT NULL DEFAULT 1;

-- Optimistic update: succeeds only if the row is still at version 7.
UPDATE documents
SET title = $1,
    body = $2,
    version = version + 1
WHERE id = $3 AND version = $4;   -- $4 = the version the client read

-- If rowCount = 0, the row changed since the read: the caller must handle
-- the conflict (re-read, merge, or tell the user to refresh) -- not silently
-- overwrite. If rowCount = 1, the update succeeded and version is now 8.

The Update Flow

The read returns the version along with the data, the client sends it back with the write, and the server includes it in the conditional update. A zero-row result is not an error to swallow: it means a concurrent change, and the handler must decide whether to retry automatically or return a conflict to the client. Treating zero rows as success is how the lost update returns through the back door.

async function updateDocument(id, expectedVersion, changes) {
  const { rowCount } = await db.query(
    `UPDATE documents
        SET title = $1, body = $2, version = version + 1
      WHERE id = $3 AND version = $4`,
    [changes.title, changes.body, id, expectedVersion],
  );
  if (rowCount === 0) {
    // Either the row is gone or its version moved: both are conflicts.
    const current = await getDocument(id);
    if (!current) throw new NotFound(id);
    return { conflict: true, current };       // let the caller merge or retry
  }
  return { conflict: false };
}

Choosing Between Optimistic and Pessimistic

Optimistic locking is best when conflicts are rare and the operation is short: most web form edits, configuration changes and profile updates. It holds no lock, so it scales, and the cost is paid only when a conflict occurs. Pessimistic locking is better when conflicts are common or the operation must not fail, such as a balance transfer or a sequence allocation, because it guarantees the writer can proceed rather than having to retry.

You can combine them: optimistic for the user-facing edit, and inside the transaction a pessimistic lock only for the brief critical section. The decision is about how often two writers touch the same row and whether a rejected write is acceptable; if retries are frequent, optimistic locking turns into a retry storm, and a lock is cheaper.

Handling the Conflict

A conflict needs a user-facing answer. The simplest is to tell the user the record changed and let them reload, which is honest and safe. A better experience is to show a diff and let them merge. Automatic retry is only correct if the operation is idempotent or the change is a pure increment that can be recomputed; blindly retrying a save that overwrites user input can discard the very data you were protecting.

For counters and accumulators, a conditional increment that fails can be retried safely because the operation is commutative. For a form save, retrying with stale form data is wrong; you must re-read and merge. Match the conflict response to the operation, and never resolve a conflict by silently taking the last write, which is the bug you set out to fix.

Testing Optimistic Locking

The lost update is invisible in a sequential test, so test it with real concurrency: start two transactions that read the same version, have both attempt the update, and assert exactly one succeeds and the other reports a conflict. Run it against the real database rather than a mock, because the guarantee comes from the database’s row-level semantics.

Also test the boundaries: a write with a version that is too old fails, a write with the current version succeeds, and a write to a deleted row reports not-found rather than conflict. These tests pin the behaviour that makes the pattern correct, so a refactor that removes the version from the WHERE clause is caught immediately.

Conclusion

Optimistic locking prevents lost updates without holding locks by adding a version column and making the update conditional on the version the reader saw. A zero-row result signals a conflict, and the handler must resolve it deliberately: reload, merge, retry only when the operation is safe to retry, or return a conflict to the user. Choose optimistic locking for rare, short conflicts and pessimistic for frequent or must-succeed operations, and test under real concurrency. The version column is small, and it turns a silent overwrite into a detected, handled event.

Sources: PostgreSQL: concurrency control, Optimistic concurrency control, Lost update (Martin Fowler).

FAQ

What is the difference between optimistic and pessimistic locking?
Optimistic locking detects a conflict and rejects the stale write, holding no lock; it is cheap when conflicts are rare. Pessimistic locking holds a lock across the read-modify-write so the second writer waits; it is better when conflicts are frequent or the write must succeed.
What should happen when the conditional update affects zero rows?
Treat it as a conflict, not a success. Re-read the row and either merge the changes, retry if the operation is safe to retry, or return a conflict to the user. Swallowing the zero-row result reintroduces the lost update.

Related Examples