# Add Prometheus Metrics to a GORM Service from a Linear Issue

Yes. Label the Linear issue and an agent registers GORM's Prometheus plugin, adds request metrics and a guarded /metrics route to your Go service, and opens a PR.

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

## What the agent does

The agent starts from the Linear issue and the repository in its own sandbox, and reads how the database and the router are built before adding a metric. In a service shaped like gotify/server, `New` in `database/database.go` opens MySQL, Postgres or SQLite through `gorm.io/gorm` v1.31.2 with a zerolog-backed logger, sets `SetMaxOpenConns(10)`, or 1 for SQLite because `go-sqlite3` cannot take concurrent writes, and `SetConnMaxLifetime(9 * time.Minute)` for MySQL. `Create` in `router/router.go` builds a `gin.New()` engine with `accessLogger`, `gin.Recovery()`, the error handler and `location.Default()`, registers `/health`, `/swagger`, `/docs`, the message, application, client and user routes, and guards admin routes with `authentication.RequireAdmin`, which accepts a client token in the `X-Gotify-Key` header, a `Bearer` authorization header or a `token` query parameter. Configuration is read from `GOTIFY_*` environment variables in `config/config.go` through the `parseBool` and `parseString` helpers in `config/parse.go`, with every key named in `config/keys.go` and documented in `gotify-server.env.example`.

For the pool, it registers `gorm.io/plugin/prometheus` in `database.New`: `db.Use(prometheus.New(prometheus.Config{DBName: "gotify", RefreshInterval: 15, StartServer: false}))`. The plugin reads `sql.DBStats` every 15 seconds and publishes nine gauges on the default registry with a constant `db_name` label: `gorm_dbstats_max_open_connections`, `gorm_dbstats_open_connections`, `gorm_dbstats_in_use`, `gorm_dbstats_idle`, `gorm_dbstats_wait_count`, `gorm_dbstats_wait_duration`, `gorm_dbstats_max_idle_closed`, `gorm_dbstats_max_lifetime_closed` and `gorm_dbstats_max_idletime_closed`. With a 10 connection cap, `wait_count` and `wait_duration` are the two that say whether the cap is too low under load, which is the question the issue asks. `StartServer` stays false, because the service already has an HTTP server, and when the dialect is `mysql` the agent adds the plugin's `MySQL` collector with `Threads_running` in `VariableNames`, so the server's own thread count sits beside the pool figures.

For requests, it adds a `metrics` package with a `HistogramVec` named `gotify_http_request_duration_seconds` labelled by `method`, `route` and `status`, where `route` is `ctx.FullPath()` so `/application/:id/message` stays one series rather than one per id, and a counter `gotify_messages_created_total` incremented in `createMessage` in `api/message.go`, the one place every message passes through whether it came from a token, a client or the MCP handler. A gin middleware records the histogram after `accessLogger` and skips `/stream`, the websocket clients hold open for hours, and `/metrics` itself. The route is `g.GET("/metrics", authentication.RequireAdmin, gin.WrapH(promhttp.Handler()))`, so a scrape needs an admin client token, which Prometheus sends from `authorization.credentials` in its scrape config as a `Bearer` header this service already reads. A `GOTIFY_METRICS_ENABLED` key, default false, follows the config pattern, and the route and plugin are registered only when it is set.

Because `make check-ci` runs `check-swagger`, which regenerates `docs/spec.json` from the `swagger:operation` comments and fails when the committed file differs, the agent adds the annotation for `GET /metrics`, installs the pinned `go-swagger` with `make download-tools` and runs `make update-swagger` so the spec it commits is the one CI will generate. It extends `router/router_test.go`'s integration suite with three cases: `/metrics` answers 401 with no token, 200 with the admin client's token and a body that contains `gorm_dbstats_open_connections{db_name="gotify"}`, and 404 when the key is off. It runs `go test --race ./...`, the Go half of `make test`, and `golangci-lint run` as `make check-go` does, then starts the server on SQLite in its sandbox with metrics on, posts a message, scrapes `/metrics` with `curl` and reads the counter and the histogram buckets back.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Go service, which uses GORM and gin. Read go.mod, app.go, database/database.go, router/router.go, api/message.go, auth/authentication.go, config/config.go, config/keys.go, config/parse.go, gotify-server.env.example, Makefile, docs/swagger.go and .github/workflows/build.yml first. Register gorm.io/plugin/prometheus in database.New with DBName gotify, the default refresh interval and StartServer false, adding the plugin's MySQL collector with Threads_running when the dialect is mysql. Add a metrics package with a request duration histogram labelled by method, route from ctx.FullPath() and status, recorded by a gin middleware after accessLogger that skips /stream and /metrics, and a messages created counter incremented in createMessage. Serve promhttp.Handler at GET /metrics behind authentication.RequireAdmin, with a swagger:operation comment, and only when a new GOTIFY_METRICS_ENABLED setting is true, following the existing config and keys pattern and documenting it in gotify-server.env.example. Run make download-tools and make update-swagger and commit docs/spec.json. Add integration tests in router/router_test.go for 401 without a token, 200 with the admin token containing gorm_dbstats_open_connections, and 404 when disabled. Run go test --race ./... and golangci-lint run, start the server on SQLite with metrics on, post a message, scrape /metrics with curl, and paste the scrape and the test output into the pull request. Change nothing else about routes or authentication.",
  "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

The pull request links the Linear issue, adds the `metrics` package, and edits `database/database.go`, `router/router.go`, `router/router_test.go`, `api/message.go`, `config/config.go`, `config/keys.go`, `gotify-server.env.example`, `docs/spec.json`, `go.mod` and `go.sum`. Its description pastes the `curl -H 'X-Gotify-Key: …' /metrics` scrape from the sandbox, showing the nine `gorm_dbstats_*` gauges with `db_name="gotify"`, the histogram buckets for the `POST /message` call it made and `gotify_messages_created_total 1`, beside the `go test --race ./...` and `golangci-lint run` output, and notes that `make check-swagger` passes because `docs/spec.json` was regenerated with the pinned tool.

A deployment that leaves `GOTIFY_METRICS_ENABLED` unset has no `/metrics` route and no plugin registered, so its behavior is unchanged. With it on, the only visible change is the new route, and the swagger document describes it like any other.

Before merging, a reviewer decides whether guarding `/metrics` with an admin client token is right for their scrape setup or whether a network restriction is enough, confirms the histogram buckets suit their latencies, since the agent keeps Prometheus's defaults, and checks that the `route` label stays bounded if routes are added later.

## Run it on every Linear issue labelled agent

Add an automation to the Project with this prompt and a `linear` trigger on `linear.issue.labeled` with the label you reserve for the agent in its `labels`. Each labelled issue starts one run with the issue as its context, on its own branch; the trigger adds the issue after the prompt and fills in no placeholder, and a change made by an app integration never fires it, so the agent's own comment on the issue starts nothing.

The automation's `max_runs_per_hour` holds a burst of labels to that many runs an hour: a fire past it is created `queued` and starts when the hour has room, and one past a second hour's worth is skipped as `rate_limited` until the issue is labelled again. From your own server, the same run starts with this request and the issue URL in `resources`, with a `request_id` that is a UUID v5 of the issue id so a retried start returns the run already begun.

## Why run it on Rush?

Metrics are easy to add and easy to add wrong: a label on a user id that grows without bound, a `/metrics` route open to the internet, a swagger check that fails CI because the spec was not regenerated with the pinned tool. The agent checks each one against the real service in its own sandbox, scraping the endpoint it added and running the same `make` targets CI runs, and the pull request carries the scrape rather than a promise.

The transcript keeps every command and its output, so the reviewer reads the scrape, the test run and the swagger regeneration without checking the branch out. A team with several Go services on GORM instruments them in parallel, each in its own sandbox, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why not let the plugin start its own metrics server?

`StartServer: true` would open a second listener on port 8080 with no authentication, outside the TLS, trusted proxy and `MaxBodyBytes` settings the main server applies. Serving `promhttp.Handler()` on the existing gin engine keeps one listener and lets the route sit behind `RequireAdmin` like the other admin routes.

### How does Prometheus authenticate to scrape?

With an admin client token. `RequireAdmin` reads a token from the `X-Gotify-Key` header, a `Bearer` authorization header or a `token` query parameter, and Prometheus's `authorization.credentials` scrape setting sends the Bearer form. The pull request includes a scrape config snippet with the token read from a file.

### Which GORM metrics does it expose?

The nine `sql.DBStats` gauges the plugin publishes, from `gorm_dbstats_max_open_connections` to `gorm_dbstats_max_idletime_closed`, each with a constant `db_name` label. On MySQL the plugin's collector adds `Threads_running`. The two to alert on with a 10 connection cap are `gorm_dbstats_wait_count` and `gorm_dbstats_wait_duration`, and the description says so.

### Why is the route label from FullPath and not the request path?

`ctx.FullPath()` returns the registered pattern, `/application/:id/message`, so every application shares one series. The raw path would create a series per id and the histogram would grow with your data. The middleware records nothing for a request that matched no route, which is also where a scanner would otherwise inflate the series.

### Does the swagger check in CI still pass?

Yes, because the agent regenerates `docs/spec.json` with `make update-swagger` using the `go-swagger` commit `make download-tools` pins, and commits the result. `check-swagger` runs the same generation and compares with `git status`, so running it the same way is the only way to keep CI green when a route gains an annotation.

## More GORM jobs

- [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/)
- [Add Slow Query Logging to a GORM App](https://getrush.ai/run/add-slow-query-logging/gorm/)

## The same job on other stacks

- [Add Prometheus Metrics to a Koa API](https://getrush.ai/run/add-prometheus-metrics/koa/)
- [Add Prometheus Metrics to a Ktor Server](https://getrush.ai/run/add-prometheus-metrics/ktor/)
- [Add Prometheus Metrics to a Leptos App](https://getrush.ai/run/add-prometheus-metrics/leptos/)

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