# Add Query Timeouts to a TypeORM + NestJS App

Yes. An agent sets a Postgres statement timeout on the pool behind TypeORM, keeps migrations exempt, maps the error to a 503, proves it with pg_sleep and opens a PR.

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

## What the agent does

The agent reads where the connection is configured, because in this app there are two places and they must agree. In an API laid out like brocoders/nestjs-boilerplate, `typeorm` 0.3.28 and `pg` 8.20.0 are driven from `src/database/typeorm-config.service.ts`, the `TypeOrmOptionsFactory` that `app.module.ts` hands to `TypeOrmModule.forRootAsync`, and from `src/database/data-source.ts`, the `AppDataSource` the `migration:*` scripts in `package.json` use. Both build an `extra` block for the `pg` pool with `max` from `DATABASE_MAX_CONNECTIONS` and an `ssl` object from the `DATABASE_SSL_*` variables, and nothing else: a search for `statement_timeout`, `query_timeout` and `connectionTimeoutMillis` across `src/` finds no hit. `src/database/config/database.config.ts` validates every `DATABASE_*` variable with class-validator in `EnvironmentVariablesValidator` and exposes them through `registerAs('database')`, and `env-example-relational` is the file CI and developers copy.

It adds the timeout at the pool, where every query passes, rather than per repository call. `pg` accepts `statement_timeout` in milliseconds on a client's config and sends it as a session setting when the connection opens, so a `statement_timeout: <ms>` entry in `extra` reaches every connection TypeORM checks out, including the ones `Repository.find` in `UsersRelationalRepository` and the raw `query()` calls use. Two environment variables carry it: `DATABASE_STATEMENT_TIMEOUT_MS` and `DATABASE_CONNECT_TIMEOUT_MS`, the second mapped to `connectionTimeoutMillis` so a database that accepts no connection fails fast instead of hanging a request. Each gets an `@IsInt() @IsOptional()` line in the validator, a field in `database-config.type.ts` and `database.config.ts`, a line in `env-example-relational`, and a paragraph in `docs/database.md`.

The CLI data source is the exception the agent writes on purpose. A migration that adds an index to a large table runs longer than any request should, so `data-source.ts` sets `statement_timeout: 0`, which disables it for the `migration:run` and `migration:generate` scripts, and the pull request says why the two files now differ in that one line. On the request side, Postgres cancels a slow statement with SQLSTATE `57014` and `pg` surfaces it as an error with that `code`; TypeORM wraps it in `QueryFailedError`, which Nest's default filter turns into a bare 500. The agent adds a small exception filter that recognises `57014` on the driver error and answers 503 with a stable error code, so a dashboard can tell a timed-out query from a crash.

The proof runs in the sandbox against a real Postgres, installed from apt and started there, with `env-example-relational` copied to `.env` and the host set to localhost. The agent runs `npm run migration:run`, then a test in `src/database/` that opens a `DataSource` with a one-second timeout and runs `select pg_sleep(2)`, asserting the rejection's `code` is `57014`, and a second case with the timeout at `0` that completes. It starts the app and sends a request through the new filter to read the 503 body. The existing e2e suite runs through `docker compose` in `.github/workflows/docker-e2e.yml`, so the agent leaves that workflow alone and runs `npm run lint` and `npm run test` before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add query timeouts to the TypeORM setup. Read src/database/typeorm-config.service.ts, src/database/data-source.ts, src/database/config/database.config.ts, src/database/config/database-config.type.ts, src/app.module.ts, env-example-relational, docs/database.md and package.json first, and confirm no timeout is set today. Add DATABASE_STATEMENT_TIMEOUT_MS and DATABASE_CONNECT_TIMEOUT_MS, validated like the other DATABASE_ variables, and pass them to the pg pool through extra as statement_timeout and connectionTimeoutMillis in the Nest config service. Set statement_timeout to 0 in the CLI data source so migrations are exempt, and say why in the pull request. Add an exception filter that maps Postgres error 57014 to a 503 with a stable code. Install Postgres in your sandbox, run the migrations, and prove the timeout with a test that runs select pg_sleep past the limit and one that completes under it. Run npm run lint and npm run test, and open a pull request that quotes the test output and the 503 body.",
  "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 touches the two data source files, the three config files under `src/database/config/`, `env-example-relational`, `docs/database.md`, one new exception filter and one new test. Its description quotes the test output with the `57014` rejection and the completing case, the 503 body from a request through the filter, and the lint and unit test output.

The run's record keeps the Postgres install, the migration run and the test run, so a reviewer can see the timeout fire against a real server rather than read a mocked error.

Before merging, a reviewer sets the production value, since the agent's default is a starting point and the right number depends on the slowest legitimate query in the app, and decides whether the document-database configuration in `src/database/mongoose-config.service.ts` should get the equivalent `serverSelectionTimeoutMS`, which the pull request names as a follow-up.

## Run it on every database alert

A Grafana contact point can call a `webhook` trigger on a Project automation directly, with `Authorization: Bearer <its secret>` in the contact point's headers, when a long-running-queries alert fires; the automation runs a prompt that reads the alert's query and this change, and comments on whether the timeout would have caught it. The trigger's URL also takes an `Idempotency-Key` from the alert's fingerprint, so Grafana's repeat notifications do not start repeat runs.

A team with several NestJS services on TypeORM starts one run per repository from a script, `POST /o/{org}/sessions` with this `input` and the repository in `resources`, with a `request_id` that is a UUID v5 of the repository's full name. Each run reads that service's own config files, so one that already sets `statement_timeout`, or one on MySQL where the option is `connectTimeout` and a `max_execution_time` hint, gets a pull request that fits it.

## Why run it on Rush?

A timeout is cheap to add and easy to get wrong in the one place that matters: the migration runner, where a cut-off statement leaves a half-applied schema. The agent reads both data sources, exempts the right one, and proves the request-side limit against a Postgres it installed itself, with the `pg_sleep` test and the 503 body in the run's record.

Across many services the runs happen at once, one sandbox each, and every pull request carries that service's own test output, so a reviewer checks evidence rather than a template.

## Frequently asked questions

### Why statement_timeout in extra rather than maxQueryExecutionTime?

`maxQueryExecutionTime` is TypeORM's slow-query logger: it reports a query that ran long after it finished and never stops it. `statement_timeout` is enforced by Postgres and cancels the statement. They answer different questions, and this change is about the second.

### Does the timeout apply to transactions?

Per statement, not per transaction. Each statement inside a transaction gets its own budget, so a transaction of many fast statements is unaffected. A cap on a whole transaction is `idle_in_transaction_session_timeout` for the idle gaps, which the pull request names but does not set.

### What happens to the request when a query is cancelled?

`pg` rejects with an error whose `code` is `57014`, TypeORM throws `QueryFailedError` around it, and the new filter turns that into a 503 with a stable code and logs the SQL summary. The connection goes back to the pool in a clean state because Postgres cancelled only the statement.

### Why not set it in postgresql.conf instead?

A server-side default covers every client, including migrations and ad-hoc sessions, which is the opposite of what the migration exemption needs. Setting it per pool keeps the policy next to the code that opens the connections and lets the CLI and the app differ.

## More TypeORM jobs

- [Add Read Replicas to a TypeORM App](https://getrush.ai/run/add-read-replicas/typeorm/)
- [Add Seed Data to a NestJS TypeORM App](https://getrush.ai/run/add-seed-data/typeorm/)
- [Add Slow Query Logging to a TypeORM + NestJS App](https://getrush.ai/run/add-slow-query-logging/typeorm/)

## The same job on other stacks

- [Add Query Timeouts to a Drizzle and postgres.js Setup in Next.js](https://getrush.ai/run/add-query-timeouts/drizzle/)
- [Add Query Timeouts to a GORM App](https://getrush.ai/run/add-query-timeouts/gorm/)
- [Add Query Timeouts to a Flask and SQLAlchemy App](https://getrush.ai/run/add-query-timeouts/sqlalchemy/)

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