# Add OpenTelemetry Tracing to a Fastify API

Yes. An agent adds the OpenTelemetry Node SDK with Fastify, Knex and MySQL instrumentation to your API, proves a trace with a test and a request, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-opentelemetry/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 server boots, because tracing has to be in place before the first plugin loads. In an API shaped like fastify/demo, `package.json` sets `"type": "module"`, pins `fastify` `^5.10.0`, `@fastify/autoload`, `@fastify/under-pressure` `^9.1.0`, `knex` `^3.3.0` on `mysql2` `^3.23.1`, `close-with-grace` and TypeScript `~6.0.3`, and runs tests with `node:test` through `glob -c "tsx --test" "./test/**/*.ts"` under `c8`. `src/server.ts` builds the instance with pino logging, connection and request timeouts and an Ajv config, registers `serviceApp` through `fastify-plugin`, wires `closeWithGrace`, and listens on `PORT` or 3000. `src/app.ts` autoloads `plugins/external`, then `plugins/app`, then `routes`, and sets the error and not-found handlers. There is no tracing anywhere.

The agent adds `@opentelemetry/sdk-node`, `@opentelemetry/api`, `@fastify/otel`, the official Fastify instrumentation whose peer is `@opentelemetry/api` 1.9, `@opentelemetry/instrumentation-knex`, `@opentelemetry/instrumentation-mysql2` and an OTLP HTTP trace exporter. A new `src/instrumentation.ts` creates a `NodeSDK` with those instrumentations, a resource whose service name comes from `OTEL_SERVICE_NAME`, and the exporter pointed at `OTEL_EXPORTER_OTLP_ENDPOINT`, and starts it. Because the package is ESM, the SDK is loaded with Node's `--import` flag rather than a `require` at the top of `server.ts`: `start` becomes `node --import ./dist/instrumentation.js dist/server.js` and `dev` passes the same file to `tsx --import`. The Fastify instrumentation is also registered as a plugin in a new `src/plugins/external/otel.ts`, the form `@fastify/otel` offers, so every route gets a span named after its route pattern even when the loader is absent, as it is in the tests.

Configuration follows `src/plugins/external/env.ts`, where `@fastify/env` validates `process.env` against a JSON schema and decorates the instance as `fastify.config`. The agent adds `OTEL_SERVICE_NAME` and `OTEL_EXPORTER_OTLP_ENDPOINT` as optional string properties, so a missing endpoint means spans are created but not exported, and adds both to `.env.example` beside `LOG_LEVEL`. The `healthCheck` that `under-pressure.ts` runs against Knex every `healthCheckInterval` would otherwise produce a span every few seconds, so the Knex instrumentation is configured to drop it.

The test lives with the others under `test/app/`. It registers an in-memory span exporter from `@opentelemetry/sdk-trace-base` as the global tracer provider, builds the app with `build(t)` from `test/helper.ts`, injects `GET /`, and asserts that one span carries the route pattern and `http.response.status_code` of 200. Before pushing, the agent runs what `.github/workflows/ci.yml` runs: `npm run build -- --noEmit`, `npm run lint` with the repository's `neostandard` config, and `npm run db:migrate && npm run test` against a MySQL started with the same `mysql:8.4` image and credentials the workflow's service block lists. It then starts the server with the SDK's console exporter, sends `GET /api/tasks` after logging in, and pastes the printed spans, HTTP, Knex and MySQL, into the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add OpenTelemetry tracing to this Fastify API and open a pull request. Read package.json, src/server.ts, src/app.ts, src/plugins/external/env.ts, src/plugins/external/knex.ts, src/plugins/external/under-pressure.ts, src/plugins/README.md, test/helper.ts, test/app/rate-limit.test.ts, .env.example and .github/workflows/ci.yml first. Add @opentelemetry/sdk-node, @opentelemetry/api, @fastify/otel, @opentelemetry/instrumentation-knex, @opentelemetry/instrumentation-mysql2 and @opentelemetry/exporter-trace-otlp-http. Create src/instrumentation.ts that starts a NodeSDK with those instrumentations, the service name from OTEL_SERVICE_NAME and an OTLP exporter at OTEL_EXPORTER_OTLP_ENDPOINT, and load it with node --import in the start script and tsx --import in the dev script since the package is ESM. Register the @fastify/otel plugin in a new src/plugins/external/otel.ts so route spans exist without the loader. Add OTEL_SERVICE_NAME and OTEL_EXPORTER_OTLP_ENDPOINT as optional properties in env.ts and to .env.example. Ignore the under-pressure health check query in the Knex instrumentation. Add test/app/otel.test.ts that installs an in-memory span exporter, builds the app with the helper, injects GET / and asserts a span with the route and a 200 status. Run npm run build -- --noEmit, npm run lint and npm run test against a MySQL started like ci.yml does, then start the server with a console exporter, request GET /api/tasks after logging in and paste the spans in the pull request description. Do not change any route, schema or migration.",
  "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 `src/instrumentation.ts`, `src/plugins/external/otel.ts`, the two optional keys in `src/plugins/external/env.ts` and `.env.example`, the changed `start` and `dev` scripts, the new dependencies in `package.json` and `package-lock.json`, and `test/app/otel.test.ts`. The description shows the build, lint and test output from the branch and the console spans from one authenticated request to `/api/tasks`, with the Fastify span as the parent and the Knex and MySQL spans beneath it.

The repository's `CI` workflow runs the matrix on Node 22 and 24 against its MySQL service, so the new test runs twice with the rest of the suite and `c8` counts the new files. The agent pushes one commit for the SDK and plugin, one for configuration and scripts, and one for the test.

A reviewer checks that `start` still works without `OTEL_EXPORTER_OTLP_ENDPOINT` set, that the health check query is not traced, that the span names use the route pattern rather than the concrete URL, and that `closeWithGrace` still shuts the SDK down with the app. Then they set the endpoint to their collector in the deployment's environment.

## Run it on every service without tracing

A team bringing every Node service onto one collector 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 client and boot sequence, so a service on Postgres gets the `pg` instrumentation and a CommonJS one gets a `--require` rather than `--import`, and each run opens its own pull request.

The key's `webhook_url` receives `run.completed` for each run it starts, with a `session_url` for the result, so a script can list the pull request links in the team channel as they land.

## Why run it on Rush?

Wiring the SDK is a small change; the risk is loading it in the wrong order, in which case every span is missing and nothing says why. In a Rush sandbox the agent starts the server with the console exporter, sends real requests and reads the spans back, and that output is kept in the transcript, so the pull request shows the HTTP, Knex and MySQL spans rather than asserting they would appear.

The change respects the repository's own structure, an `env.ts` schema, a plugin under `plugins/external`, a `node:test` file built with the shared helper, and passes its CI matrix before a reviewer opens it. The same request works unchanged across every Fastify service the team owns.

## Frequently asked questions

### Why both a --import loader and a Fastify plugin?

The loader starts the SDK before `server.ts` so Knex and MySQL calls are patched. The plugin form of `@fastify/otel` hooks Fastify's own lifecycle, so route spans with the route pattern exist even in tests built from `test/helper.ts`, which never pass through the loader.

### Does it work with the ESM package?

Yes. `package.json` sets `type` to `module`, so the agent uses `node --import` and `tsx --import` instead of `--require`, and checks in the sandbox that the MySQL and Knex spans appear under that loader before it pushes. If an instrumentation needs the ESM hook as well, the register file is added and named in the pull request.

### What happens when no collector endpoint is set?

The two variables are optional in the `@fastify/env` schema, so the app starts as before. Spans are still created, the test still passes with its in-memory exporter, and nothing is exported until `OTEL_EXPORTER_OTLP_ENDPOINT` names a collector.

### Will the under-pressure health check flood the collector?

No. `under-pressure.ts` runs `SELECT 1` through Knex every `healthCheckInterval`, and the Knex instrumentation is configured to ignore that statement, so only request-driven queries produce spans.

## More Fastify jobs

- [Add Password Reset to a Fastify API](https://getrush.ai/run/add-password-reset/fastify/)
- [Add Prometheus Metrics to a Fastify App](https://getrush.ai/run/add-prometheus-metrics/fastify/)
- [Add a Redis Session Store to a Fastify App from a Linear Issue](https://getrush.ai/run/add-redis-sessions/fastify/)

## The same job on other stacks

- [Add OpenTelemetry Tracing to a Flask App](https://getrush.ai/run/add-opentelemetry/flask/)
- [Add OpenTelemetry Tracing to a Gin API](https://getrush.ai/run/add-opentelemetry/gin/)
- [Add OpenTelemetry Tracing to a Go Service](https://getrush.ai/run/add-opentelemetry/go/)

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