Optimistic locking

Concurrency control without holding a lock: read the row with its version, then UPDATE only WHERE the version (and status) are still what you read, incrementing the version. Zero rows affected means someone else changed it first; re-read and retry or give up.

Minimal example

sql
UPDATE orders SET status = ?, version = version + 1
WHERE id = ? AND status = ? AND version = ?;

Learn this concept

Lesson 3.11 · State machines and optimistic locking

Used in exercises

Exercise 3.12 · POST /v1/orders/{id}/events: order lifecycle Exercise 8.2 · Stock reservation service
Prerequisite conceptsTransaction