# Add Connection Pooling to a GORM App

Yes. An agent reads how your app opens its database, sets pool limits and lifetimes on the sql.DB behind GORM from the environment, proves them, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-connection-pooling/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 what the pool is set to now. In an API laid out like realworld-apps/golang-gin-realworld-example-app, `common/database.go` opens SQLite with `gorm.Open(sqlite.Open(dbPath), &gorm.Config{TranslateError: true})`, calls `db.DB()` and sets `SetMaxIdleConns(10)`, and nothing else: no `SetMaxOpenConns`, no `SetConnMaxLifetime`, no `SetConnMaxIdleTime`. `GetDB()` returns the package-level `*gorm.DB` with a comment saying "you can create your connection pool here", and `TestDBInit()` does the same with `SetMaxIdleConns(3)`. Every error on the way is `fmt.Println("db err: ...")` and the function returns a `db` that may be nil. The driver is `gorm.io/driver/sqlite` over cgo `mattn/go-sqlite3`, the file path comes from `DB_PATH` with a default of `./data/gorm.db`, and `hello.go` holds `sqlDB.Close()` in a `defer` after `common.Init()`.

It sets the pool from the environment, in the one place the pool is made. A `configurePool(sqlDB *sql.DB)` in `database.go` reads `DB_MAX_OPEN_CONNS`, `DB_MAX_IDLE_CONNS`, `DB_CONN_MAX_LIFETIME` and `DB_CONN_MAX_IDLE_TIME`, with defaults the pull request writes down, and both `Init` and `TestDBInit` call it. For SQLite the defaults matter more than for Postgres: a file database takes one writer at a time, so the agent sets `_busy_timeout=5000` and `_journal_mode=WAL` on the DSN so a second connection waits rather than failing with `database is locked`, and defaults `DB_MAX_OPEN_CONNS` to 1 writer-safe when the DSN is an SQLite file and leaves it unbounded when `DB_PATH` is replaced by a Postgres URL later. `DB_PATH` and the four new variables are added to `.env.example` with the defaults as their values.

Errors stop being printed. `Init` returns `(*gorm.DB, error)`, `hello.go` calls `log.Fatal` on it instead of deferring a close on a database that may not exist, and the `fmt.Println` lines go. `TestDBInit` keeps its signature because `articles/unit_test.go` and `users/unit_test.go` call it, but panics on an open error so a test does not run against nil.

In its sandbox the agent runs `go build ./...` and `go test ./...` with the Go versions the CI matrix names, then adds `TestPoolSettings` to `common/unit_test.go`: it sets the four variables, calls `Init`, reads `sqlDB.Stats()` and asserts `MaxOpenConnections`, then opens two connections and runs an insert on each to show the busy timeout works instead of returning the locked error. It runs `bash scripts/coverage.sh` the way `ci.yml` does, and `golangci-lint` with the repository's `.golangci.yml`, and pastes the test output into the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add connection pool settings to this GORM app. Read common/database.go, common/unit_test.go, hello.go, .env.example, .github/workflows/ci.yml and .golangci.yml first. Add a configurePool function that reads DB_MAX_OPEN_CONNS, DB_MAX_IDLE_CONNS, DB_CONN_MAX_LIFETIME and DB_CONN_MAX_IDLE_TIME from the environment with sensible defaults, and call it from both Init and TestDBInit. Because the driver is SQLite, add _busy_timeout=5000 and _journal_mode=WAL to the DSN and default the open connections so writes do not fail with database is locked. Make Init return an error instead of printing it, and have hello.go log.Fatal on it; keep TestDBInit's signature. Add the variables to .env.example. Write TestPoolSettings in common/unit_test.go asserting sql.DB Stats and that two concurrent writers both succeed. Run go test ./..., scripts/coverage.sh and golangci-lint, and quote the output in the pull request. Open a 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 touching `common/database.go`, `common/unit_test.go`, `hello.go` and `.env.example`. The description lists each variable with its default and the SQLite DSN parameters, quotes the `go test ./...` summary including the new `TestPoolSettings`, the coverage total from `scripts/coverage.sh`, and the `golangci-lint` run with the three linters `.golangci.yml` enables.

The run's record keeps the full test transcript, including the `Stats()` values the test read back and the two concurrent inserts completing. A reviewer can see that the existing `TestConnectingDatabase`, which chmods the database file to force a failing ping, still passes with `Init` returning an error.

Before merging, a reviewer decides the production defaults. For the SQLite file one open connection with WAL is the safe choice; for the Postgres the README's directory listing hints at, `DB_MAX_OPEN_CONNS` should match the server's `max_connections` divided by the number of app replicas, and the lifetime should be shorter than any proxy's idle timeout.

## Run it on every database alert

This is the job to run when the monitor reports `database is locked`, `too many connections` or a climbing `WaitCount`. In the Project for the repository, an automation with the prompt above and a `webhook` trigger takes the alert body from Grafana or Sentry; the handler sends the trigger's URL an `Idempotency-Key` made from the alert's fingerprint, so a re-fired alert does not start a second run. The trigger adds the payload after the prompt, so the run reads which error the alert carried.

The first run adds the settings. A later run on a repository that already has them reads the alert, reproduces the error in the sandbox against the same driver, and opens a pull request that changes one default with the reason in the description, each on its own branch and linked to the alert.

## Why run it on Rush?

The pool behind GORM is `database/sql`, and its defaults are unlimited open connections and a two-connection idle cap, which is wrong in opposite directions for SQLite and for Postgres. Setting four numbers takes a minute; knowing which numbers takes running the app against the real driver and watching `Stats()`, and that is what nobody does before the alert. In a Rush sandbox the agent opens the same driver, runs two writers at once, reads the stats back and quotes them.

The test and the transcript stay with the run, so when the app moves from the SQLite file to Postgres the next person can read why the defaults were chosen and which ones to change. Across many Go services on the same pattern the job runs in parallel, one sandbox each, with the driver's own behavior as the evidence.

## Frequently asked questions

### Why touch the DSN if the task is about the pool?

Because with SQLite the pool and the lock are the same problem: two pooled connections writing at once fail with `database is locked` unless the driver waits. `_busy_timeout` makes it wait and WAL lets readers proceed during a write, so the pool limits mean what they say.

### Will this break the existing tests that chmod the database file?

No. `TestConnectingDatabase` forces a failing ping and still gets a database handle back; `Init` now returns the open error alongside it rather than printing, and the test asserts on the ping as before. The agent runs the whole suite to show it.

### What are the defaults when the variables are unset?

For an SQLite path, one open connection, one idle, no lifetime cap; for anything else, 25 open, 5 idle, a 30 minute lifetime and a 5 minute idle time. They are written in `.env.example` and in a comment above `configurePool`, and every one can be changed without a rebuild.

### Does Init still return a database on error?

It returns the error and whatever `gorm.Open` produced, which may be nil; `hello.go` stops with `log.Fatal` so the server never starts with no database. Before this change it started and every request failed later.

### Can the agent add a pool metrics endpoint too?

Yes, but it is a separate job. `sql.DB.Stats()` exposes open, idle, in-use and wait counts, and the agent can wire them into the existing Prometheus setup when asked; this pull request only sets the limits and tests them.

## More GORM jobs

- [Add Cursor Pagination to a GORM API](https://getrush.ai/run/add-cursor-pagination/gorm/)
- [Add Database Indexes to GORM Models](https://getrush.ai/run/add-database-indexes/gorm/)
- [Add Database Migrations to a GORM App](https://getrush.ai/run/add-database-migrations/gorm/)

## The same job on other stacks

- [Add Connection Pooling to a Ktor Server with HikariCP](https://getrush.ai/run/add-connection-pooling/ktor/)
- [Add Connection Pooling Limits to a Prisma App on Serverless](https://getrush.ai/run/add-connection-pooling/prisma/)
- [Add Connection Pool Settings to a Flask and SQLAlchemy App](https://getrush.ai/run/add-connection-pooling/sqlalchemy/)

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