Skip to content

Commit 5c1a045

Browse files
committed
docs(transactions): note lost-update risk in read-modify-write
The bumpCounter example reads a row and writes counter+1 in a transaction without locking. Under READ COMMITTED (the default) two concurrent runs can both read the same value and lose an update. Add a short section pointing at SELECT ... FOR UPDATE and SERIALIZABLE + retry. Addresses #3485
1 parent dd1c96b commit 5c1a045

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

‎docs/howto/transactions.md‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,30 @@ func bumpCounter(ctx context.Context, db *pgx.Conn, queries *tutorial.Queries, i
9898
}
9999
return tx.Commit(ctx)
100100
}
101-
```
101+
```
102+
103+
## Concurrent read-modify-write
104+
105+
The `bumpCounter` example reads a row and then writes a value derived from it.
106+
Under the default isolation level (`READ COMMITTED`), two transactions running
107+
`bumpCounter` concurrently can both read the same `counter`, both write
108+
`counter + 1`, and one update is lost.
109+
110+
When a write depends on a value read earlier in the same transaction, lock the
111+
row on read with `SELECT ... FOR UPDATE` (supported by PostgreSQL and
112+
MySQL/InnoDB):
113+
114+
```sql
115+
-- name: GetRecordForUpdate :one
116+
SELECT * FROM records
117+
WHERE id = $1
118+
FOR UPDATE;
119+
```
120+
121+
Call `GetRecordForUpdate` in place of `GetRecord`; the second transaction then
122+
blocks until the first commits, and reads the updated value.
123+
124+
Alternatively, run the transaction at `SERIALIZABLE` isolation and retry on
125+
serialization failures. sqlc does not manage isolation levels or retries — set
126+
the isolation level when you begin the transaction and handle the retry loop in
127+
your application code.

0 commit comments

Comments
 (0)