Backend Development 7 min read

Implementing Optimistic Locking in Go with GORM

This article explains how to implement optimistic locking in Go using GORM by adding a version field, writing raw SQL updates, creating a reusable wrapper function with retry logic, and leveraging interfaces and type assertions to handle concurrency safely.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Implementing Optimistic Locking in Go with GORM

When developing Go services that require safe concurrent updates, the author introduces an optimistic locking solution that adds a version column to the database table and uses a simple SQL UPDATE statement to ensure the version matches before applying changes.

The article provides a concrete GORM example, defining an Optimistic struct with Id , UserId , Amount , and Version fields, and demonstrates a test that updates the amount while incrementing the version atomically.

To avoid repetitive hard‑coded updates, a generic wrapper UpdateWithOptimistic is introduced. It accepts a GORM DB instance, a model implementing a Lock interface, an optional callback for custom retry logic, a maximum retry count, and the current retry counter.

The function checks the retry limit, reads the current version, attempts the conditional update, and if no rows are affected, it optionally invokes the callback, sleeps briefly, reloads the latest data, and recursively retries until success or the retry limit is reached.

Because Go lacks generics (at the time of writing), the version field is accessed via a Lock interface with GetVersion and SetVersion methods, allowing compile‑time verification that structs used with the optimistic lock implement the required methods.

The article also discusses type assertions needed in the callback to convert the generic Lock back to the concrete struct (e.g., *Optimistic ) before applying business logic, noting the similarity to Java's down‑casting and the runtime risks involved.

Overall, the guide offers a reusable, interface‑driven approach to optimistic locking in Go, complete with code snippets, retry handling, and considerations for performance and type safety.

DatabaseconcurrencyGooptimistic lockGorm
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.