# Add Query Timeouts to a GORM App

Yes. An agent threads the request context through your GORM calls with a deadline, maps a timed-out query to a response code, proves it in tests, and opens a PR.

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

## What the agent does

The agent starts with how the database is reached, because a timeout is a context, and a query with no context cannot have one. In an app laid out like realworld-apps/golang-gin-realworld-example-app, `common/database.go` opens SQLite through `gorm.io/driver/sqlite` with `TranslateError` on, sets `SetMaxIdleConns(10)` and nothing else on the pool, and hands out one package-level `*gorm.DB` through `GetDB()`. `articles/models.go` calls `common.GetDB()` twenty times and `users/models.go` seven, always without a context, and `users/middlewares.go` loads the current user the same way on every request. `go.mod` pins `gorm.io/gorm v1.25.12`, `gin v1.10.0` and Go 1.21, and `.github/workflows/ci.yml` runs `scripts/gofmt.sh`, `scripts/coverage.sh` over every package and golangci-lint on Go 1.21 through 1.23.

It then threads a context from the handler to the query. Each exported model function gains a `ctx context.Context` first parameter, and the `common.GetDB()` call inside becomes `common.GetDB().WithContext(ctx)`, so GORM passes the deadline to `database/sql` and the SQLite driver interrupts a statement that outlives it. The handlers in `articles/routers.go` and `users/routers.go` pass `c.Request.Context()` wrapped in `context.WithTimeout` with a duration from one constant in `common`, and `AuthMiddleware` does the same for its user lookup, so the deadline covers the whole request rather than one query.

Two things come from reading rather than from the GORM docs. `FindManyArticle` and `GetArticleFeed` each run a count and then a page, so the deadline is shared between the two statements, which is what a caller wants. And a timed-out query comes back as `context.DeadlineExceeded` wrapped in the GORM error, so each handler that today answers `404` with `Invalid param` on any error checks `errors.Is` first and answers `504` with a message naming the timeout, leaving the `404` for the cases it was written for. `SetConnMaxLifetime` is set beside `SetMaxIdleConns` while the file is open.

In its sandbox the agent runs `gofmt -l`, `go vet ./...`, `go build ./...` and `bash scripts/coverage.sh` as the workflow does, against the SQLite test database the tests create. It adds a test in `articles/unit_test.go` that calls `FindManyArticle` with a context already cancelled and asserts `errors.Is(err, context.Canceled)`, and a router test that sends `GET /api/articles` with a one-nanosecond deadline through a test server and asserts the `504` body. The existing `limit` and `offset` tests run unchanged, since the context parameter is added at the front and every caller is updated.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add query timeouts to this Gin and GORM app. Read common/database.go, hello.go, articles/models.go, articles/routers.go, users/models.go, users/routers.go, users/middlewares.go and .github/workflows/ci.yml first. Give every exported model function a context.Context first parameter and call GetDB().WithContext(ctx) inside it; in each handler and in AuthMiddleware pass c.Request.Context() under context.WithTimeout with a duration held as one constant in common. Where a handler answers 404 on any error, check errors.Is(err, context.DeadlineExceeded) first and answer 504 with a message naming the timeout. Set SetConnMaxLifetime beside SetMaxIdleConns. Do not change query logic or response shapes. Run gofmt, go vet, go build and bash scripts/coverage.sh. Add a model test with a cancelled context and a router test with a tiny deadline asserting the 504. Open a pull request quoting the test 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 across `common/database.go`, `articles/models.go`, `articles/routers.go`, `users/models.go`, `users/routers.go`, `users/middlewares.go` and the two test files. The diff is wide but shallow: one added parameter per model function, one `WithContext` per query, one `WithTimeout` per handler, and the `504` branch where a `404` used to swallow every error. The description quotes the `go vet` and `coverage.sh` output and lists the handlers whose error branch changed.

The run's record keeps the full test log, including the new cancelled-context test and the `504` router test, so a reviewer can read the body the handler returned rather than trusting the description.

Before merging, a reviewer sets the one timeout constant for their database and traffic, since the agent chose a value to prove the path rather than to tune it, and decides whether `504` or `503` is the code their clients expect for a slow database.

## Run it on every Linear issue labelled latency

A team with several Go services makes this a rule. In the Project for each repository, an automation with the prompt above and a `linear` trigger on `linear.issue.labeled` for the label `latency` starts a run when someone files "the articles list hung for forty seconds during the migration". The trigger adds the issue after the prompt, so the run reads which endpoint the issue names and writes the router test around that one.

Each run opens its own pull request on its own branch and links the issue. A service whose queries already take a context gets a description saying so, and a pull request that only adds the missing `WithTimeout` at the handlers or the `504` branch.

## Why run it on Rush?

Adding `WithContext` to twenty-seven call sites is tedious on a laptop and easy to leave half done: one query without it still blocks forever, and nothing in the build says which. In a Rush sandbox the agent changes every call, compiles the whole module so a missed caller fails the build, and proves the path with a cancelled context and a deadline a handler cannot meet.

The build and test output stay with the run and the pull request quotes them, so the reviewer sees `go vet` clean, the coverage script green and the `504` body rather than a list of files changed. Across several services the job runs in parallel, one sandbox and one pull request each.

## Frequently asked questions

### Does SQLite honour the context at all?

Yes. `database/sql` passes the context to the driver, and the SQLite driver GORM uses here interrupts a running statement when the deadline passes, so the test with a tiny deadline fails with `context.DeadlineExceeded` rather than finishing. On Postgres or MySQL the same code cancels the statement on the server side.

### Why change the model function signatures instead of a global timeout?

A global timeout on the pool cannot know when the request began. Passing `c.Request.Context()` down ties every query to its request, so a client that disconnects also cancels its queries, and one constant sets the deadline for all of them.

### Will the RealWorld API responses change?

Only for a query that times out, which today would hang and then surface as a `404` with `Invalid param`. Every successful response keeps its shape, and the existing tests for `limit`, `offset`, tags and the feed run unchanged.

### What about queries in middleware?

`AuthMiddleware` loads the user model on every request through `UpdateContextUserModel`; the pull request gives it the same deadline, so a slow users table cannot stall every route before a handler runs.

## More GORM jobs

- [Add Seed Data to a GORM App](https://getrush.ai/run/add-seed-data/gorm/)
- [Add Slow Query Logging to a GORM App](https://getrush.ai/run/add-slow-query-logging/gorm/)
- [Add Soft Delete to GORM Models](https://getrush.ai/run/add-soft-delete/gorm/)

## The same job on other stacks

- [Add Query Timeouts to a Flask and SQLAlchemy App](https://getrush.ai/run/add-query-timeouts/sqlalchemy/)
- [Add Query Timeouts to a sqlc Project](https://getrush.ai/run/add-query-timeouts/sqlc/)
- [Add Query Timeouts to a TypeORM + NestJS App](https://getrush.ai/run/add-query-timeouts/typeorm/)

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