# Add Prometheus Metrics to a Fastify App

Yes. An agent adds a prom-client plugin to your Fastify app with request duration and count by route template, process metrics and a /metrics route, tested.

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

## What the agent does

The agent reads how the app is put together before it adds a plugin, because in Fastify the registration order is the design. In an app like fastify/demo, `package.json` pins `fastify ^5.10.0` as an ES module compiled with TypeScript `~6.0.3` on `fastify-tsconfig`, and `src/app.ts` loads three directories with `@fastify/autoload`: `plugins/external` first, then `plugins/app`, then `routes` with `autoHooks` and `cascadeHooks`. The external plugins are `env`, `cors`, `helmet`, `knex` over `mysql2`, `multipart`, `rate-limit` with `RATE_LIMIT_MAX` per minute, `sensible`, `session`, `static`, `swagger` at `/api/docs` with `hideUntagged: true`, and `under-pressure`, which watches event loop delay, heap and RSS and runs `SELECT 1` through knex but exposes nothing a scraper could read. `src/server.ts` builds the instance with a pino logger that goes through `pino-pretty` on a TTY and otherwise uses `LOG_LEVEL`, and `src/routes/api/autohooks.ts` refuses any request under `/api` without a session user. There is no metrics dependency and no `/metrics` route in the tree.

The change is one dependency and one plugin. The agent adds `prom-client` and writes `src/plugins/external/metrics.ts` as a `fastify-plugin` named `metrics`, so autoload registers it with the other external plugins and routes can rely on it. The plugin creates its own `Registry` per Fastify instance rather than using prom-client's global default, because `test/helper.ts` builds a fresh app for every test and a shared registry would throw on the second registration. It calls `collectDefaultMetrics` on that registry for the process and Node.js meters, and adds a `Histogram` named `http_request_duration_seconds` and a `Counter` named `http_requests_total`, both labelled `method`, `route` and `status_code`. An `onResponse` hook observes `reply.elapsedTime` and uses `request.routeOptions.url` for the `route` label, so `GET /api/tasks/7` and `GET /api/tasks/8` share one `/api/tasks/:id` series and a request that matched no route is labelled `unmatched`. A `Gauge` with a `collect` callback reads the knex pool's used, free and pending counts, so a connection leak shows on a chart before it shows as `503` from under-pressure.

The route lives where a probe can reach it. `src/routes/metrics/index.ts` mounts `GET /metrics` outside `src/routes/api`, so the session hook never sees it, with `config: { rateLimit: false }` so a scrape every few seconds never spends the `RATE_LIMIT_MAX` budget the tests set to 4, and with no `tags`, which keeps it out of the Swagger document under `hideUntagged`. It answers the registry's `contentType` and `metrics()` text. Nothing in the existing routes changes; the hook sees every request, including the `404` the not-found handler in `src/app.ts` answers and the `429` from the limiter.

Tests follow `test/helper.ts`, whose `build(t)` registers `serviceApp` through `fastify-plugin` and closes the app after the test. `test/routes/metrics/metrics.test.ts` requests `/` once, then `/metrics`, and asserts a `200` with a `text/plain` content type and a `http_requests_total` line whose `route` label is `/` and whose `status_code` is `200`; a second test logs in with `injectWithLogin`, fetches one task by id and asserts the `route` label reads `/api/tasks/:id` rather than the number; a third sends more requests to `/metrics` than `RATE_LIMIT_MAX` and expects every one to be `200`, in the way `test/app/rate-limit.test.ts` expects the fifth request to `/` to be `429`. `npm test` runs `npm run db:seed && c8 npm run test:run` over `./test/**/*.ts` with `tsx --test`, and the seed needs `CAN_SEED_DATABASE=1` and the `mysql:8.4` from `docker-compose.yml` after `npm run db:create` and `npm run db:migrate`, so the agent does what `.github/workflows/ci.yml` does on Node 22 and 24: install, `npm run build -- --noEmit`, `npm run lint`, migrate, test. It also starts the server with `npm run dev` and reads `/metrics` once, so the pull request can quote the first lines of a real scrape.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Fastify app. Read package.json, src/app.ts, src/server.ts, every file under src/plugins/external, src/routes/api/autohooks.ts, src/routes/home.ts, test/helper.ts and .github/workflows/ci.yml first. Add prom-client and write src/plugins/external/metrics.ts as a named fastify-plugin that creates its own Registry per instance, calls collectDefaultMetrics on it, and registers an http_request_duration_seconds histogram and an http_requests_total counter labelled method, route and status_code, observed from an onResponse hook using reply.elapsedTime and request.routeOptions.url so the route label is the template and never a concrete id; label unmatched requests as unmatched. Add a gauge that reads the knex pool's used, free and pending counts. Add src/routes/metrics/index.ts with GET /metrics outside the api directory, rate limiting switched off for the route, no tags, answering the registry's content type and text. Add node:test tests in the style of test/app/rate-limit.test.ts: /metrics answers 200 with the counter line for a prior request to /, a logged-in request to one task shows the /api/tasks/:id template as its route label, and more requests to /metrics than RATE_LIMIT_MAX all answer 200. Start MySQL from docker-compose.yml, run npm run db:create and npm run db:migrate, then npm test with CAN_SEED_DATABASE=1 and RATE_LIMIT_MAX=4 as the CI workflow does, plus npm run build -- --noEmit and npm run lint. Start the server once and read /metrics. Do not change the under-pressure or rate-limit configuration, .env.example or any workflow. Open a pull request that lists the meters and their labels, quotes the first lines of the scrape and the test and lint 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 on its own branch adding `src/plugins/external/metrics.ts`, `src/routes/metrics/index.ts`, `test/routes/metrics/metrics.test.ts` and the `prom-client` entry in `package.json` and `package-lock.json`. The body lists each meter with its labels, says which come from `collectDefaultMetrics` and which from the hook, quotes the first lines of the scrape the agent read from the running server, and quotes the `npm test` summary with its coverage table, the type check and the lint result.

The session read names the repository and the pull request, and the transcript keeps the MySQL start, the migrations, the seed, the first test run in which the metrics tests failed before the plugin existed, the passing run, the lint, and the request to `/metrics`. `GET /o/{org}/p/{project}/sessions/{id}/changes` lists the files with their diff.

Before merging, a reviewer checks that the `route` label is the template on every series and that nothing user-controlled, such as a query string, reached a label; that `/metrics` sits outside `src/routes/api` and carries `rateLimit: false`; and that the registry is created inside the plugin rather than imported as prom-client's global one, since the test suite builds many instances in one process. Where the service runs behind a network that should not see `/metrics`, the reviewer asks for a follow-up that binds it to a second port or an allow-list.

## Run it on every Fastify service without a /metrics route

Metrics are a hand-off job: well specified, mostly reading, and the same on every service. From Claude Code or Codex with Rush connected as an MCP server at `https://api.phoenix.so/mcp`, ask for a `create_session` with this prompt and your repository, keep working on something else, and read the pull request later with `get_session`; `wait_for_sessions` waits up to 50 seconds per call when you would rather block. The sandbox parks at the end of the turn with `node_modules` and the MySQL container's data still there, so a `send_session_message` asking for a second histogram on the knex query time wakes it where it stopped.

From a script, send one `POST /o/{org}/sessions` per Fastify service with the repository in `resources` and a `request_id` per repository, so a retried call returns the run it already started. With a `webhook_url` on the key, each run the key started POSTs `run.completed`, `run.failed` or `run.cancelled` when its turn ends, with `data.session_url` to read for the pull request link.

## Why run it on Rush?

In this app a metrics plugin done carelessly fails in three quiet ways: a `route` label taken from `request.url` makes one series per task id, a `/metrics` route placed under `/api` answers `401` to the scraper, and a default limiter answers `429` after four scrapes a minute. The agent reads the autoload order, the hooks and the limiter in its own sandbox and places the plugin and the route where they work, then runs the seeded test suite against the repository's own MySQL to prove it.

The pull request carries its evidence: the first lines of a real scrape, the test run with coverage, the type check and the lint are in the transcript, and the diff is a plugin, a route and a test. A platform team that wants the same meters on every Fastify service runs the same request against each repository, one sandbox and one pull request each, with the plugins directory read from each repository rather than assumed.

## Frequently asked questions

### Why prom-client directly rather than a Fastify metrics plugin?

Because this app's constraints are in its own plugins: the limiter, the session hook under `/api` and the `hideUntagged` Swagger setting. A hook of a few lines on `onResponse` with prom-client gives the agent control of the route label, the registry per instance and the route's options, and leaves nothing to a third package's defaults. If your team already standardises on a plugin, name it in the prompt and the agent uses it.

### Will the metrics show one series per task id?

No. The `route` label comes from `request.routeOptions.url`, the matched template, so `/api/tasks/:id` is one series for every id, and a request that matched no route is labelled `unmatched`. The test for the logged-in task request asserts exactly that, and the prompt forbids concrete ids in labels.

### Is /metrics behind the session or the rate limiter?

Neither. The route lives under `src/routes/metrics`, outside `src/routes/api`, so the `onRequest` hook in `autohooks.ts` that requires `request.session.user` never applies, and it sets `config: { rateLimit: false }` so the `RATE_LIMIT_MAX` budget is untouched. Whether the public can reach it is a matter of your network, and the pull request says so.

### Why does each app instance get its own Registry?

prom-client's default registry is global to the process and throws when a metric name is registered twice. `test/helper.ts` builds a new Fastify instance for every test, so a plugin that used the global registry would fail from the second test onward. A `Registry` created inside the plugin is scoped to that instance and closes with it.

### Which Node versions does it test on?

The CI matrix, Node 22 and 24, which the README's prerequisite matches. The agent runs on one of them in the sandbox and the pull request's own workflow run covers the other.

## More Fastify jobs

- [Add a Redis Session Store to a Fastify App from a Linear Issue](https://getrush.ai/run/add-redis-sessions/fastify/)
- [Add Request IDs and Structured Logging to a Fastify App](https://getrush.ai/run/add-request-id-logging/fastify/)
- [Add Soft Delete to a Fastify API from a Linear Issue](https://getrush.ai/run/add-soft-delete/fastify/)

## The same job on other stacks

- [Add Prometheus Metrics to a Fiber App](https://getrush.ai/run/add-prometheus-metrics/fiber/)
- [Add Prometheus Metrics to a Gin API from a Linear Issue](https://getrush.ai/run/add-prometheus-metrics/gin/)
- [Add Prometheus Metrics to a GORM Service from a Linear Issue](https://getrush.ai/run/add-prometheus-metrics/gorm/)

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