# Add Prometheus Metrics to a Rocket App

Yes. An agent adds a request-counting fairing, a latency histogram and a token-guarded /metrics route to a Rocket 0.5 app, runs its feature matrix and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-prometheus-metrics/rocket/). 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 server is assembled before it adds anything. In a Rocket application like dani-garcia/vaultwarden, `Cargo.toml` names `rocket` 0.5.1 with `default-features = false` and only `json` and `tls`, `rocket_ws`, `tokio`, `diesel` with `r2d2`, `governor` for rate limiting and `log` with `fern`, on edition 2024 with `rust-version` 1.97.1, while `rust-toolchain.toml` pins channel 1.99.0. The database is a feature choice: `sqlite`, `mysql` and `postgresql` each switch on a Diesel backend, and `enable_mimalloc` and `s3` are extra. `src/main.rs` builds the instance in `launch_rocket`: a `rocket::Config` with Rocket's own signal handlers turned off, `Limits` for JSON and file uploads, mounts for `web_routes` at `/`, `core_routes` at `/api`, `admin_routes` at `/admin`, events at `/events`, `identity_routes` at `/identity`, `icons_routes` at `/icons` and `notifications_routes` at `/notifications`, `.manage(pool)` for the database, and three fairings from `src/util.rs`: `AppHeaders`, `Cors` and `BetterLogging`.

`BetterLogging` is the template for what the metrics fairing has to do. It declares `Kind::Liftoff | Kind::Request | Kind::Response`, skips `OPTIONS` requests unless extra debugging is on, and in `on_response` logs `request.route()`, the matched route with its path pattern, next to the status, while `on_request` logs the raw path. The constant `LOGGED_ROUTES` lists the seven prefixes worth logging and leaves static files and `/alive` out. The agent copies that shape: a `Metrics` fairing with `Kind::Request | Kind::Response` that stores an `Instant` in the request's local cache on the way in and, on the way out, increments a counter labelled by method, the matched route's URI pattern and the status class, and observes the elapsed time in a histogram with the same labels. Labelling by the route pattern rather than the request path matters here, because vault paths carry cipher and user UUIDs that would make one series per object. A request with no matched route is counted under a fixed `unmatched` label so 404 noise stays one series.

The second half is the pool and the route. `src/db/mod.rs` defines `DbPool` as an `r2d2` pool behind an `Option` plus a `Semaphore` that caps concurrent connections, so the fairing reads the pool state on each scrape for open and idle connection gauges and the semaphore's available permits. The `/metrics` route goes into `src/api/web.rs` beside `alive` and `alive_head`, which already exist for health checks, and it is guarded the way the admin page is: `src/config.rs` declares every setting through the `make_config!` macro with a label, a description, a type and a default, such as `admin_token: Pass, true, option;`, and `src/api/admin.rs` compares tokens with `crate::crypto::ct_eq`. The agent adds `metrics_token: Pass, false, option;` with a doc line, so `METRICS_TOKEN` in the environment switches the route on, a missing token keeps it returning 404, and a bearer token that does not match in constant time gets 401. Because `.env.template` documents every setting with commented lines, the agent adds `METRICS_TOKEN` next to `ADMIN_TOKEN` there too.

Then it runs what `.github/workflows/build.yml` runs. That workflow installs `libmariadb-dev-compat`, `libpq-dev` and `libssl-dev`, sets `RUSTFLAGS=-Dwarnings`, and tests with `cargo test --profile ci --features sqlite,mysql,postgresql,enable_mimalloc,s3` before testing each database feature alone, then runs `cargo clippy` on the full feature set and `cargo fmt --all -- --check` on the pinned toolchain; a second matrix row repeats the tests on the MSRV. The agent runs those commands in the sandbox with the same packages installed, adds unit tests for the fairing using `rocket::local::blocking::Client` on a minimal instance so no database is needed, starts the binary against SQLite, makes a few requests and curls `/metrics` with and without the token to paste both responses into the pull request. The `typos` and `zizmor` workflows run on the pull request as well, so the doc comment is spelled plainly and no workflow file changes.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Rocket application. Read Cargo.toml, rust-toolchain.toml, src/main.rs, src/util.rs, src/api/mod.rs, src/api/web.rs, src/db/mod.rs, src/config.rs, src/api/admin.rs, .env.template and .github/workflows/build.yml first. Add the prometheus crate and implement a Metrics fairing in a new module, modelled on the BetterLogging fairing: record a request counter and a duration histogram labelled by method, the matched route's URI pattern (never the raw path) and the status class, with a fixed label for requests that matched no route, and gauges for the database pool's open and idle connections and the semaphore's free permits. Attach it in launch_rocket after the existing fairings. Add a GET /metrics route beside alive in src/api/web.rs guarded by a new metrics_token setting declared through make_config! like admin_token, compared in constant time with crate::crypto::ct_eq: 404 when the setting is unset, 401 on a wrong bearer token. Document METRICS_TOKEN in .env.template next to ADMIN_TOKEN. Write unit tests for the fairing with rocket::local::blocking::Client on a minimal rocket instance. Install the system packages build.yml installs, then run cargo test --profile ci --features sqlite,mysql,postgresql,enable_mimalloc,s3, cargo test --profile ci --features sqlite, cargo clippy --profile ci --features sqlite,mysql,postgresql,enable_mimalloc,s3 with RUSTFLAGS=-Dwarnings, and cargo fmt --all -- --check. Start the binary against SQLite with METRICS_TOKEN set, make requests to a few routes, and fetch /metrics with and without the token. Do not change any workflow, Dockerfile or migration. Open a pull request that quotes the commands you ran with their output and pastes a trimmed /metrics response showing the route-pattern labels.",
  "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 with a new metrics module, one dependency line in `Cargo.toml` and the matching `Cargo.lock` entries, an `.attach()` line in `launch_rocket`, a `metrics` route beside `alive` in `src/api/web.rs`, a `metrics_token` entry in `src/config.rs` and a commented `METRICS_TOKEN` block in `.env.template`. The body quotes the `cargo test`, `cargo clippy` and `cargo fmt` commands with their output and pastes a trimmed `/metrics` response in which the series are labelled by route patterns such as the ciphers and sync routes, not by paths containing identifiers.

The repository's `build.yml` runs on the pull request because `src/**` and `Cargo.*` are in its path filter, on both the pinned toolchain and the MSRV, with warnings as errors; the Docker, typos and workflow-security checks run beside it. A failing clippy lint or a format difference would appear there with the file and line.

A reviewer checks the label set first, since cardinality is the mistake that hurts in production, then the token comparison and the 404-when-unset behaviour against how `ADMIN_TOKEN` is handled, and finally that the fairing adds no work on the request path beyond a clock read and a hash-map increment.

## Run it on every Rocket service without metrics

A team with several Rocket services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`, using a `request_id` per repository so a retry returns the run it already started. Each run reads its own `main.rs`, so a service that already has a logging fairing gets the metrics fairing attached beside it and a service with several mounts gets one `/metrics` at the root, and each opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `data.session_url` to read the pull request and the pasted `/metrics` sample from. A follow-up on `POST /o/{org}/sessions/{id}/messages`, once the turn has finished, wakes the same sandbox to add a gauge or rename a label.

## Why run it on Rush?

Metrics code is easy to write and hard to trust: a label on the raw path explodes cardinality, a fairing in the wrong position misses the responses it should count, and a `/metrics` route that is open to the internet leaks route names and traffic shape. In a Rush sandbox the agent compiles the full feature matrix with the headers the workflow installs, runs the tests and the lints exactly as CI does, starts the server and reads the exposition text it produced, and all of that stays in the transcript next to the diff.

A password manager's server is not where you want a first draft of an endpoint merged on faith. The pull request carries the commands, their output and the sample scrape, so the review is about label design and the token rule, not about whether it builds.

## Frequently asked questions

### Why label by the route pattern and not the request path?

Because the API paths carry cipher, folder and user identifiers, and a label per path would create a series per object. Rocket exposes the matched route on the request in `on_response`, which `BetterLogging` already logs, so the fairing uses the route's URI pattern and keeps the series count equal to the number of routes times a handful of status classes.

### Why guard /metrics with a token instead of a separate port?

Rocket runs one listener per instance, and the application already has the pattern: `ADMIN_TOKEN` is declared through `make_config!` and compared with `ct_eq`. A `METRICS_TOKEN` follows the same rule, is documented in the same `.env.template`, and leaves the route returning 404 when unset, so an instance that never configures it exposes nothing new.

### Does it need a database to run the tests?

The fairing tests use `rocket::local::blocking::Client` on a minimal instance and need no database. The full `cargo test` on the feature matrix needs the MariaDB and PostgreSQL client headers that `build.yml` installs, which the agent installs in the sandbox before running the same commands.

### Will the fairing slow requests down?

It reads a clock on the way in and increments one counter and one histogram on the way out, with labels drawn from values Rocket already has. The agent attaches it after `BetterLogging`, so it measures the same requests that are logged, and `OPTIONS` preflights are skipped the same way.

## More Rocket jobs

- [Add Rate Limiting to a Rocket API](https://getrush.ai/run/add-rate-limiting/rocket/)
- [Add Request ID Logging to a Rocket App](https://getrush.ai/run/add-request-id-logging/rocket/)
- [Add Structured Logging to a Rocket API](https://getrush.ai/run/add-structured-logging/rocket/)

## The same job on other stacks

- [Add Prometheus Metrics to an Express and Sequelize API](https://getrush.ai/run/add-prometheus-metrics/sequelize/)
- [Add Prometheus Metrics to a Slim 4 App](https://getrush.ai/run/add-prometheus-metrics/slim/)
- [Add Prometheus Metrics to a Socket.IO Server](https://getrush.ai/run/add-prometheus-metrics/socket-io/)

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