# Add Health Check Endpoints to a Ktor Server

Yes. An agent adds liveness and readiness routes to your Ktor server, the readiness one validating the JDBC connection with a timeout, with tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/ktor/). 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 opens its database before it adds a route that reports on it. In the `postgres` sample of ktorio/ktor-samples, `build.gradle.kts` applies Kotlin `2.4.20`, the Ktor plugin `3.6.0` and `jvmToolchain(17)`, depends on `ktor-server-core-jvm`, `ktor-server-content-negotiation-jvm`, `ktor-serialization-kotlinx-json-jvm`, `ktor-server-netty-jvm`, `ktor-server-config-yaml` and `org.postgresql:postgresql` 42.7.8, and declares `ktor-server-test-host-jvm` and `kotlin-test-junit` as test dependencies although there is no `src/test` directory yet. `src/main/resources/application.yaml` names the module `com.example.PostgresApplicationKt.module` on port 8080. `PostgresApplication.kt` calls `configureSerialization()` and then `configureRouting(dbConnection = connectToPostgres(embedded = false))`.

`src/main/kotlin/com/example/plugins/Routing.kt` holds both halves. `connectToPostgres` loads the driver and builds one `java.sql.Connection` from `postgres.yaml`, the same file `docker-compose.yaml` extends for the `db` service, reading `POSTGRES_DB`, `POSTGRES_USER` and `POSTGRES_PASSWORD` from it. `configureRouting` wraps that connection in an `ArticleService`, whose `init` runs `CREATE TABLE IF NOT EXISTS ARTICLES`, and registers `POST /articles`, `GET`, `PUT` and `DELETE /articles/{id}`. There is no health route, and because the service holds a single connection rather than a pool, a dropped connection stays dropped until the process restarts, which is exactly what a readiness probe should notice.

The agent adds a `configureHealth(dbConnection: Connection)` function in a new `plugins/Health.kt`, called from the module after routing. `GET /healthz` answers `200` with `{"status": "ok"}` and touches nothing. `GET /readyz` calls `connection.isValid(2)` inside `withContext(Dispatchers.IO)`, the same dispatcher `ArticleService` uses for its statements, and answers `200` with `{"status": "ok", "database": "ok"}` or `503` with `"database": "unavailable"`, logging the `SQLException` through `application.log` rather than returning it. Both responses are `@Serializable` data classes so the installed `ContentNegotiation` with `json()` renders them.

Tests are the first in this sample, so they follow the sibling `mongodb` sample's `ApplicationTest.kt`: `testApplication`, `application { ... }` to install the plugins, and the test client. `src/test/kotlin/com/example/HealthTest.kt` calls `configureSerialization()` and `configureHealth` with a `Connection` mocked to return `true` or `false` from `isValid`, and asserts the status and body of each route. The agent runs `./gradlew test` and `./gradlew build` in the sample directory, as `build-all.sh` at the repository root does for every sample, and adds the two routes to the sample's `README.md`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add health check endpoints to the Ktor server in the postgres sample of this 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/service/ArticleService.kt, postgres/postgres.yaml, postgres/docker-compose.yaml, mongodb/src/test/kotlin/com/example/ApplicationTest.kt and build-all.sh first. Add postgres/src/main/kotlin/com/example/plugins/Health.kt with configureHealth(dbConnection: Connection): GET /healthz returns 200 and {\"status\":\"ok\"} without touching anything; GET /readyz calls connection.isValid(2) on Dispatchers.IO and returns 200 with {\"status\":\"ok\",\"database\":\"ok\"} or 503 with \"database\":\"unavailable\", logging the exception, not returning it. Use @Serializable response classes with the existing ContentNegotiation. Call configureHealth from the module after configureRouting. Add postgres/src/test/kotlin/com/example/HealthTest.kt in the style of the mongodb sample's test using testApplication, with a Connection whose isValid returns true in one test and false in another, asserting status and body for both routes. Run ./gradlew test and ./gradlew build inside postgres/, paste the output in the pull request description, and document both routes in postgres/README.md. Do not change the article routes or ArticleService.",
  "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 `postgres/src/main/kotlin/com/example/plugins/Health.kt`, a one-line call in `PostgresApplication.kt`, the first test file in `postgres/src/test/kotlin/com/example/`, and two lines in `postgres/README.md`. The description shows a `curl` of each route against the sample running with the compose database, and the `./gradlew test` and `./gradlew build` output from the branch.

If the repository runs `build-all.sh` in CI, the sample builds and tests as before with the new test included; if it does not, the pasted Gradle output is the evidence. The agent pushes one commit for the routes and one for the test and README.

A reviewer checks that `/readyz` is registered outside any authentication the sample may gain later, that the two-second validity timeout fits their probe interval, that the `503` body names nothing about the host or credentials in `postgres.yaml`, and that `ArticleService` is unchanged. Then they point a liveness probe at `/healthz` and a readiness probe at `/readyz`.

## Run it on every new Ktor service

A platform team that wants every JVM service to answer the same two routes starts one run per repository with `POST /o/{org}/sessions`, this prompt and the repository in `resources`. The agent reads each service's own database setup, so a service on a connection pool validates a pooled connection and one on Exposed runs a trivial query through it, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run with a `session_url`, so a small handler can post the pull request links to the team channel as they land.

## Why run it on Rush?

The routes are short; the work is in validating the connection correctly for a server that holds a single `java.sql.Connection`, and in writing the sample's first tests in a form the maintainers already use elsewhere in the repository. In a Rush sandbox the agent runs Gradle, starts the compose database, curls both routes and reads the `503` after closing the connection, and all of that output is kept in the transcript.

The result passes `./gradlew build` for the sample before a reviewer opens it and documents the routes where the next engineer will look. The same request works unchanged across every Ktor service the team owns.

## Frequently asked questions

### Why isValid rather than a SELECT 1?

`Connection.isValid(timeout)` is the JDBC way to ask the driver whether the connection still works, with a bound in seconds, and it needs no table. A `SELECT 1` would also work; `isValid` keeps the readiness check independent of the `ARTICLES` table that `ArticleService.init` creates.

### Does the sample have tests to follow?

Not yet. `build.gradle.kts` declares `ktor-server-test-host-jvm` and `kotlin-test-junit` but there is no `src/test`. The agent follows the `mongodb` sample's `ApplicationTest.kt` in the same repository, which uses `testApplication` and installs the plugins inside `application { }`.

### Why two routes instead of one?

Liveness says the process should not be restarted; readiness says it can serve. With one `Connection` and no pool, a database outage should take the instance out of rotation, which is `/readyz`, but restarting it would not help, which is why `/healthz` touches nothing.

### What about the embedded H2 branch in connectToPostgres?

Unchanged. `configureHealth` takes whatever `Connection` the module passes, so the `embedded = true` branch gets the same two routes against its own connection.

## More Ktor jobs

- [Add Input Validation to a Ktor API](https://getrush.ai/run/add-input-validation/ktor/)
- [Add JWT Authentication to a Ktor API](https://getrush.ai/run/add-jwt-auth/ktor/)
- [Add OpenAPI Docs to a Ktor Server](https://getrush.ai/run/add-openapi-docs/ktor/)

## The same job on other stacks

- [Add Liveness and Readiness Probes to Kustomize Manifests](https://getrush.ai/run/add-health-checks/kustomize/)
- [Add Health Checks to a Leptos App](https://getrush.ai/run/add-health-checks/leptos/)
- [Add a Health Check Endpoint to a Litestar App](https://getrush.ai/run/add-health-checks/litestar/)

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