Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Optimistic Locking Implementation in Go

14 min readintermediate
Website QA and SEO audits

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 never takes a lock. You read a record together with a version token (an integer, a timestamp, a SQL Server rowversion, an HTTP ETag), mutate a private copy, then write back with the token in the predicate: UPDATE ... SET v = v + 1 WHERE id = ? AND v = ?. If the affected-row count comes back zero, somebody else wrote first, so you discard your work and retry from a fresh read. The whole design is a bet that conflicts are rare, and the cost of losing the bet is a wasted round trip rather than a stalled thread. That is the opposite trade from mutual exclusion, which pays coordination cost on every access so conflicts become impossible. Two hazards are permanent. The retry loop must be bounded and jittered or contention becomes livelock. And a token that can be reused makes equality a lie: the value went A, then B, then back to A, your check passes, and a change you never observed is silently overwritten. The eight languages diverge because the token lives somewhere different in each. Some hand you a declarative version column in the ORM, some make you count rows off the driver yourself, and in shared memory the primitive is a hardware compare-and-swap whose exact signature, memory ordering rules and spurious-failure behaviour are genuinely different per language.

Optimistic Locking in Go: what you actually reach for

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.

Go implementation

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. Reviewers want ctx threaded through every attempt so the caller can cancel mid-retry, defer tx.Rollback() left in place after a successful Commit because it returns ErrTxDone and is harmlessly ignored, and a computed backoff rather than a constant Sleep. Fanning goroutines at one hot row without an errgroup limit or a buffered channel gets rejected on sight.
go
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 Free

The Go-specific 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. 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.

Performance in Go, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Optimistic Locking between languages.

Real-World Applications

Optimistic Locking is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Optimistic Locking helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Optimistic Locking appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Optimistic Locking over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Optimistic Locking to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Devin free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.