# Fix N+1 Queries in a Gin API

Yes. An agent counts the queries behind each Gin list endpoint, batches the per-row lookups GORM still runs, proves the count with a test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/fix-n-plus-one-queries/gin/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by measuring, not guessing. In an API shaped like gothinkster/golang-gin-realworld-example-app, `go.mod` declares `go 1.21` with `gin-gonic/gin` v1.10.0, `gorm.io/gorm` v1.25.12 on the SQLite driver v1.5.7 and `stretchr/testify` v1.10.0. It turns on GORM's query logger, calls `GET /api/articles` with the default `limit` of 20 that `FindManyArticle` falls back to, and reads the log. `FindManyArticle` already preloads `Author.UserModel` and `Tags`, and `ArticlesSerializer.Response` in `articles/serializers.go` already batches favorites through `BatchGetFavoriteCounts` and `BatchGetFavoriteStatus`, so that part of the earlier fix is done. What the log still shows is one query per article: `ArticleUserSerializer.Response` builds a `users.ProfileSerializer`, whose `Response` in `users/serializers.go` calls `myUserModel.isFollowing(self.UserModel)`, and `isFollowing` in `users/models.go` runs a `First(&follow)` against `follow_models` every time. Twenty articles is twenty extra statements; the same author twenty times is still twenty.

The same shape repeats on `GET /api/articles/:slug/comments`. `ArticleCommentList` in `articles/routers.go` loads the comments with `getComments`, which preloads `Author.UserModel` in one query, then `CommentsSerializer.Response` serializes each comment's author through `ProfileSerializer` and pays the following lookup once per comment. `GET /api/articles/feed` goes through `GetArticleFeed`, which already batches the followed authors' ids, and then hands the result to the same `ArticlesSerializer`, so it carries the same per-author cost.

The fix follows the pattern the repository already uses for favorites. In `users/models.go` the agent adds `BatchGetFollowingStatus(followedByID uint, followingIDs []uint) map[uint]bool`, one `Where("followed_by_id = ? AND following_id IN ?", ...)` query that returns the set of followed ids, returning an empty map when the caller is anonymous (`myUserModel.ID == 0`) so no query runs at all. `ProfileSerializer` gets a `ResponseWithFollowing(following bool)` beside its existing `Response`, so single-profile routes in `users/routers.go` keep their behaviour. `ArticlesSerializer.Response` collects the distinct `Author.UserModel.ID` values, calls the batch once, and passes each author's flag down through `ArticleUserSerializer`; `CommentsSerializer.Response` does the same for comment authors. The single-article path in `ArticleSerializer.Response` is left alone, because one article is one lookup.

Proof goes into `articles/unit_test.go`, in the style `common/unit_test.go` sets: `httptest.NewRecorder`, a `gin` engine, `assert.New(t)`. The agent registers a GORM `Query().After` callback that increments a counter, seeds several articles by different authors, and asserts the number of statements for the list route is the same with 5 articles as with 20, and that the comments route is likewise flat. Before pushing it runs what `.github/workflows/ci.yml` runs: `bash ./scripts/gofmt.sh`, `bash ./scripts/coverage.sh` (which runs `go test -coverprofile` package by package), `golangci-lint run` with the `staticcheck`, `unused` and `misspell` linters from `.golangci.yml`, and `gosec ./...`. It also runs `scripts/run-api-tests.sh`, the Realworld Postman collection through Newman, because the JSON shape of `author.following` must not change.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Find and fix N+1 queries in this Gin API and open a pull request. Read go.mod, hello.go, articles/models.go, articles/serializers.go, articles/routers.go, users/models.go, users/serializers.go, common/unit_test.go, .golangci.yml, scripts/coverage.sh and .github/workflows/ci.yml first. Turn on GORM's query logger and call GET /api/articles, GET /api/articles/feed and GET /api/articles/:slug/comments with seeded data; list every statement that runs once per row. Favorites are already batched; the per-author following check in users.ProfileSerializer is not. Add a BatchGetFollowingStatus function in users/models.go that answers for a list of user ids in one query and returns an empty map for an anonymous caller, add ResponseWithFollowing on ProfileSerializer, and use them from ArticlesSerializer.Response and CommentsSerializer.Response. Do not change the JSON shape of any response or the single-article and single-profile paths. Add a test in articles/unit_test.go that counts queries with a GORM callback and asserts the list and comments routes run the same number of statements for 5 rows as for 20. Run scripts/gofmt.sh, scripts/coverage.sh, golangci-lint run, gosec ./... and scripts/run-api-tests.sh, and paste the before and after query logs for GET /api/articles in the pull request.",
  "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 touches `users/models.go`, `users/serializers.go`, `articles/serializers.go` and `articles/unit_test.go` and nothing in `articles/routers.go` or `hello.go`. The description shows two GORM logs for `GET /api/articles?limit=20`: the one from `main`, with its row of `SELECT * FROM follow_models WHERE ...` statements, and the one from the branch, where that row has become a single `IN` query, plus the test output from `scripts/coverage.sh` for the `articles` and `users` packages.

On a repository with this `CI` workflow the pull request runs the gofmt check, the coverage script on Go 1.21, 1.22 and 1.23, golangci-lint, the gosec scan, and the Newman run of the Realworld collection against the started server. The collection asserts status codes and body shapes, and `author.following` keeps its name and type, so it passes unchanged.

A reviewer checks that the batch query is keyed by `UserModel.ID` and not by `ArticleUserModel.ID`, which are different tables in this codebase, that an anonymous request still answers `following: false` without a query, and that the test counts statements through a callback rather than parsing log text. Then they merge and watch the article list's database time on the next deploy.

## Run it on every slow list endpoint

A team that runs several Gin services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own serializers, so a service that already batches everything comes back with a report and no pull request, while one that pays a lookup per row gets a branch with the batch and the counting test.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and the query logs from. Send a `request_id` with each start so a retried call after a timeout returns the run already started instead of opening a second pull request.

## Why run it on Rush?

An N+1 is invisible in a unit test with three rows and obvious in production with a thousand. The proof is a query log at a realistic row count, and that means a seeded database and a running server. In a Rush sandbox the agent builds the binary, seeds SQLite through the models' `AutoMigrate`, calls the routes with `limit=20`, and keeps the log it read in the run's record, so the pull request quotes the exact statements it removed instead of asserting they were there.

The repository already has a four-job CI with gofmt, coverage, lint, a security scan and a Postman suite, and the agent runs the same scripts before pushing, so the pull request arrives green rather than failing on a `misspell` finding in a comment. The same request body works on every Gin service a team owns; each run finds its own per-row lookups.

## Frequently asked questions

### Will it change the API responses?

No. `ArticleResponse`, `CommentResponse` and `ProfileResponse` keep their fields and JSON tags. The change is where `following` is computed, not what it says, and the Realworld Postman collection in `scripts/run-api-tests.sh` is run to show that.

### GORM has Preload. Why not preload the follows?

`following` is relative to the caller, not a property of the author row, so there is no association to preload. A single query on `follow_models` filtered by the caller's id and the authors' ids answers it, which is the same approach `BatchGetFavoriteStatus` already takes for favorites.

### How does the test count queries?

It registers a callback with `db.Callback().Query().After("gorm:query")` that increments a counter, runs the route twice with different row counts, and asserts the counts match. A log-parsing test would break on the next GORM upgrade; a callback does not.

### Does this work with Postgres instead of SQLite?

Yes. The batch is a plain `IN` query that GORM renders for any driver. The repository ships with the SQLite driver and a `DB_PATH` variable, so the test uses that; a service on `gorm.io/driver/postgres` runs the same code.

## More Gin jobs

- [Move a Gin API From SQLite to Postgres](https://getrush.ai/run/migrate-sqlite-to-postgres/gin/)
- [Review Pull Requests on a Gin API](https://getrush.ai/run/review-pull-requests/gin/)
- [Security Audit of a Gin API](https://getrush.ai/run/security-audit/gin/)

## The same job on other stacks

- [Fix N+1 KV Reads in a Hono API](https://getrush.ai/run/fix-n-plus-one-queries/hono/)
- [Fix N+1 Queries in a Laravel App](https://getrush.ai/run/fix-n-plus-one-queries/laravel/)
- [Fix N+1 Queries in a Phoenix App](https://getrush.ai/run/fix-n-plus-one-queries/phoenix/)

## 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/)
