sql go 25 lines · 2 tabs

Optimistic locking with a version column

Leah Thompson Jan 2026
2 tabs
ALTER TABLE documents ADD COLUMN version BIGINT NOT NULL DEFAULT 0;
2 files · sql, go Explain with highlit

When multiple clients can update the same record, I prefer optimistic locking over heavy row locks. The idea is simple: every row has a version that increments on each update. The update statement includes WHERE id=$1 AND version=$2, so if someone else updated the row first, your update affects zero rows and you return a 409 Conflict. This is a clean, DB-native way to detect lost updates without forcing a transaction to hold locks while the client thinks. The operational benefit is better concurrency under load, especially for “edit settings” style endpoints. In practice, the API returns the latest record so the client can re-apply changes or show a merge UI. It’s a small schema change with a big correctness payoff.


Related snips

Share this code

Here's the card — post it anywhere.

Optimistic locking with a version column — share card
Link copied