# Add Prometheus Metrics to a Leptos App

Yes. An agent adds a request counter and latency histogram to a Leptos app's Axum server behind the ssr feature, serves /metrics, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-prometheus-metrics/leptos/). 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 half of the app first, because a Leptos crate compiles twice. In a project generated from leptos-rs/start-axum, `Cargo.toml` takes `leptos`, `leptos_router` and `leptos_meta` 0.8.0, and makes `axum` 0.8.0, `tokio` and `leptos_axum` optional behind the `ssr` feature while `hydrate` pulls `wasm-bindgen` 0.2.106 and `console_error_panic_hook` for the browser bundle. `src/main.rs` is `#[cfg(feature = "ssr")]`: it reads `get_configuration(None)`, builds `Router::new().leptos_routes(…).fallback(leptos_axum::file_and_error_handler(shell)).with_state(leptos_options)` and runs `axum::serve` on `site-addr`, which `[package.metadata.leptos]` sets to `127.0.0.1:3000`. `src/app.rs` holds the `shell`, the `App` with one `Route` at the root and a `HomePage` counter, and `end2end/tests/example.spec.ts` is a Playwright test that checks the title and the `h1`. There is no `.github` directory, so the checks are `cargo leptos build --release` and `cargo leptos end-to-end`, the commands the README names.

The metrics crates go behind `ssr` so the WebAssembly build never sees them. The agent adds `metrics` and `metrics-exporter-prometheus` as optional dependencies listed in the `ssr` feature, and in `src/main.rs` installs the recorder with `PrometheusBuilder::new().install_recorder()` before the router is built, keeping the returned handle in the router's state next to `LeptosOptions`. A `track_metrics` function registered with `axum::middleware::from_fn` reads the `MatchedPath` extension when Axum matched a route and labels the request `fallback` otherwise, so the `/pkg/…` assets and favicon served by the file handler collapse into one series instead of one per file name. It records `http_requests_total` with `method`, `path` and `status` labels and `http_request_duration_seconds` as a histogram with the same labels, timing the call around `next.run(request)`.

`/metrics` is a plain Axum route returning `handle.render()` as text, added before `leptos_routes` so Leptos does not try to render a page for it. Because the template serves everything from one listener, the agent documents in the README that a deployment should either keep the port private or put the path behind the proxy's allowlist, and leaves a `LEPTOS_METRICS_ADDR` variable commented in the code path for teams that want a second listener. The histogram's buckets are set explicitly in the builder for the `http_request_duration_seconds` name, so the default buckets do not hide sub-millisecond server-rendered pages.

Two tests cover it. `tests/metrics.rs`, compiled only with `ssr`, builds the router through a `build_router` function the agent extracts from `main`, sends `GET /` and then `GET /metrics` with `tower::ServiceExt::oneshot`, and asserts the body contains `http_requests_total` with `path="/"` and `status="200"` and a `_bucket` line for the histogram. `end2end/tests/metrics.spec.ts` uses Playwright's `request` fixture to fetch `http://localhost:3000/metrics` through the running server that `cargo leptos end-to-end` starts, and checks the same counter name, so the metric is proven on the real binary and not only on the router in memory.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add Prometheus metrics to the Axum server of this Leptos app. Read Cargo.toml including [package.metadata.leptos], src/main.rs, src/app.rs, src/lib.rs, rust-toolchain.toml, README.md and end2end/tests/example.spec.ts first. Add metrics and metrics-exporter-prometheus as optional dependencies enabled only by the ssr feature. In src/main.rs install the Prometheus recorder before the router is built, keep the handle in state, and add a from_fn middleware that records http_requests_total and an http_request_duration_seconds histogram with method, path and status labels, using MatchedPath and the label fallback for the file handler. Serve /metrics as a text route registered before leptos_routes, set explicit histogram buckets, and extract a build_router function so it can be tested. Add tests/metrics.rs behind cfg(feature = \"ssr\") using tower oneshot to assert the counter and bucket lines after a request to /, and end2end/tests/metrics.spec.ts that fetches /metrics from the running server. Run cargo leptos build --release and cargo leptos end-to-end, and open a pull request with the output and a sample of the /metrics text.",
  "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 changes `Cargo.toml`, `src/main.rs` and `README.md`, adds `tests/metrics.rs` and `end2end/tests/metrics.spec.ts`, and updates `Cargo.lock`. Its description pastes the release build, the `cargo test --features ssr` run and the Playwright run, plus the first lines of `/metrics` from the sandbox so a reviewer sees the label set before a scrape job is written.

A Prometheus server pointed at the port gets one series per route and status, with the file handler's traffic in a single `fallback` series, and a latency histogram per route that distinguishes a slow server render from a slow asset. The browser bundle is unchanged in size and in what it imports, because nothing new compiles under `hydrate`.

Before merging, a reviewer decides whether `/metrics` stays on the public listener behind the proxy or moves to its own address, checks the bucket boundaries against the app's actual render times, and confirms the `path` label cannot grow without bound, which the `MatchedPath` choice is there to guarantee.

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

A team instrumenting several Rust web services starts one run per repository from the terminal: one `POST /o/{org}/sessions` each with that repository in `resources` and a `request_id` that is a UUID v5 of its full name, so a retried call returns the run already started. Each run reads its own server: a Leptos app on Actix gets the same two metrics through an Actix middleware, a plain Axum API gets the middleware with no feature flag, and one that already has a recorder gets only the route labels and the tests.

Each run opens its own pull request on its own branch, and `GET /o/{org}/sessions` lists them newest first, so the person who started the batch reads every build and test result from one place.

## Why run it on Rush?

The mistakes in a metrics change are quiet: a path label that includes every asset file name, a dependency that leaks into the WebAssembly build and fails only on `cargo leptos build`, or a histogram whose buckets all read `+Inf`. The agent builds both targets and reads the real `/metrics` text in its sandbox, and the assertions it writes check the label set and the buckets on every later pull request.

The run keeps every command and its output, so the reviewer sees the nightly toolchain install, the two builds and the Playwright run without setting up `cargo-leptos`, `wasm32-unknown-unknown` and `sass` locally. Several services can be instrumented at once, each in its own sandbox, and one that already exposes metrics is left with a note instead of a second recorder.

## Frequently asked questions

### Will this change the browser bundle?

No. The two crates are optional and listed only under the `ssr` feature, and the middleware and route live inside the `#[cfg(feature = "ssr")]` main. `cargo leptos build --release` compiles the `hydrate` side as before; the test run in the pull request shows both targets building.

### Why label by matched route and not by URL?

A URL label grows with every distinct path a crawler or a user types, which makes Prometheus slow and the dashboard useless. `MatchedPath` is the route pattern Axum matched, a fixed set, and anything the file-and-error fallback served is labelled `fallback`. Leptos page routes appear by their pattern, so `/users/:id` is one series however many users there are.

### Does /metrics need authentication?

The template serves one listener, so the agent puts the route on it and says so in the README. The usual answer is to let the reverse proxy serve `/metrics` only to the scraper's network, or to move the route to a second listener on a private address; the pull request leaves the second option as a marked spot in the code rather than guessing the deployment.

### What does the end-to-end test add over the unit test?

The unit test exercises the router in memory and proves the middleware order and the label names. The Playwright test fetches `/metrics` from the binary that `cargo leptos end-to-end` starts, which proves the recorder was installed in the real `main` before any request and that the route survived the Leptos route generation.

## More Leptos jobs

- [Add Rate Limiting to a Leptos Server](https://getrush.ai/run/add-rate-limiting/leptos/)
- [Add Request ID Logging to a Leptos App on Axum](https://getrush.ai/run/add-request-id-logging/leptos/)
- [Add Security Headers to a Leptos Axum App](https://getrush.ai/run/add-security-headers/leptos/)

## The same job on other stacks

- [Add Prometheus Metrics to a Litestar App](https://getrush.ai/run/add-prometheus-metrics/litestar/)
- [Add Prometheus Metrics to a Phoenix LiveView App](https://getrush.ai/run/add-prometheus-metrics/phoenix-liveview/)
- [Add Prometheus Metrics to a Quarkus App](https://getrush.ai/run/add-prometheus-metrics/quarkus/)

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