← Back to Backend, page 2

backend-0033 · Medium mid

What is optimistic locking, how do you implement it with a version column in SQL, and when is it better than pessimistic locking?

Optimistic locking assumes conflicts are rare. You read the row together with a version number, and on update you add AND version = :old to the WHERE clause and increase the version. If another writer got there first, zero rows are updated and you know there was a conflict, so you reload and retry or tell the user. It avoids holding locks while users think, and works well for web forms and low contention data. Under heavy contention the retries cost more than waiting on a lock.

Full answer

The lost update

  • Two users load the same record. Both change it and save. The second save overwrites the first without knowing about it.

The pattern

  1. Table has a version integer (or an updated_at timestamp, or a row hash).
  2. Read: SELECT id, name, version FROM docs WHERE id = 1.
  3. Update: UPDATE docs SET name = :new, version = version + 1 WHERE id = 1 AND version = :seen.
  4. Check the affected row count. 1 means success. 0 means somebody changed the row: reload, merge or show a conflict message, and try again.

Notes

  • It also works over HTTP with ETag and If-Match, mapping a failure to 412 or 409.
  • No database locks are held between the read and the write, so there is no waiting and no deadlock.
  • For counters and simple increments, use an atomic UPDATE (balance = balance + 5) instead.
  • ORMs offer it as a built-in feature (a version column).
  • Choose pessimistic locking (SELECT FOR UPDATE) when conflicts are frequent, the work between read and write is short and inside one transaction, or retries would be expensive.
javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query(`DROP TABLE IF EXISTS bk33_docs; CREATE TABLE bk33_docs (id int PRIMARY KEY, body text NOT NULL, version int NOT NULL DEFAULT 1);
                  INSERT INTO bk33_docs VALUES (1, 'original', 1)`);

  const load = async () => (await db.query('SELECT body, version FROM bk33_docs WHERE id = 1')).rows[0];
  const save = async (body, seenVersion) => (await db.query('UPDATE bk33_docs SET body = $1, version = version + 1 WHERE id = 1 AND version = $2', [body, seenVersion])).rowCount;

  // Both editors load version 1.
  const editorA = await load(), editorB = await load();

  console.log('editor A saves     :', (await save('A edit', editorA.version)) === 1 ? 'saved' : 'conflict');
  console.log('editor B saves     :', (await save('B edit', editorB.version)) === 1 ? 'saved' : 'conflict (zero rows updated)');
  console.log('row after both     :', JSON.stringify(await load()));

  // B reloads, applies the change again and retries.
  const fresh = await load();
  console.log('editor B retries   :', (await save('A edit + B edit', fresh.version)) === 1 ? 'saved' : 'conflict');
  console.log('final row          :', JSON.stringify(await load()));

  // Without the version check the second writer silently wins (a lost update).
  await db.query("UPDATE bk33_docs SET body = 'original', version = 1");
  await db.query("UPDATE bk33_docs SET body = 'A edit' WHERE id = 1");
  await db.query("UPDATE bk33_docs SET body = 'B edit' WHERE id = 1");
  console.log('no version check   :', (await load()).body, '(A\'s change is gone)');

  await db.query('DROP TABLE bk33_docs');
  await db.end();
})();

Runs on the local PostgreSQL. The two editors are simulated by loading the same version twice, then saving one after the other. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): editor A saves : saved editor B saves : conflict (zero rows updated) row after both : {"body":"A edit","version":2} editor B retries : saved final row : {"body":"A edit + B edit","version":3} no version check : B edit (A's change is gone)

Key points

  • Add a version to each row and check it in the update's WHERE clause.
  • Zero updated rows means a conflict.
  • No locks are held while users edit.
  • Retry or ask the user to resolve conflicts.
  • Use atomic updates for counters.

Common mistakes

  • Checking the version in the application instead of in the UPDATE.
  • Ignoring the row count of the update.
  • Using optimistic locking on a hot counter.
  • Not telling the user what changed.
  • Forgetting to include the version in every write path.

Follow-ups

  • How does an ORM implement a version column?
  • How would you do this over HTTP?
  • When do you prefer SELECT FOR UPDATE?

Tips

  • Show the WHERE version clause.
  • Say 'zero rows means conflict'.
  • Compare with pessimistic locking.