# Add Prometheus Metrics to an Axum API

Yes. An agent adds a request counter and latency histogram to your Axum API with the metrics crates, serves /metrics, checks it with curl, and opens a PR.

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

## What the agent does

The agent reads the server setup before it picks a crate, because the right approach depends on the Axum version. In an API shaped like launchbadge/realworld-axum-sqlx, `Cargo.toml` pins `axum 0.3.4` with the `tower-log` feature, `tower 0.4.11`, `tower-http 0.2.0` with `trace`, `sqlx 0.5` on Postgres, `env_logger` and `log`. `src/http/mod.rs` builds the app in `serve()`: `api_router()` merges `users::router()`, `profiles::router()` and `articles::router()`, then a `ServiceBuilder` adds `AddExtensionLayer` with the `ApiContext` and `TraceLayer::new_for_http()`, and `axum::Server::bind` listens on `0.0.0.0:8080`. `src/config.rs` reads `DATABASE_URL` and `HMAC_KEY` through `clap` from the environment.

Axum 0.3 predates `axum::middleware::from_fn`, so the agent does not reach for a crate written against a newer Axum. It adds `metrics` and `metrics-exporter-prometheus` to `Cargo.toml`, installs the recorder once in `serve()` with `PrometheusBuilder::new().install_recorder()`, and writes a small Tower middleware in `src/http/metrics.rs` that wraps the router: on each response it increments `http_requests_total` labelled by method, the matched route pattern and status, and records the elapsed time in `http_request_duration_seconds`. The route label uses the pattern, `/api/articles/:slug`, not the concrete path, so the series count stays bounded.

The metrics route goes in `src/http/mod.rs` as `GET /metrics`, outside the `/api` prefix and outside the `AuthUser` extractor, returning `handle.render()` as `text/plain`. The agent threads the `PrometheusHandle` through the same `ApiContext` extension the handlers already use rather than a global. Because `TraceLayer` is already there, the middleware is layered inside it so the trace span still covers the whole request.

The repository has no unit tests of its own; `.github/workflows/rust.yml` runs `cargo build --verbose`, `cargo test --verbose` against a Postgres service after `sqlx db setup`, then starts the server and runs the Realworld Postman collection with `./run-api-tests.sh`. The agent adds a test in `src/http/metrics.rs` that builds the router with the middleware, sends two requests through `tower::ServiceExt::oneshot`, and asserts that the rendered output contains `http_requests_total` with the expected labels. It then runs `cargo fmt --check`, `cargo clippy`, `cargo build` and `cargo test` in the sandbox, starts the server with a local Postgres and `curl`s `/metrics` after a few API calls, and pastes the scrape output in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to this Axum API and open a pull request. Read Cargo.toml, src/main.rs, src/http/mod.rs, src/http/users.rs, src/http/extractor.rs, src/config.rs, .env.sample and .github/workflows/rust.yml first, and note the Axum version before choosing crates. Add the metrics and metrics-exporter-prometheus crates. Install the Prometheus recorder once in serve() and keep its handle in ApiContext. Add src/http/metrics.rs with a Tower middleware that records http_requests_total labelled by method, matched route pattern and status, and http_request_duration_seconds as a histogram, and layer it inside the existing TraceLayer. Serve GET /metrics outside the /api prefix and outside authentication, returning the rendered text. Add a test in src/http/metrics.rs that sends two requests through the middleware with tower::ServiceExt::oneshot and asserts the rendered output contains http_requests_total with the expected labels. Run cargo fmt --check, cargo clippy, cargo build and cargo test, start the server against a local Postgres, make a few API calls, curl /metrics and paste the scrape in the pull request. Do not change any existing route, the JWT extractor or the migrations.",
  "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 two new dependencies in `Cargo.toml` and `Cargo.lock`, `src/http/metrics.rs` with the middleware and its test, a `metrics` field on `ApiContext`, and a `/metrics` route in `src/http/mod.rs`. The description shows the first lines of a real scrape from the sandbox, `http_requests_total{method="POST",route="/api/users",status="200"}` and the histogram buckets, plus the output of `cargo clippy` and `cargo test`.

The repository's workflow builds the branch, runs `cargo test` and the Realworld Postman collection on the pull request, so a label mismatch or a middleware that breaks a response shows up there. The new route is not in the collection, so the agent's `curl` output is the evidence for it.

A reviewer checks that the route label is the pattern and not the raw path, that `/metrics` is not behind the `Authorization: Token` extractor and is not under `/api`, that the recorder is installed exactly once, and that the histogram buckets suit their latency range. Then they point their Prometheus scrape config at port 8080.

## Run it on every service added to the Prometheus scrape list

A platform team adding services to a scrape config sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `Cargo.toml` and picks the middleware shape its Axum version supports, so an API on a newer Axum gets `middleware::from_fn` instead of the hand-written Tower service, and each opens its own pull request.

With a `webhook_url` on the API key, Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so the scrape config change and the application change can be reviewed together.

## Why run it on Rush?

Metrics middleware in Rust is mostly version archaeology: the crate that works on one Axum release fails to compile on the one you have. In a Rush sandbox the agent reads the pinned `axum 0.3.4` first, compiles against it, and keeps every `cargo` command and the compiler's answer in the run's record, so a reviewer sees that the chosen crates actually built rather than guessing from a README.

The proof is a scrape. The agent starts the server with a real Postgres, exercises `POST /api/users` and `GET /api/articles`, and pastes the `/metrics` text in the pull request, so the series names and labels a dashboard will use are visible before merge. The same request works unchanged on every Axum service a team runs.

## Frequently asked questions

### Why not the axum-prometheus crate?

Because this repository pins Axum 0.3.4, and that crate targets Axum 0.6 and later. The `metrics` and `metrics-exporter-prometheus` crates do not depend on the web framework at all, so a small Tower middleware is the version-safe route; on a newer Axum the agent would use `axum::middleware::from_fn` or the crate directly.

### Will the route label explode the series count?

No. The middleware labels with the matched route pattern, so `/api/articles/how-to-train-your-dragon` and `/api/articles/another-slug` both count under `/api/articles/:slug`. A request that matched no route is labelled `unmatched`.

### Is /metrics authenticated?

It is served outside the `/api` prefix and does not use the `AuthUser` extractor, because Prometheus scrapes without a token. If the service is reachable from the internet, restrict the path at the load balancer or bind the scrape to an internal port; the pull request notes this.

### Does it slow requests down?

The middleware records one counter increment and one histogram observation per response, in process, with no I/O. The `TraceLayer` already wraps every request, and the metrics layer sits inside it.

## More Axum jobs

- [Add Rate Limiting to an Axum API](https://getrush.ai/run/add-rate-limiting/axum/)
- [Add Refresh Tokens to an Axum JWT API](https://getrush.ai/run/add-refresh-tokens/axum/)
- [Add Request Timeouts to an Axum API](https://getrush.ai/run/add-request-timeouts/axum/)

## The same job on other stacks

- [Add Prometheus Metrics to Broadway SQS Pipelines With PromEx](https://getrush.ai/run/add-prometheus-metrics/broadway/)
- [Add Prometheus Metrics to a Celery App](https://getrush.ai/run/add-prometheus-metrics/celery/)
- [Add Prometheus Metrics to a chi API](https://getrush.ai/run/add-prometheus-metrics/chi/)

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