# Add Health Checks to an aiohttp App

Yes. An agent adds /healthz and /readyz to your aiohttp app, with readiness running SELECT 1 through the app's async SQLAlchemy engine, plus tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/aiohttp/). 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 app is assembled before it adds a route, because in aiohttp a health check has to find the database handle where the app keeps it. In an app like the polls demo in aio-libs/aiohttp-demos, `aiohttpdemo_polls/main.py` builds a `web.Application`, stores the parsed YAML config under `config_key`, sets up Jinja2 templates, appends `pg_context` to `app.cleanup_ctx`, then calls `setup_routes`, `setup_static_routes` and `setup_middlewares`. `db.py` is where the handle lives: `pg_context` creates an async engine from a `postgresql+asyncpg` DSN and stores an `async_sessionmaker` under `db_key`, and the two keys are typed `web.AppKey` values in `typedefs.py`. `routes.py` registers `/`, `/poll/{question_id}`, its `/results` and `/vote`, and a static route. `requirements-dev.txt` pins aiohttp 3.13.5, asyncpg 0.32.0, SQLAlchemy 2.0.54, pytest 9.1.1 and pytest-aiohttp 1.1.1.

Then it decides what each probe answers. `GET /healthz` is liveness: the process is serving, so it returns `web.json_response({"status": "ok"})` and touches nothing. `GET /readyz` is readiness: it takes a session from `app[db_key]`, runs `SELECT 1` through `sqlalchemy.text` inside `asyncio.wait_for` with a two second limit, and answers `200` with `{"status": "ok", "database": "ok"}` or `503` naming the failed check. The agent writes both in a new `aiohttpdemo_polls/health.py` and registers them in `setup_routes` with names, so `app.router["readyz"].url_for()` works in tests the way `router["results"]` already does in `views.py`.

One detail in `middlewares.py` shapes the code. The error middleware catches any `Exception` from a handler, logs it and renders the `500.html` template, so a readiness handler that lets an `OSError` escape would answer an HTML 500 instead of a JSON 503. The handler catches its own exceptions, including `asyncio.TimeoutError`, and builds the 503 itself. The agent also keeps the probes out of the Jinja2 path: no template, no `aiohttp_jinja2.template` decorator, plain JSON that a Kubernetes probe or a load balancer can read.

The tests go in `tests/test_health.py` beside `test_integration.py` and use the fixtures `conftest.py` already defines: `cli` builds the app through `init_app` with `config/polls_test.yaml` and wraps it in `aiohttp_client`, and `db` creates the test database through `init_db.py`. `test_healthz` needs no database. `test_readyz_ok` uses `db` and expects `200`. `test_readyz_database_down` writes a temporary config whose `postgres.port` is a closed port and expects `503` within the timeout; `create_async_engine` does not connect until first use, so building the app still works. `pytest.ini` turns warnings into errors and sets `asyncio_mode = auto`, so the new tests are plain `async def` functions with no decorator. The agent installs PostgreSQL in its sandbox with `apt-get`, sets the `postgres` password `init_db.py` expects, then runs `flake8 demos` and `pytest demos/polls` the way the root `Makefile` and `.github/workflows/ci.yml` do.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add health check routes to this aiohttp app. Read aiohttpdemo_polls/main.py, routes.py, db.py, typedefs.py, middlewares.py, views.py, config/polls.yaml, config/polls_test.yaml, requirements-dev.txt, pytest.ini, tests/conftest.py, tests/test_integration.py, init_db.py and the root Makefile and CI workflow first. Add GET /healthz that returns JSON 200 without touching the database, and GET /readyz that runs SELECT 1 through the async_sessionmaker stored under db_key with a short timeout and returns a JSON 503 naming the failed check when it cannot. Put them in a new health module, register them in setup_routes with route names, catch errors inside the readiness handler so the error middleware does not turn them into the HTML 500 page, and keep both routes out of the templates. Write tests beside test_integration.py using the existing cli and db fixtures, including one where the database is unreachable. Start PostgreSQL in the sandbox the way init_db.py expects it, run flake8 and pytest for the polls demo, then open a pull request that shows the test output and a curl of both 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 that adds `aiohttpdemo_polls/health.py` and `tests/test_health.py`, and changes `routes.py` by two registration lines. The description shows `curl -i` for `/healthz` and `/readyz` against a running `python -m aiohttpdemo_polls`, the three new test names from the `pytest -v` output that `pytest.ini` already asks for, and the timeout value in one place so a reviewer can change it.

The run's record keeps the PostgreSQL install, the `init_db.py` step, the `flake8` run and every `pytest` invocation, including the one where the readiness check was pointed at a closed port and came back `503`, so the behaviour is in the log and not only in the description.

Before merging, a reviewer decides whether readiness should also cover anything beyond PostgreSQL, whether an orchestrator's probes should point at `/readyz` or `/healthz`, and whether the demo's `polls.yaml` host and port need an entry in the deployment's probe config. The agent changes no existing route, template or model.

## Run it on every Python service without probes

A team with several aiohttp services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with the repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of opening a second pull request. Each run reads its own `main.py` and finds where that service keeps its engine, pool or client.

To keep readiness honest after that, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a datastore or an outbound client the service cannot work without, add it to the readiness check in the health module and say so in a comment" reads each new pull request. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

A health route written without running the app is wrong in small ways that only show in production: a readiness check that opens its own connection instead of the app's pool and so reports healthy while the pool is exhausted, an exception that the error middleware turns into an HTML page the probe cannot parse, or a check with no timeout that hangs the probe when PostgreSQL hangs. The agent runs the real app in its own sandbox with a real PostgreSQL, hits both routes, points the check at a closed port and watches the answer change.

Every command stays with the run, from the `apt-get` install to the `pytest` lines, and the pull request cites them. Doing the same for a dozen aiohttp services at once costs no more attention than one, because each run has its own machine, its own record and its own pull request.

## Frequently asked questions

### Why two routes instead of one?

Because an orchestrator treats them differently. A failing liveness probe restarts the process, which does nothing for a database that is down and would restart a healthy server in a loop. A failing readiness probe only takes the instance out of rotation until the dependency is back. `/healthz` checks the process; `/readyz` checks what the process needs.

### Why go through app[db_key] rather than open a connection?

The `async_sessionmaker` stored by `pg_context` is the pool every view uses, so a `SELECT 1` through it proves the thing that matters: the app's own connections work. A separate `asyncpg.connect` could succeed while the pool is wedged. The session is released on the way out of the `async with` block, as in `views.py`.

### What happens when PostgreSQL is down?

`/readyz` answers `503` with `{"status": "error", "database": "unreachable"}` within the timeout, and `/healthz` keeps answering `200`. The handler catches the exception itself, because `middlewares.py` would otherwise render the `500.html` template; a test in the pull request covers exactly this case by pointing the config at a closed port.

### Does this change the error pages or the templates?

No. The probes return `web.json_response` directly and never pass through `aiohttp_jinja2`, and the 404 and 500 overrides in `setup_middlewares` are untouched. The only edit to an existing file is the two `add_get` lines in `setup_routes`.

## More aiohttp jobs

- [Add Input Validation to an aiohttp App](https://getrush.ai/run/add-input-validation/aiohttp/)
- [Add OpenTelemetry Tracing to an aiohttp App](https://getrush.ai/run/add-opentelemetry/aiohttp/)
- [Add Pagination to an aiohttp App](https://getrush.ai/run/add-pagination/aiohttp/)

## The same job on other stacks

- [Add Health Checks to an ASP.NET Core App from a Linear Issue](https://getrush.ai/run/add-health-checks/aspnet-core/)
- [Add Health Checks to an Axum Service](https://getrush.ai/run/add-health-checks/axum/)
- [Add Health Checks to a Blazor Web App](https://getrush.ai/run/add-health-checks/blazor/)

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