Optimistic Locking Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Optimistic Locking runs in O(1) time and O(1) space, in Go as in every other language.
- ✓database/sql is the whole story for rows: db.ExecContext with UPDATE ... WHERE id = $1 AND version = $2, then res.RowsAffected(), which returns (int64, error) and that error is not decorative because not every driver implements the call.
- ✓Explicit error returns and no panics: the conflict is a package-level sentinel compared with errors.Is, and the retry is a plain bounded for loop.
- ✓The Go trap: Return a conflict as a typed pointer and the retry loop never terminates. A func attempt() error that does var e *ConflictErr; return e hands back an interface whose type word is set and whose data word is nil, so err != nil is true, errors.Is finds nothing, and every iteration looks like an unrelated failure.
- ✓Goroutines are cheap enough to be dangerous here: a few thousand writers on one row turn a bounded retry into livelock, so cap concurrency with errgroup.SetLimit or a buffered channel.
What Optimistic Locking actually is
Optimistic Locking in Go: what you actually reach for
Go implementation
var (
ErrConflict = errors.New("optimistic conflict") // a value, never a typed nil
ErrInsufficient = errors.New("insufficient funds")
)
func Withdraw(ctx context.Context, db *sql.DB, id, amt int64) error {
const upd = `UPDATE account SET balance = balance - $1, version = version + 1
WHERE id = $2 AND version = $3`
for attempt := 0; attempt < 5; attempt++ {
var bal, ver int64
err := db.QueryRowContext(ctx,
`SELECT balance, version FROM account WHERE id = $1`, id).Scan(&bal, &ver)
if err != nil {
return err // includes sql.ErrNoRows
}
if bal < amt {
return ErrInsufficient
}
res, err := db.ExecContext(ctx, upd, amt, id, ver)
if err != nil {
return err
}
// always check this error: not every driver implements RowsAffected
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 1 {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(5<<attempt) * time.Millisecond):
}
}
return ErrConflict
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Optimistic Locking?
database/sql is the whole story for rows: db.ExecContext with UPDATE ... WHERE id = $1 AND version = $2, then res.RowsAffected(), which returns (int64, error) and that error is not decorative because not every driver implements the call. GORM has no version column of its own, so you write .Where("version = ?", v) and read tx.RowsAffected. In memory, sync/atomic since Go 1.19 exposes typed values, atomic.Int64, atomic.Uint64 and the generic atomic.Pointer[T], each with CompareAndSwap(old, new) bool, replacing the older atomic.CompareAndSwapInt64(&x, old, new). errors.As with pgconn.PgError separates a serialization failure, SQLSTATE 40001, from a plain lost compare-and-set.
What is the most common Go mistake when implementing Optimistic Locking?
Return a conflict as a typed pointer and the retry loop never terminates. A func attempt() error that does var e *ConflictErr; return e hands back an interface whose type word is set and whose data word is nil, so err != nil is true, errors.Is finds nothing, and every iteration looks like an unrelated failure. Return a nil literal, or a sentinel value. The second trap is protocol-level: go-sql-driver/mysql reports rows changed rather than rows matched, so an UPDATE whose new values happen to equal the current ones returns zero and is indistinguishable from a lost compare-and-set. Add clientFoundRows=true to the DSN. Postgres drivers report matched rows and never show this.
How does Optimistic Locking actually perform in Go?
Goroutines are cheap enough to be dangerous here: a few thousand writers on one row turn a bounded retry into livelock, so cap concurrency with errgroup.SetLimit or a buffered channel. Escape analysis will heap-allocate the retry closure and anything that outlives one attempt, so keep the loop body free of freshly built slices. A time.After inside a loop used to pin a timer until it fired; Go 1.23 made unreferenced timers collectable, but time.NewTimer paired with Stop is still the portable form. RowsAffected itself costs nothing, since the count arrives in the command tag. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Devin free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.