# Add Prometheus Metrics to an Express and Sequelize API

Yes. An agent adds a /metrics route with request and query histograms to your Express and Sequelize API, from the timings Sequelize already measures, and opens a PR.

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

## What the agent does

The agent reads how requests and queries flow before it adds a counter anywhere. In an API laid out like the `express-main-example` in sequelize/express-example, `express/app.js` builds the route table in a loop: for each module in `routes` it registers `GET /api/<name>`, `GET /api/<name>/:id`, `POST`, `PUT` and `DELETE` when the module exports `getAll`, `getById`, `create`, `update` and `remove`, each wrapped by `makeHandlerAwareOfAsyncErrors` so a rejected promise reaches `next(error)`. `sequelize/index.js` opens SQLite at `sqlite-example-database/example-db.sqlite` with `logQueryParameters: true` and `benchmark: true`, which is the detail that matters: with `benchmark` on, Sequelize calls the `logging` function with the SQL as its first argument and the elapsed milliseconds as its second, and today that function is the default `console.log`, which prints lines like `Executed (default): SELECT ... Elapsed time: 1ms`. `package.json` pins `express ^4.17.1`, `sequelize ^6.3.3`, `sqlite3 ^5.0.0` and `body-parser`, has `start` and `setup-example-db` scripts and no test or lint script, `.npmrc` turns the lockfile off, and `express/helpers.js` throws a `TypeError` for a non-numeric `:id`, which the wrapper turns into Express's default 500.

One thing the agent checks before installing anything: on npm, `prom-client` is marked deprecated with the note that it has been replaced by `@prometheus-io/client`, so that is the package it adds, as a regular dependency, with the same exports (`register`, `Histogram`, `Counter`, `collectDefaultMetrics`, `contentType`). It writes `express/metrics.js` with three things. `collectDefaultMetrics()` on the default registry, which gives `process_cpu_seconds_total`, `process_resident_memory_bytes`, `nodejs_eventloop_lag_seconds`, `nodejs_heap_size_used_bytes`, `nodejs_gc_duration_seconds` and the rest with no further code. An `http_request_duration_seconds` histogram with `method`, `route` and `status_code` labels, observed from a middleware that starts a timer and ends it on the response's `finish` event, with `route` taken from `req.route.path` so it reads `/api/users/:id` and never the actual id; a request that matched no route is labelled `unmatched`. And a `sequelize_query_duration_seconds` histogram with one `statement` label, fed from a `logging` function in `sequelize/index.js` that keeps the existing `console.log` line and also observes `ms / 1000` under the query's first word, `SELECT`, `INSERT`, `UPDATE` or `DELETE`, so the SQL text itself, which carries parameters because of `logQueryParameters`, never becomes a label.

The route goes in `express/app.js` outside the loop: `app.get('/metrics', ...)` sets `Content-Type` to the client's `contentType` value, `text/plain; version=0.0.4; charset=utf-8`, and sends `await register.metrics()`. It is registered before the `/api` routes so the middleware does not time the scrape itself. The root `/` handler and the three route modules under `express/routes/` are untouched, and so is `sqlite-example-database/setup.js`, whose `sequelize.sync({ force: true })` and seed data are what the agent uses to get a database to measure.

To prove it, the agent runs `npm install`, `npm run setup-example-db` and `npm start` in its sandbox, sends a few requests with `curl` to `/api/users`, `/api/orchestras?includeInstruments` and `/api/users/abc`, then reads `/metrics` and pastes the histogram lines into the pull request: the `http_request_duration_seconds_bucket` series with `route="/api/users/:id"` and `status_code="500"` for the bad id, and the `sequelize_query_duration_seconds_count` for `SELECT`. Because the project has no test runner and `engines` says Node 10 or newer, it adds no test framework; the curl transcript in the run is the check, and the description says so.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add Prometheus metrics to this Express and Sequelize API. Read package.json, .npmrc, index.js, express/app.js, express/helpers.js, express/routes/users.js, express/routes/orchestras.js, express/routes/instruments.js, sequelize/index.js, sequelize/extra-setup.js and sqlite-example-database/setup.js first. Check npm for the current Prometheus client package and its deprecation notice before installing; add only that one dependency. Write express/metrics.js with collectDefaultMetrics, an http_request_duration_seconds histogram labelled by method, route template from req.route.path and status_code, observed on the response finish event, and a sequelize_query_duration_seconds histogram labelled by statement verb only, fed from a logging function in sequelize/index.js that uses the elapsed milliseconds benchmark already passes and keeps the existing console output. Add GET /metrics in express/app.js before the /api routes with the client's content type. Do not change the route modules or setup.js. In the sandbox run npm install, npm run setup-example-db and npm start, send requests including a bad :id, read /metrics and open a pull request that pastes the histogram lines.",
  "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 `express/metrics.js`, adds one dependency to `package.json`, changes `sequelize/index.js` to pass a `logging` function beside `benchmark: true`, and adds the middleware and the `/metrics` route to `express/app.js`. The description names the metric families and their labels, with the bounded label values written out, and pastes the `/metrics` excerpt from the sandbox after the sample requests.

The run's record holds the install, the database setup with its 51 executed statements, the server start, every `curl` and the full scrape, so a reviewer sees which `route` and `status_code` values appeared and that no SQL text or id reached a label.

Before merging, a reviewer checks the histogram buckets against the latency the API actually has, decides whether `/metrics` needs to be kept off the public listener, and confirms the Prometheus scrape config points at port 8080 from `index.js`. Nothing else in the routes changes.

## Run it on every Express service without a /metrics route

A team that runs several small Express services sends one `POST /o/{org}/sessions` per repository from its terminal or a script, with this prompt and that repository in `resources`, and a `request_id` that is a UUID v5 of the repository name so a retried call returns the run already started. `GET /o/{org}/github` lists every repository the Rush GitHub App installation can reach, so the script can start a run only where no `/metrics` route exists.

Each run reads that service's own app file and ORM setup, so a service on Knex or Prisma gets its query histogram from that library's hooks instead, and each opens its own pull request. A webhook URL on the API key reports `run.completed` with the `session_url` to read the pull request link from.

## Why run it on Rush?

The work is small and the mistakes are specific: a label built from `req.path` that turns every user id into a new series, a query label built from the SQL text that leaks parameters into Prometheus, a scrape that times itself, and the wrong npm package because the one everybody remembers was deprecated this year. The agent reads the route loop and the Sequelize options first, uses the elapsed time Sequelize already computes rather than wrapping the query layer, and checks the registry before adding a dependency.

In its own sandbox it seeds the SQLite database, starts the server and reads the scrape, so the pull request shows real histogram lines rather than a description of them, and the run keeps every command and its output. The same request runs against every Express service a team owns, each in its own sandbox, each pull request shaped by that service's own routes.

## Frequently asked questions

### Why @prometheus-io/client rather than prom-client?

Because npm marks `prom-client` as deprecated with the message that it has been replaced by `@prometheus-io/client`. The new package has the same registry, histogram and default-metrics API, so the code is the same either way; the agent checks the registry at run time and installs what is current.

### How does it time Sequelize queries without wrapping them?

`sequelize/index.js` already sets `benchmark: true`, which makes Sequelize pass the elapsed milliseconds as the second argument of the `logging` function on every query. The agent replaces the default `console.log` with a function that prints the same line and observes `ms / 1000` in the histogram. No hook or query wrapper is added.

### Will the route label explode with ids?

No. The label is `req.route.path`, which Express sets to the registered pattern, `/api/users/:id`, not the URL that was requested. The loop in `app.js` registers a fixed set of patterns, so the set of `route` values is the set of routes plus `unmatched` for a request that hit none.

### What about the SQL text and query parameters?

They stay out. `logQueryParameters: true` puts parameter values into the logged SQL, so the agent labels queries by their first word only, `SELECT`, `INSERT`, `UPDATE` or `DELETE`. The SQL itself keeps going to the console as before.

### Is there a test?

The repository has no test script and allows Node 10 in `engines`, so the agent adds no test framework. The check is the sandbox transcript: seed, start, requests, scrape, pasted into the pull request and kept in the run. A reviewer who wants a permanent test can ask for one with `node:test` and a Node floor of 18 in a follow-up.

## More Sequelize jobs

- [Add Slow Query Logging to a Sequelize App](https://getrush.ai/run/add-slow-query-logging/sequelize/)
- [Add Soft Delete to Sequelize Models in an Express App](https://getrush.ai/run/add-soft-delete/sequelize/)
- [Add Structured Logging to a Sequelize App](https://getrush.ai/run/add-structured-logging/sequelize/)

## The same job on other stacks

- [Add Prometheus Metrics to a Slim 4 App](https://getrush.ai/run/add-prometheus-metrics/slim/)
- [Add Prometheus Metrics to a Socket.IO Server](https://getrush.ai/run/add-prometheus-metrics/socket-io/)
- [Expose Temporal Worker Metrics to Prometheus in a TypeScript Project](https://getrush.ai/run/add-prometheus-metrics/temporal/)

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