# Add Optimistic Locking to a GORM Model in a Gin API

Yes. An agent adds a version column to your GORM model, makes updates refuse a stale version with a 412, exposes it as an ETag, tests the race, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-optimistic-locking/gorm/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the write path before touching the model. In a Gin API laid out like realworld-apps/golang-gin-realworld-example-app, `articles/models.go` declares `ArticleModel` on `gorm.Model` with a `Slug` under `uniqueIndex`, `Title`, `Description`, `Body`, an `AuthorID` and a many-to-many `Tags`, and its `Update` method is one line: `db.Model(model).Updates(data)`. `ArticleUpdate` in `articles/routers.go` loads the row with `FindOneArticle`, checks `AuthorID` against the caller, binds the body through `NewArticleUpdateValidator`, builds an `updates` map from whichever of `title`, `description` and `body` were set, regenerates the slug when the title changed, and calls `Update` in a loop that retries on `gorm.ErrDuplicatedKey`. Two requests from the same author that read the article, edit different fields and save both succeed, and the second silently overwrites the first. `go.mod` pins `gorm.io/gorm` at `v1.25.12` on `gorm.io/driver/sqlite` `v1.5.7`, and `common.Init` in `common/database.go` opens with `TranslateError: true`.

It adds a `Version uint` field to `ArticleModel` with a `gorm:"default:1"` tag, which `Migrate` in `hello.go` picks up through `db.AutoMigrate(&articles.ArticleModel{})`, and rewrites `Update` to take the version it expects: the statement becomes `db.Model(model).Where("version = ?", model.Version).Updates(data)` with `version` set to `model.Version + 1` in the same map, and the method returns a named `ErrStaleVersion` when `RowsAffected` is zero and the row still exists. `ReplaceTags`, which writes the join table through an association, is left as it is, since it replaces the whole set and has no read-modify-write.

The version reaches the client as an `ETag` on article reads, set in `ArticleRetrieve` and in the response of `ArticleUpdate`, and comes back as `If-Match` on `PUT /api/articles/:slug`. When the header is present and does not match the loaded row's version, the handler answers `412 Precondition Failed` with the body shape `common.NewErrorMessage` already produces, before any write. When the header is absent, the update runs as before, so the RealWorld API tests that `scripts/run-spec-tests.sh` drives, which send no such header, keep passing, and clients opt in by echoing the tag. The serializer in `articles/serializers.go` also gets a `version` field beside `updatedAt`.

Tests go in `articles/unit_test.go`, next to `TestArticleUpdateEndpoint` and `TestArticleUpdateSlugRaceRetries`, which already open a throwaway SQLite file through `common.TestDBInit` and sign requests with `common.HeaderTokenMock`. The new cases read an article, send two `PUT`s with the same `If-Match`, and assert the first returns 200 with a new tag and the second 412 with the row unchanged; a `PUT` with no header still returns 200; and a direct `Update` with a stale `Version` returns `ErrStaleVersion` with `RowsAffected` zero. It runs `bash scripts/gofmt.sh`, `bash scripts/coverage.sh` and `golangci-lint run --timeout=5m` at `v1.61`, the three checks `.github/workflows/ci.yml` runs across Go 1.21 to 1.23, and opens the pull request with their output.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add optimistic locking to the article model in this Gin and GORM API. Read go.mod, hello.go, common/database.go, common/utils.go, articles/models.go, articles/routers.go, articles/validators.go, articles/serializers.go, articles/unit_test.go, scripts/coverage.sh, scripts/gofmt.sh and .github/workflows/ci.yml first. Add a Version uint field to ArticleModel with a default of 1 so AutoMigrate adds the column. Change ArticleModel.Update to add a where clause on the current version and set version+1 in the same Updates call, returning a named ErrStaleVersion when RowsAffected is zero and the row exists. Expose the version as an ETag on article reads and update responses and as a version field in the serializer. In ArticleUpdate, when an If-Match header is present and does not equal the loaded version, answer 412 with the existing error body shape before writing; with no header, update as before so the RealWorld spec tests keep passing. Add tests in articles/unit_test.go for two updates with the same If-Match, an update with no header, and the stale Update error. Run scripts/gofmt.sh, scripts/coverage.sh and golangci-lint, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `articles/models.go`, `articles/routers.go`, `articles/serializers.go` and `articles/unit_test.go`, with the `ETag` and `If-Match` contract written into the description beside the SQL the new `Update` issues. The description quotes the `go test` output from `scripts/coverage.sh` and the lint run.

The run's record keeps the test run in which the second `PUT` comes back 412, so a reviewer sees the lost update refused rather than reads that it would be.

Before merging, a reviewer decides whether `If-Match` stays optional. The pull request leaves it optional so existing clients and the spec tests are unaffected, and names the one-line change that would make a missing header a 428 once every client sends it.

## Run it on every Linear issue labelled agent

A lost update is reported as a bug, usually with two people's names and one article. With Linear connected under Settings → Connections in the console, add an automation to the Project with a `linear` trigger on `linear.issue.labeled` and the label `agent`. Its saved prompt asks for this without the model name: read the model and handler the issue names, add a version column, check it on update, expose it as an ETag, write the race test and open a pull request. The trigger adds the issue after the prompt and fills in no placeholder, so which model comes from the issue.

The trigger fires only when someone in your Rush org adds the label, and a change made by an app integration never fires it. A team with several GORM services sends this body once per repository from its own server instead, each with its repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started.

## Why run it on Rush?

The bug is a race, and the proof is a test that stages the race: two reads, two writes, one refusal. The agent writes that test and runs it in its own sandbox against the project's own SQLite test database, under the same Go versions the workflow uses, and the record keeps the run. On a laptop the race is reproduced once by hand and never again.

Each service gets its own sandbox and its own pull request, so a company with several GORM APIs runs them all at once and reviews a diff of four files per service with the test output beside it. The contract is the same everywhere: a version in the row, an `ETag` out, an `If-Match` in, a 412 when they disagree.

## Frequently asked questions

### Why not use GORM's hooks or a plugin for this?

A `where` clause on the version plus `RowsAffected` is the whole mechanism, and it reads as plain SQL in the one `Update` method the handler already calls. A hook would hide the check inside the model and still need the same `RowsAffected` test, so the pull request keeps it explicit.

### Does SQLite support this, or only Postgres?

The check is an `UPDATE ... WHERE id = ? AND version = ?` and a row count, which every database GORM drives supports. The tests run on the SQLite file `common.TestDBInit` creates, and the same code works unchanged when the driver changes.

### What happens to clients that never send If-Match?

Nothing changes for them: the handler updates as before and bumps the version. The version is still checked inside `Update`, so two writes that race from such clients both succeed as they do today. Sending the tag is how a client opts in to the refusal.

### Why 412 and not 409?

Because the refusal is about a precondition the client stated in `If-Match`, which is what 412 means in HTTP. The agent uses the existing `common.NewErrorMessage` shape for the body so the client reads it the same way as a 404 or 403 from the same handler.

## More GORM jobs

- [Add Prometheus Metrics to a GORM Service from a Linear Issue](https://getrush.ai/run/add-prometheus-metrics/gorm/)
- [Add Query Timeouts to a GORM App](https://getrush.ai/run/add-query-timeouts/gorm/)
- [Add Seed Data to a GORM App](https://getrush.ai/run/add-seed-data/gorm/)

## The same job on other stacks

- [Add Optimistic Locking to a Mongoose API](https://getrush.ai/run/add-optimistic-locking/mongoose/)
- [Add Optimistic Locking to Prisma Models](https://getrush.ai/run/add-optimistic-locking/prisma/)
- [Add Optimistic Locking to a Sequelize App](https://getrush.ai/run/add-optimistic-locking/sequelize/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
