# Add Health Checks to a Fastify App

Yes. An agent adds /health/live and /health/ready to a Fastify app, reuses the under-pressure database check, keeps probes out of auth and rate limits, tested.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/fastify/). 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 composed before it adds a route, because in Fastify the composition is the design. In an app like fastify/demo, `package.json` pins `fastify ^5.10.0` as an ES module built with TypeScript `~6.0.3` on `fastify-tsconfig`, and `src/app.ts` loads three directories with `@fastify/autoload`: `plugins/external` first, then `plugins/app`, then `routes` with `autoHooks` and `cascadeHooks` on. The external plugins already registered are `env`, `cors`, `helmet`, `knex` (a `mysql2` pool of 2 to 10 connections), `multipart`, `rate-limit`, `sensible`, `session` with `cookie`, `static`, `swagger` at `/api/docs` with `hideUntagged: true`, and `under-pressure`. `src/server.ts` sets the timeouts (`connectionTimeout` 120 000 ms, `requestTimeout` 60 000, `keepAliveTimeout` 10 000, `headersTimeout` 15 000), the Ajv options, a `close-with-grace` handler with `FASTIFY_CLOSE_GRACE_DELAY`, and listens on `PORT` or 3000.

Two existing pieces decide the shape of the new routes. `src/plugins/external/under-pressure.ts` already configures `@fastify/under-pressure` with `maxEventLoopDelay` 1000, `maxHeapUsedBytes` 100 000 000, `maxRssBytes` 1 000 000 000, `maxEventLoopUtilization` 0.98, a `retryAfter` of 50 and a `healthCheck` that runs `fastify.knex.raw('SELECT 1')` every 5000 ms, declared with `dependencies: ['knex']`, but it sets no `exposeStatusRoute`, so nothing answers a probe today. And `src/routes/api/autohooks.ts` adds an `onRequest` hook that refuses any request under `/api` without a session user except `/api/auth/login`, while `src/app.ts` rate-limits the not-found handler to 3 requests per 500 ms and `rate-limit.ts` applies `RATE_LIMIT_MAX` per minute to every route, `4` in `.env.example` for the tests. A probe has to live outside `/api`, carry no cookie, and opt out of the limiter.

So the agent adds `src/routes/health/index.ts`, which autoload mounts at `/health` outside the API hook. `GET /health/live` answers `{ status: 'ok' }` with a TypeBox response schema through `@fastify/type-provider-typebox`, as `src/routes/home.ts` does, with `config: { rateLimit: false }` so a probe every few seconds never spends the `RATE_LIMIT_MAX` budget, and a `Health` tag so Swagger lists it. For readiness it turns on under-pressure's `exposeStatusRoute` at `/health/ready` with the same `rateLimit: false` route option, because that route already answers `503` when the event loop, heap or RSS limits trip or when the `SELECT 1` check throws, and reuses the `healthCheckInterval` the plugin has instead of adding a second query path. A `Cache-Control: no-store` header goes on both.

Tests follow `test/helper.ts`, whose `build(t)` registers `serviceApp` through `fastify-plugin` with `skipOverride`, closes the app after the test and offers `app.inject`. `test/app/rate-limit.test.ts` is the template for the first assertion: it sends four requests to `/` and expects the fifth to be 429 with `RATE_LIMIT_MAX=4`, so a health test sends more than four to `/health/live` and expects every one to be 200. A second test stubs `fastify.knex.raw` with `t.mock.method` to reject and expects `/health/ready` to answer 503. `npm test` runs `npm run db:seed && c8 npm run test:run`, where `test:run` is `glob -c "tsx --test" "./test/**/*.ts"`, and the seed needs `CAN_SEED_DATABASE=1` and a MySQL from `docker compose up -d` after `npm run db:create` and `npm run db:migrate` (postgrator migrations `001` to `005` under `migrations/`). The agent runs those in its sandbox the way `.github/workflows/ci.yml` does on Node 22 and 24 with a `mysql:8.4` service, plus `npm run build -- --noEmit` and `npm run lint` (neostandard with TypeScript and no trailing commas).

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add health checks to this Fastify app. Read src/app.ts, src/server.ts, every file under src/plugins/external, src/routes/api/autohooks.ts, src/routes/home.ts and test/helper.ts first. Add a routes/health directory with GET /health/live, answering 200 with a TypeBox response schema, no dependencies, rate limiting switched off for the route and no session required. For GET /health/ready, expose under-pressure's status route at that path with rate limiting switched off, so it answers 503 when its existing knex SELECT 1 check or its event loop, heap or RSS limits fail; do not add a second database check. Send Cache-Control: no-store on both and tag them so Swagger lists them. Add node:test tests in the style of test/app/rate-limit.test.ts: more requests to /health/live than RATE_LIMIT_MAX all answer 200, /health/ready answers 200 with the database up and 503 with knex.raw mocked to reject. Start MySQL from docker-compose.yml, run npm run db:create, npm run db:migrate, then npm test with CAN_SEED_DATABASE=1 and RATE_LIMIT_MAX=4 as the CI workflow does, plus npm run build -- --noEmit and npm run lint. Do not change the under-pressure thresholds, .env.example or any workflow. Open a pull request that lists the routes and what each reports and quotes the test and lint 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/routes/health/index.ts`, a few lines in `src/plugins/external/under-pressure.ts` that expose the status route with its route options, and `test/routes/health/health.test.ts`. The body lists the two routes, which conditions make `ready` answer 503 (the knex check and each under-pressure threshold), and quotes the `npm test` summary with its c8 coverage table, the type check and the lint result.

The session read names the repository and the pull request, and the transcript keeps the MySQL start, the migrations, the seed, the first test run in which the health tests failed before the routes existed, the passing run and the lint. The `changes` route on the session lists the files with their diff.

Before merging, a reviewer checks that both routes carry `rateLimit: false`, that they sit outside `src/routes/api` so the session hook does not apply, that the `ready` route did not get a second `SELECT 1` beside under-pressure's, and that the thresholds that now make `ready` fail match what their orchestrator should treat as not ready rather than as a reason to restart.

## Run it on every new Fastify 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`. For the services you already run, 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, each with its own `request_id` so a retry returns the run it already started.

With a `webhook_url` on the key, the end of each turn 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 holds nothing back and the queued run begins as soon as one of the key's runs ends or parks.

## Why run it on Rush?

In this app a health route done wrong is worse than none: inside `/api` it answers 401, under the default limiter it answers 429 after four probes a minute, and a second database check beside under-pressure's doubles the load for no information. The agent reads the plugin order, the hooks and the limiter in its own sandbox and places the routes where they work, with a MySQL started from the repository's own compose file to prove it.

The pull request carries the proof: the seeded test run with coverage, the type check and the lint, plus the failing run before the routes existed. Several services get the same pair at once, each in its own sandbox and pull request, and a follow-up about a threshold wakes the same sandbox with `node_modules` and the database still there.

## Frequently asked questions

### Why reuse under-pressure for readiness instead of a plain route?

Because `under-pressure.ts` already runs `SELECT 1` on the knex pool every 5 seconds and tracks event loop delay, heap and RSS, and its status route answers 503 from that state. A hand-written route would query the database again on every probe and know nothing about the event loop.

### Do probes get rate limited or need the session cookie?

Neither. Both routes set `config: { rateLimit: false }`, and they live under `src/routes/health`, outside `src/routes/api`, so the `onRequest` hook in `autohooks.ts` that requires `request.session.user` never sees them.

### What makes ready answer 503 besides the database?

The thresholds already in `under-pressure.ts`: an event loop delay over 1000 ms, heap over 100 MB, RSS over 1 GB or event loop utilisation over 0.98. The prompt leaves those numbers alone; change them in that file if your service runs hotter than the demo.

### Which Node version does it test on?

The CI matrix, Node 22 and 24, which the README's prerequisite of Node 22 or higher matches. The agent runs on one of them in the sandbox and the pull request's own workflow run covers the other.

## More Fastify jobs

- [Serve OpenAPI Docs from a Fastify API from a Linear Issue](https://getrush.ai/run/add-openapi-docs/fastify/)
- [Add OpenTelemetry Tracing to a Fastify API](https://getrush.ai/run/add-opentelemetry/fastify/)
- [Add Password Reset to a Fastify API](https://getrush.ai/run/add-password-reset/fastify/)

## The same job on other stacks

- [Add Health Checks to a Fiber API](https://getrush.ai/run/add-health-checks/fiber/)
- [Add Health Checks to a Flask App](https://getrush.ai/run/add-health-checks/flask/)
- [Add Health Check Endpoints to a Gin App](https://getrush.ai/run/add-health-checks/gin/)

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