# Add a Health Check Endpoint to a Socket.IO Server

Yes. An agent adds GET /health to each worker of a clustered Socket.IO server, checking SQLite and counting clients, with a node:test smoke test, and opens a PR.

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

## What the agent does

A Socket.IO server that runs under Node's `cluster` module has one process per core and no process that answers for all of them, so the agent reads how the processes are laid out before deciding what a probe can report. In a server laid out like socketio/chat-example, `index.js` is the whole application and `package.json` has `"type": "module"`, one script, `start`, and five dependencies: `express` resolved to `4.18.2`, `socket.io` to `4.7.2`, `@socket.io/cluster-adapter` to `0.2.2`, `sqlite` to `5.0.1` and `sqlite3` to `5.1.6` in `package-lock.json`. On the primary, `index.js` forks one worker per `availableParallelism()` with `PORT` set to `3000 + i` and calls `setupPrimary()` for the cluster adapter; the primary itself listens on nothing. Each worker opens `chat.db` with `sqlite`'s `open` and `sqlite3.Database` at module top level with `await`, creates the `messages` table, builds an Express app whose only route serves `index.html`, wraps it in `createServer`, and starts `new Server` with `connectionStateRecovery` and the cluster adapter. The connection handler inserts each `chat message` with its `client_offset` and replays missed rows for a client that was not recovered.

That layout decides three things. A health route has to live on each worker's Express app, because the ports are per worker and a load balancer in front of them probes each one. The check that matters is the database, since every worker holds its own handle to the same `chat.db` file and a locked or missing file is what turns a working socket into a silent one. And `io.engine.clientsCount` on each worker counts only that worker's sockets, which is the right thing for a per-process probe. There is no test runner, no `.github` directory and no lint configuration; `.codesandbox/Dockerfile` says `FROM node:20`, the only statement of which Node the project expects, and `.gitignore` keeps `chat.db` out of git.

The agent adds `app.get('/health', …)` before the `/` route in the worker branch. It runs `db.get('SELECT 1')` inside a `try`, and answers 200 with `{ status: 'ok', worker: cluster.worker.id, pid: process.pid, port, clients: io.engine.clientsCount, uptime: process.uptime() }`, or 503 with `status: 'degraded'` and the error message when the query throws. It sets `Cache-Control: no-store` so a proxy never answers a probe from cache, and keeps the handler synchronous apart from the one query so it answers under load. The response is JSON through `res.json`, and the handler is a dozen lines in the same file, since the project keeps everything in `index.js` and a second module would be the first structural change the repository has seen.

To prove it the agent adds a test the repository can keep. `test/health.test.js` uses Node's built-in `node:test` and `node:assert`, spawns `node index.js` as a child process with `PORT` unset as the primary expects, polls `http://localhost:3000/health` with `fetch` until the first worker answers, asserts the status, the `status: 'ok'` field, a numeric `clients` and the `Cache-Control` header, then sends `SIGTERM` to the child and removes the `chat.db` the run created. `package.json` gains a `test` script, `node --test`. The agent runs `npm ci` from the lockfile and `npm test` in its sandbox on Node 20, then starts the server by hand and requests `/health` on two worker ports to show each reports its own `worker` and `pid`. It makes `chat.db` unreadable for a moment to show the 503 path, and pastes both responses.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a health check endpoint to this clustered Socket.IO chat server. Read index.js, package.json, package-lock.json, .gitignore and .codesandbox/Dockerfile first. In the worker branch of index.js, add GET /health on the Express app that runs SELECT 1 on the open sqlite database and answers 200 with status, worker id, pid, port, io.engine.clientsCount and uptime, or 503 with status degraded and the error message when the query throws, with a Cache-Control: no-store header. Add test/health.test.js on node:test that spawns node index.js, polls http://localhost:3000/health until it answers, asserts the status, body fields and header, then stops the child and removes chat.db, and add a test script running node --test. Run npm ci and npm test on Node 20, start the server and request /health on two worker ports, show the 503 path by making chat.db unreadable, and open a pull request with both responses and the test output. Do not change the socket handlers or index.html.",
  "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

The pull request changes `index.js` and `package.json` and adds `test/health.test.js`. Its description shows a 200 response from two worker ports with different `worker` and `pid` values, the 503 response with the SQLite error, and the `node --test` output from the sandbox. No dependency is added; the test uses `node:test`, `node:child_process` and `fetch`, all built into Node 20.

The repository has no workflow, so GitHub shows no check on the pull request; the run's record is where a reviewer reads `npm ci`, `npm test` and the two `curl` calls. The description points at a one-job workflow running `npm ci` and `npm test` as the natural follow-up now that there is a test to run.

Before merging, a reviewer decides whether the probe should also count across workers through the cluster adapter, which this one does not, whether a load balancer should probe every port or only the first, and whether `uptime` and `pid` belong in a response a public port exposes. The socket handlers, the `messages` table and `index.html` are unchanged.

## Run it on every Socket.IO service without a health route

An organisation with several real-time 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. Each run reads its own server file, so a service on the Redis adapter gets a probe that pings Redis instead of SQLite, one on a single process gets the route without the cluster fields, and one already serving `/healthz` gets a report of what that route checks and no pull request.

A team that wants the probe checked before each release runs the follow-up as an automation in the Project with a `github` trigger on `pull_request.opened`. The trigger adds the pull request after the prompt, and the run starts the server on that branch, requests `/health` on every worker port and comments with the responses, so a change that breaks the database open or the adapter is seen as a failed probe rather than a quiet socket.

## Why run it on Rush?

The route is short, but where it goes is the whole question: on the primary it answers nothing, on one worker it says nothing about the others, and a probe that skips the database reports a server that accepts connections and loses every message. The agent reads the cluster layout, starts the server in its own sandbox and requests the probe on more than one port, so the pull request shows per-worker answers rather than describing them.

Every command stays with the run, from `npm ci` to the deliberately broken database, so a reviewer sees both the healthy and the degraded response before merging. The same prompt runs across every Socket.IO service at once, each in its own sandbox and with its own pull request.

## Frequently asked questions

### Why is the health route on each worker and not on the primary?

Because the primary in `index.js` forks the workers and calls `setupPrimary()` for the cluster adapter but opens no port; every listener is a worker on `3000 + i`. A load balancer probes the ports it sends traffic to, so each worker answers for itself, and the response names its `worker` id and `pid` so a failing one can be found.

### What does the SQLite check catch?

A `chat.db` that was deleted, is unreadable or is locked by another process. The connection handler inserts every message into it, so a worker whose handle is broken still accepts sockets and silently drops messages; `SELECT 1` through the same handle turns that into a 503 the probe can see.

### Does clients count every connected user?

No. `io.engine.clientsCount` is the number of sockets on that worker. The cluster adapter forwards events between workers but does not sum connections, so a total needs `io.serverSideEmit` or the adapter's `fetchSockets`; the pull request leaves that out of a probe that must answer fast and says how to add it.

### Why node:test rather than Jest or Mocha?

The repository has no test runner and no dev dependencies, and `.codesandbox/Dockerfile` names Node 20, where `node --test`, `fetch` and `node:assert` are built in. One file and one script line add a test without changing how the project installs.

## More Socket.IO jobs

- [Add Input Validation to a Socket.IO Chat](https://getrush.ai/run/add-input-validation/socket-io/)
- [Add JWT Authentication to a Socket.IO Server](https://getrush.ai/run/add-jwt-authentication/socket-io/)
- [Show Online Users in a Socket.IO Chat](https://getrush.ai/run/add-online-users/socket-io/)

## The same job on other stacks

- [Add Health Checks to a Symfony App](https://getrush.ai/run/add-health-checks/symfony/)
- [Add Health Check Endpoints to a tRPC and Next.js App](https://getrush.ai/run/add-health-checks/trpc/)
- [Add Health Checks to a Vapor App](https://getrush.ai/run/add-health-checks/vapor/)

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