Two requests hit your API at the same time. Both read the same row — an inventory count, an account balance, a seat reservation — both compute a new value, both write it back. One of the writes is silently gone. Nothing errored, no exception fired, the second write simply overwrote the first as if it never happened. This is the lost update, and it is the reason locking strategy exists. You have two families of solutions, and picking the wrong one shows up either as corrupted counts or as a system that collapses under exactly the load it was built for.
Pessimistic locking prevents the conflict: take a lock on the row before reading it, and nobody else can touch it until you commit. Optimistic locking detects the conflict: read freely, write with a condition that fails if the row changed underneath you, and retry. Same problem, opposite failure modes, and the right choice depends on one number — how often two writers actually collide on the same row.
The Problem, Precisely
The lost update is a read-modify-write race. Any code shaped like this is vulnerable:
-- Session A and Session B both run:
SELECT stock FROM inventory WHERE sku = 'WIDGET-42'; -- both see 7
-- A computes 7 - 1 = 6, B computes 7 - 2 = 5
UPDATE inventory SET stock = 6 WHERE sku = 'WIDGET-42'; -- A commits
UPDATE inventory SET stock = 5 WHERE sku = 'WIDGET-42'; -- B commits, A's write is gone
Neither transaction violated any isolation rule here. Under the default READ COMMITTED isolation level, this interleaving is legal — each statement sees a consistent snapshot, but nothing stops two snapshots from covering the same row. A single UPDATE that does the arithmetic inside the statement (SET stock = stock - 2) fixes this one case by making the read and write atomic, but the moment the new value depends on application logic — validation, price lookups, calling another service — you’re back to read-modify-write, and you need a real strategy.
Pessimistic: Lock First, Then Read
The pessimistic approach takes a row lock before reading, so the read-modify-write sequence runs inside an exclusion zone. In PostgreSQL that’s SELECT ... FOR UPDATE; the lock releases at commit or rollback:
func reserveStock(ctx context.Context, tx pgx.Tx, sku string, units int) error {
// Lock the row; concurrent reservers block here until we commit.
var stock int
err := tx.QueryRow(ctx,
`SELECT stock FROM inventory WHERE sku = $1 FOR UPDATE`,
sku).Scan(&stock)
if err != nil {
return err
}
if stock < units {
return ErrInsufficientStock
}
_, err = tx.Exec(ctx,
`UPDATE inventory SET stock = stock - $1 WHERE sku = $2`,
units, sku)
return err
}
This is correct by construction and easy to reason about: if a second transaction starts its own FOR UPDATE on the same row, it waits. But the waiting is the cost. Throughput on that row serializes — every transaction touching sku = 'WIDGET-42' queues behind the previous one, lock held for the full length of your transaction, including any slow work you left inside it. Hold the lock while calling a payment provider and the queue gets ugly fast.
Three practical guards come with the territory. Set lock_timeout so a stuck lock fails fast instead of holding connections hostage. Order lock acquisition consistently — always lock rows sorted by the same key — because the classic deadlock is two transactions each holding the row the other wants. And keep transactions holding FOR UPDATE locks as short as physically possible: no HTTP calls, no batching, no waiting on user input.
Optimistic: Read Freely, Commit Conditionally
The optimistic approach assumes collisions are rare. Read the row plus a version number, do the work with no locks held, then write with the version in the WHERE clause. If anyone else committed first, the version no longer matches and the UPDATE affects zero rows:
func reserveStockOptimistic(ctx context.Context, db *pgxpool.Pool, sku string, units int) error {
for attempt := 0; attempt < 5; attempt++ {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
var stock, version int
err = tx.QueryRow(ctx,
`SELECT stock, version FROM inventory WHERE sku = $1`, sku).
Scan(&stock, &version)
if err != nil {
tx.Rollback(ctx)
return err
}
if stock < units {
tx.Rollback(ctx)
return ErrInsufficientStock
}
tag, err := tx.Exec(ctx,
`UPDATE inventory
SET stock = stock - $1, version = version + 1
WHERE sku = $2 AND version = $3`,
units, sku, version)
if err != nil {
tx.Rollback(ctx)
return err
}
if tag.RowsAffected() == 1 {
return tx.Commit(ctx) // won the race
}
tx.Rollback(ctx) // someone committed first — reread and retry
}
return ErrTooMuchContention
}
No locks are ever held across your business logic — between the read and the write, this transaction holds nothing but memory. The conflict surfaces as a cheap, retryable miss instead of a blocking wait. The costs are different from pessimism’s: you need a version column (or a reliable updated-at timestamp, which is weaker — equal timestamps collide), every write path must check RowsAffected, and retries must re-run the entire decision, including any validations against the fresh state.
There’s also a variant worth knowing for workflows that span HTTP requests: send the version to the client with the resource, and require it back on the update. The conflict then surfaces as a 409 Conflict at the API boundary instead of a background retry — the user sees “this record changed, reload and try again,” which is sometimes the correct UX anyway.
Choosing: Contention Is the Whole Decision
The two strategies have opposite performance curves. Pessimistic locking’s cost is roughly constant per transaction — one lock, one wait if any — and its tail risk is serialization, not failure. Optimistic locking is free when there are no conflicts and pays only on collision — but when collision rates climb, the retry loops multiply: under heavy contention on one hot row, writers mostly fail, retry, fail again, and you burn CPU and connections doing work that keeps getting discarded. A retry storm on a hot row is worse than a polite queue.
- Low contention (most rows, few writers per row) — optimistic wins. Locks cost nothing when unused, and conflicts are rare enough that retries are noise.
- Hot rows (a handful of popular SKUs, a shared counter, a leaderboard) — pessimistic, or sidestep both: serialize through a queue, or push the mutation into a single atomic statement or stored procedure so no application-level read-modify-write exists.
- The write spans services or a user think-time — optimistic is the only option. You cannot hold a database lock across an HTTP call to another service or across a form the user fills out over lunch; the lock either times out or quietly leaks until the connection closes.
- Multi-row invariants (transferring between two accounts) — pessimistic with consistent ordering is easier to prove correct; optimistic across many rows means aborting and retrying a wide transaction, which gets expensive fast.
Pitfalls That Show Up in Production
- Optimistic without retry. Adding a version column and checking
RowsAffectedbut surfacing a rare “update didn’t happen” as a 500 means occasional silent data loss under exactly the conditions you added the column to prevent. - Forgetting the version in bulk updates.
UPDATE ... WHERE sku = $1in a batch script bypasses the version check and defeats the whole scheme. - Locks held across external calls. The optimistic-minded developer who uses
FOR UPDATE“just for safety” around a third-party API call has built the worst of both worlds. - Retry loops without backoff or a cap. Unbounded retries under contention turn a busy row into an outage; cap attempts (the five in the example) and fall back to queuing or failing loudly.
- ORM blind spots. Most ORMs support optimistic versioning, but only if the entity is configured for it — and a
save()that writes every column from a stale in-memory entity can clobber concurrent changes even with a version column, if the version check is absent from the generated UPDATE.
Wrapping Up
Both strategies solve the same race; they differ in whether the collision costs a wait or a retry. Estimate your collision rate per row, and let that number decide: quiet rows get the version column, hot rows get locks or an atomic mutation, anything spanning a network boundary gets optimistic semantics with the conflict shown to the user. The one indefensible choice is the unguarded read-modify-write — the version that both strategies exist to protect.