- Architecture
- API
Optimistic locking with row_version in a REST API
Two editors, one record: how a simple integer column prevents silent overwrites and what the client does with a 409.
Akbar Bintang Mahendra1 min read
The problem
Two people open the same record. Without a version check the last save silently wins and the first person's work disappears.
The contract
Every row carries row_version. A PUT must send the version it read:
PUT /api/v1/admin/posts/{id}
{ "title": "…", "row_version": 3 }
The server compares the stored version. If it still matches, it saves and increments to 4. If not, it answers 409 with message_code 1460.
On the client
The editor shows a clear message, reloads the latest version and lets the user re-apply their change. No locks, no blocked users, and no lost work.
In PostgreSQL later
A trigger increments row_version on every update, and the UPDATE statement includes WHERE row_version = $n. The same rule, enforced by the database.