# Add Health Checks to an Axum Service

Yes. An agent adds /healthz and /readyz to an Axum service, runs SELECT 1 on the SQLx pool with a timeout for readiness, and proves both with oneshot tests.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/axum/). 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 built before it adds a route. In an Axum service like launchbadge/realworld-axum-sqlx, `Cargo.toml` and `Cargo.lock` pin `axum` 0.3.4, `sqlx` 0.5.9 with `runtime-tokio-native-tls`, `postgres`, `uuid` and `time`, `tokio` 1.14, `tower` 0.4.11, `tower-http` 0.2.0 for `TraceLayer`, and a `clap` 3 beta that parses `Config` from `DATABASE_URL` and `HMAC_KEY`. `src/main.rs` loads `.env`, starts `env_logger`, builds a `PgPoolOptions` pool with `max_connections(50)`, runs `sqlx::migrate!()` so the four files under `migrations/` are applied before the port opens, and calls `http::serve`. `src/http/mod.rs` holds the private `ApiContext { config: Arc<Config>, db: PgPool }`, adds it with `AddExtensionLayer` next to `TraceLayer::new_for_http()`, merges `users::router()`, `profiles::router()` and `articles::router()` in `api_router()`, and binds `0.0.0.0:8080`.

Error handling is the detail that matters for a probe. `src/http/error.rs` defines one `Error` enum, with `Sqlx` and `Anyhow` variants that `IntoResponse` turns into a 500 `an error occurred with the database`, and a `WWW-Authenticate: Token` header on 401. A readiness route must not go through that path, because an orchestrator wants 503 from a service that is up but cannot reach Postgres, not 500. So the agent adds `src/http/health.rs` inside the `http` module, where `ApiContext` is visible, with a `router()` merged into `api_router()`: `GET /healthz` answers 200 with `{"status":"ok"}` and touches nothing, and `GET /readyz` takes `Extension<ApiContext>`, runs `sqlx::query_scalar::<_, i32>("select 1").fetch_one(&ctx.db)` under `tokio::time::timeout`, and answers 503 with `{"status":"unavailable","database":"..."}` on a timeout or error, with `Cache-Control: no-store` on both. Neither route uses the `AuthUser` extractor from `src/http/extractor.rs`, so no token is needed.

Tests are the gap in this repository. `.github/workflows` has one job that starts a `postgres` service, installs `sqlx-cli` and runs `sqlx db setup`, `cargo build`, `cargo test`, and then the Realworld Postman collection from a checked-out fork against `cargo run&` on port 8080; the only Rust test is `test_slugify` in `src/http/articles/mod.rs`, whose comment argues for integration tests over unit tests. `sqlx` 0.5 has no `#[sqlx::test]`, so the agent adds a `#[cfg(test)]` module in `health.rs` that builds a `PgPool` from `DATABASE_URL`, the variable CI already exports, wraps `health::router()` with the same `AddExtensionLayer` as `serve`, and drives it with `tower::ServiceExt::oneshot`: `/healthz` is 200, `/readyz` is 200 against the live database, and `/readyz` is 503 with a pool built by `connect_lazy` against a closed port. `cargo test` runs them in the sandbox the way the workflow does.

Then the agent runs the rest of the workflow: `cargo build --verbose`, `cargo test --verbose`, and the service under `cargo run` to call both routes with `curl` and show the status codes and bodies, plus `cargo fmt --check` even though CI does not, so the diff is clean. It writes the two routes into the README's setup section and opens a pull request that lists them, the timeout, the pool the readiness query borrows from, and the test output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add health checks to this Axum service. Read Cargo.toml, src/main.rs, src/http/mod.rs, src/http/error.rs, src/http/extractor.rs and the CI workflow first. Add a health module inside src/http with a router merged into api_router: GET /healthz answers 200 with a small JSON body and no dependencies, and GET /readyz runs select 1 on the SQLx pool from the ApiContext extension under a short timeout and answers 503 with the reason on failure, not through the Error enum's 500 path. Send Cache-Control: no-store on both and require no authentication. Add a cfg(test) module that builds a pool from DATABASE_URL, wraps the router with the same extension layer serve uses, and uses tower's oneshot to check /healthz is 200, /readyz is 200 against the database, and /readyz is 503 with a lazily connected pool pointed at a closed port. Start Postgres, run sqlx db setup, cargo build, cargo test and cargo fmt --check, then run the service and call both routes with curl. Do not change Cargo.toml beyond what the tests need, the migrations or any workflow. Open a pull request that lists the routes, the timeout and the pool they use, and quotes the test and curl output.",
  "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 on its own branch adding `src/http/health.rs` with its test module, two lines in `src/http/mod.rs` that declare the module and merge its router, and a README note. The body lists `/healthz` and `/readyz`, the timeout the readiness query runs under, that it borrows one connection from the 50-connection pool `main.rs` builds, and quotes the `cargo test` output and the `curl` responses from the running service.

The session read names the repository and the pull request, and the transcript keeps the Postgres start, `sqlx db setup`, the build, the first `cargo test` in which the new tests failed to compile before the module existed, the passing run, the formatter and the two `curl` calls. The `changes` route lists the files with their diff.

Before merging, a reviewer checks that `/readyz` answers 503 and not 500 on a database error, that the timeout is shorter than the probe interval they will configure, that the test against a closed port cannot hang, and that `/readyz` is not reachable from the public internet once deployed, since it reveals whether the database is up.

## Run it on every new Rust service

When a service repository is created, a handler on your server receives GitHub's repository event and sends `POST /o/{org}/sessions` with this prompt and the repository in `resources`. Across services that already exist, a script lists what the Rush GitHub App installation reaches with `GET /o/{org}/github`, looks for a health route in each, and starts one run per repository without one, with its own `request_id`.

With a `webhook_url` on the key, each turn's end arrives as `run.completed`, `run.failed` or `run.cancelled`, signed per Standard Webhooks, and `data.session_url` reads back the pull request. A key may have at most `max_concurrent` runs in progress, 4 by default; starting one more answers `202` with `status: "queued"`, so the script can start every service's run at once and Rush begins each queued one when a slot frees.

## Why run it on Rush?

A readiness route in this codebase has to dodge the shared `Error` type, borrow the pool through a private context, and come with the first integration tests the repository has, against a real Postgres with `sqlx db setup` run first. The agent does that in its own sandbox with the Postgres the workflow uses and keeps the compile, test and curl output, rather than someone proving it on a laptop with a different database.

The pull request carries its evidence, including the failing test before the module existed. Several services get the same two routes at once, each in its own sandbox and pull request, and a follow-up about the timeout wakes the same sandbox with `target/` already built.

## Frequently asked questions

### Does readiness take a connection from the pool?

Yes, one of the 50 `main.rs` allows, for the length of a `select 1`. Under a timeout that is a few milliseconds every probe interval; if the pool is exhausted the query waits and then times out, and `/readyz` answers 503, which is the honest answer in that state.

### The service runs migrations at startup. Does readiness cover that?

It does not need to. `sqlx::migrate!().run(&db)` finishes before `http::serve` binds the port, so a process that answers `/healthz` at all has already migrated. `/readyz` only has to say whether Postgres is still reachable afterwards.

### Why tests inside the crate rather than a tests directory?

Because `ApiContext` and `api_router` are private to `src/http`, and the pull request keeps them that way. A `#[cfg(test)]` module in `health.rs` reaches both, and `cargo test` runs it with the `DATABASE_URL` the workflow already sets.

### axum 0.3 is old. Will the agent upgrade it on the way?

No. The prompt forbids changing `Cargo.toml` beyond what the tests need, so the routes use the `axum::Server` and `AddExtensionLayer` APIs the lockfile pins. Upgrading the framework is a separate job with its own pull request.

## More Axum jobs

- [Add Input Validation to an Axum API](https://getrush.ai/run/add-input-validation/axum/)
- [Add OpenAPI Docs to an Axum API from a Linear Issue](https://getrush.ai/run/add-openapi-docs/axum/)
- [Add Prometheus Metrics to an Axum API](https://getrush.ai/run/add-prometheus-metrics/axum/)

## The same job on other stacks

- [Add Health Checks to a Blazor Web App](https://getrush.ai/run/add-health-checks/blazor/)
- [Add Health Checks to a chi API](https://getrush.ai/run/add-health-checks/chi/)
- [Add a Health Check Endpoint to a Cloudflare Worker](https://getrush.ai/run/add-health-checks/cloudflare-workers/)

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