# Add Prometheus Metrics to a Ktor Server

Yes. An agent installs MicrometerMetrics with a Prometheus registry, serves /metrics, splits the module so it is testable without Postgres, and opens a PR.

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

## What the agent does

The agent reads the build and the module before it adds a plugin. In a server shaped like the `postgres` sample of ktorio/ktor-samples, `build.gradle.kts` applies Kotlin 2.4.20, the `io.ktor.plugin` 3.6.0 and the serialization plugin, and depends on `ktor-server-core-jvm`, `ktor-server-content-negotiation-jvm`, `ktor-serialization-kotlinx-json-jvm`, `ktor-server-netty-jvm`, `ktor-server-config-yaml`, logback and the PostgreSQL driver, with `ktor-server-test-host-jvm` and `kotlin-test-junit` for tests, on a JVM 17 toolchain. `src/main/resources/application.yaml` names one module, `com.example.PostgresApplicationKt.module`, on port 8080. `PostgresApplication.kt` calls `configureSerialization()` and then `configureRouting(dbConnection = connectToPostgres(embedded = false))`, and `Routing.kt` opens a JDBC connection from `postgres.yaml` and wires four `/articles` routes over an `ArticleService` that creates the table on construction. There is no test source set, and the module cannot start without the database from `docker-compose.yaml`.

The agent adds `io.ktor:ktor-server-metrics-micrometer-jvm` and `io.micrometer:micrometer-registry-prometheus` to the dependencies, the second with an explicit version since it is not in the Ktor BOM. A new `plugins/Monitoring.kt` holds `configureMonitoring()`: it creates a `PrometheusMeterRegistry(PrometheusConfig.DEFAULT)`, installs `MicrometerMetrics` with that registry plus the JVM memory, GC, processor and uptime binders, and adds a `get("/metrics")` route that responds with `registry.scrape()` as `text/plain`. `module()` calls it before `configureRouting`, so the `/articles` handlers are timed under `ktor.http.server.requests` with `route`, `method` and `status` tags.

To make the plugin testable without PostgreSQL, the agent moves the database-dependent call into a second function, `Application.articlesModule()`, keeps `module()` as the composition of both for `application.yaml`, and writes `src/test/kotlin/MonitoringTest.kt` with `testApplication { application { configureMonitoring() } }`. The test calls `/metrics`, asserts `200`, that the body contains `jvm_memory_used_bytes`, and after one more request that `ktor_http_server_requests_seconds_count` appears with `route="/metrics"`. The `ArticleService` and its routes are not touched, so the sample's behaviour with Docker running is unchanged.

The agent runs `./gradlew build` with the wrapper, which compiles and runs the new test on the toolchain, and `./gradlew run` with the compose database up when Docker is available to scrape a real `/metrics` after a `POST /articles`. `.github/workflows/build-all.yml` builds every sample through `build-all.sh` on JDK 24, so the agent checks that script still finds the `postgres` directory and pastes the Gradle output and a trimmed scrape in the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add Prometheus metrics to the postgres sample in this Ktor repository and open a pull request. Read postgres/build.gradle.kts, postgres/gradle.properties, postgres/src/main/resources/application.yaml, postgres/src/main/kotlin/com/example/PostgresApplication.kt, postgres/src/main/kotlin/com/example/plugins/Routing.kt, postgres/src/main/kotlin/com/example/plugins/Serialization.kt, postgres/docker-compose.yaml and build-all.sh first. Add ktor-server-metrics-micrometer-jvm and micrometer-registry-prometheus with an explicit version. Create plugins/Monitoring.kt with configureMonitoring that installs MicrometerMetrics on a PrometheusMeterRegistry with the JVM binders and serves registry.scrape() at GET /metrics as text/plain. Call it from module before configureRouting. Split the database wiring into an articlesModule function so configureMonitoring can be tested without PostgreSQL. Add src/test/kotlin/MonitoringTest.kt using testApplication that asserts /metrics answers 200 with jvm_memory_used_bytes and, after a second request, the ktor_http_server_requests_seconds_count series for the /metrics route. Run ./gradlew build and paste the output in the pull request. Do not change ArticleService or the /articles routes.",
  "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 under `postgres/`: two dependencies in `build.gradle.kts`, a new `plugins/Monitoring.kt`, a two-function split in `PostgresApplication.kt`, and a new `src/test/kotlin/MonitoringTest.kt`. The description shows the `./gradlew build` output with the test task passing and about twenty lines of `/metrics`, including the request histogram for `/articles` when the compose database was available during the run.

On a repository with the samples' workflow, the pull request runs `build-all.sh` on JDK 24, which builds and tests every sample, so the new test runs there without a database. A reviewer can also run `./gradlew run` with the compose file and scrape `/metrics` locally in under a minute.

Before merging, the reviewer checks that `/metrics` is not exposed on the public port in their deployment, whether they want a separate management port, and whether the `route` tag cardinality is acceptable for their path shapes; `/articles/{id}` is recorded as the template, not the id, so it stays bounded. Then they add the scrape target.

## Run it on every service onboarded to monitoring

A platform team bringing Ktor services onto Prometheus sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own module function and plugins, so a service already using `CallLogging` gets `MicrometerMetrics` installed beside it, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn finishes, with the `session_url` to read the pull request and the scrape sample from.

## Why run it on Rush?

The plugin install is a few lines; the work is making it testable in a module that opens a JDBC connection at startup, which is why samples like this one ship without tests. In a Rush sandbox the agent restructures the module, runs the Gradle build with the repository's wrapper, starts the compose database when it can to scrape real request metrics, and keeps every command and its output in the run's record.

The same request works unchanged on every Ktor service a team owns, and because the run opens a pull request through the Rush GitHub App, the first test file in the project arrives alongside the feature instead of as a separate chore.

## Frequently asked questions

### Why split the module?

`module()` connects to PostgreSQL at startup through `connectToPostgres`, so a `testApplication` that loads it needs a running database. Moving that call into `articlesModule()` lets the test install only `configureMonitoring()`; `application.yaml` still points at `module`, which calls both, so nothing changes at runtime.

### Which version of micrometer-registry-prometheus?

The Ktor plugin brings `micrometer-core` transitively but not the Prometheus registry, so the pull request pins the registry to the same Micrometer line the plugin uses, read from the resolved dependency tree, and notes it in `gradle.properties` beside `logback_version`.

### Does it slow down request handling?

`MicrometerMetrics` records a timer per request and a gauge of active requests; the cost is a few microseconds per call. The JVM binders sample memory and GC on scrape, not per request.

### Can I use a different backend than Prometheus?

Yes. `configureMonitoring` takes the registry as a parameter with the Prometheus one as default, so swapping in a `StatsdMeterRegistry` or an OTLP registry is a one-line change and the `/metrics` route is dropped.

## More Ktor jobs

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

## The same job on other stacks

- [Add Prometheus Metrics to a Leptos App](https://getrush.ai/run/add-prometheus-metrics/leptos/)
- [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/)

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