Optimistic concurrency
Overview and setup
Optimistic concurrency assumes conflicting writes are uncommon and detects stale updates using an expected version. Read the row and version, then update only when both its key and expected version match; increment the version in the same statement. A zero-row result means the condition failed, which may be a changed version, missing record or another failed predicate.
Use a fresh disposable file database initialized with versions/v56/locking-fixture.sql. Enable WAL with PRAGMA journal_mode=WAL; before opening two independent private-cache connections A and B. Use driver autocommit, no implicit transaction, zero busy timeout, and fully fetch each query result. Follow steps in order; the included Python validator automates this. Never use production data.
First two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[10, 1]]
2. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session A
UPDATE lock_item SET qty=7,version=version+1 WHERE id=1 AND version=1 RETURNING qty,version;Observed rows: []
4. Session A
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[11, 2]]
How it works
A reads quantity 10, version 1; B changes quantity to 11 and version to 2. A’s stale write matches no rows. In the retry example A reads version 2 and recomputes the reservation to 8 rather than reusing 7, then updates version to 3. Every writer must honor the version protocol. This handles a single-row stale overwrite, not arbitrary cross-row invariants. The writes still acquire database locks.
Second two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[10, 1]]
2. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session A
UPDATE lock_item SET qty=7,version=version+1 WHERE id=1 AND version=1 RETURNING qty,version;Observed rows: []
4. Session A
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[11, 2]]
5. Session A
UPDATE lock_item SET qty=8,version=version+1 WHERE id=1 AND version=2 AND qty>=3 RETURNING qty,version;Observed rows: [[8, 3]]
6. Session B
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[8, 3]]
Practice and mistakes
Practice: remove the version increment from B’s update and predict whether A detects the conflict. Hint 1: the predicate checks version, not quantity. Hint 2: run the unsafe-writer edge test on a fresh fixture. Mistake: retrying blindly with an old computed value.