# Add Query Timeouts to a Drizzle and postgres.js Setup in Next.js

Yes. An agent sets statement and connect timeouts on your postgres.js client under Drizzle, maps a cancelled query to your error type, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-query-timeouts/drizzle/). 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 connection is made and how a failure surfaces. In a Next.js app laid out like vercel/chatbot, `lib/db/queries.ts` opens the client with `postgres(process.env.POSTGRES_URL ?? "")` and no options, wraps it in `drizzle` from `drizzle-orm/postgres-js`, and exports twenty-seven query functions, each with a `try` that rethrows as `new ChatbotError("bad_request:database", { cause: error })`. `lib/errors.ts` maps the `database` surface to `log` visibility, so `toResponse` prints the cause to the console and answers the client with a generic message. `package.json` pins `drizzle-orm` at `^0.45.2`, `postgres` at `^3.4.9` and `next` at `16.2.10`. `lib/db/migrate.ts` opens its own client with `{ max: 1 }`, the one place an option is passed. With no `statement_timeout`, a `getChatsByUserId` page over a large history or a `deleteMessagesByChatIdAfterTimestamp` that waits on a lock holds the request, and the route handler in `app/(chat)/api/history/route.ts` holds with it.

It sets the limits at the client. postgres.js takes a `connection` option whose keys become session parameters on every connection it opens, so the agent passes `connection: { statement_timeout: … }` there along with `connect_timeout` and `idle_timeout`, with the values read from environment variables documented in `.env.example` beside `POSTGRES_URL` and given defaults in one `lib/db/client.ts` that both `queries.ts` and `migrate.ts` import. The migration client keeps `max: 1` and gets a longer statement timeout, since `migrate` from `drizzle-orm/postgres-js/migrator` runs DDL that may rightly take longer than a request.

A cancelled query has to be told apart from a bad one. Postgres cancels a statement past its timeout with SQLSTATE `57014`, which postgres.js exposes as the error's `code`. The agent adds a `timeout` type to `ErrorType` in `lib/errors.ts` with a status code of 504, and a small `wrapDatabaseError` in `lib/db/client.ts` that the twenty-seven `catch` blocks call in place of the inline `new ChatbotError(...)`, returning `timeout:database` for `57014` and `bad_request:database` for anything else. The history route and the chat route already answer with `error.toResponse()`, so a timed-out query becomes a 504 with the generic database message, and the cause reaches the log as before.

The proof is a test that makes a query time out on purpose. The project's suite is Playwright under `pnpm test` with `PLAYWRIGHT=True`, which mocks the model but not the database, so the agent installs PostgreSQL in the sandbox, sets `POSTGRES_URL`, runs `pnpm db:migrate`, and adds a small `tsx`-run script under `tests/` that opens the client with a statement timeout of a fraction of a second, runs `select pg_sleep(…)` through `db.execute`, and asserts the error maps to `timeout:database`; a second case runs a normal query and asserts it succeeds under the same setting. It runs that script, `pnpm lint` and `tsc --noEmit`, and opens the pull request with the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add query timeouts to this Next.js app's Drizzle and postgres.js setup. Read package.json, .env.example, drizzle.config.ts, lib/db/queries.ts, lib/db/migrate.ts, lib/db/schema.ts, lib/errors.ts, app/(chat)/api/history/route.ts, app/(chat)/api/chat/route.ts and playwright.config.ts first. Create lib/db/client.ts that builds the postgres.js client with statement_timeout, idle_timeout and connect_timeout read from environment variables with sensible defaults, passes statement_timeout through the connection option so it applies to every session, and exports it for queries.ts; give migrate.ts its own client with max 1 and a longer statement timeout. Add a timeout error type to lib/errors.ts with a 504 status and a wrapDatabaseError helper that maps SQLSTATE 57014 to timeout:database and everything else to bad_request:database, and use it in every catch in queries.ts. Document the variables in .env.example. Install PostgreSQL in the sandbox, run pnpm db:migrate, add a tsx script under tests/ that proves a pg_sleep past the timeout maps to timeout:database and a normal query still succeeds, run it with pnpm lint and tsc --noEmit, and open a pull request with the 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 that adds `lib/db/client.ts` and the script under `tests/`, changes `lib/db/queries.ts`, `lib/db/migrate.ts`, `lib/errors.ts` and `.env.example`, and lists the defaults it chose for each timeout. The description shows the client options, the error mapping and the output of the timeout script, the lint run and the type check.

The run's record keeps the script run in which `pg_sleep` is cancelled and mapped to the new error, so a reviewer sees the 504 path rather than reads that it exists.

Before merging, a reviewer sets the request-path statement timeout against their slowest legitimate query, which the pull request helps with by naming the query functions it judged heaviest from their shape, `getChatsByUserId` and the two `deleteMessagesByChatIdAfterTimestamp` and `deleteDocumentsByIdAfterTimestamp` cleanups.

## Run it on every alert on slow database queries

This is the job to run when the database dashboard reports queries past a threshold or a connection pool that stays full. In the Project for the repository, an automation with the prompt above and a `webhook` trigger takes the alert from a Grafana contact point, which can send the trigger's bearer secret in an `Authorization` header and an `Idempotency-Key` made from the alert's fingerprint to the trigger's URL, so a re-fired alert does not start a second run. The trigger adds the alert body after the prompt, so the run reads which query or table was slow.

The first run adds the timeouts and the mapping. A later run on a repository that already has them reads the alert, checks whether the query it names needs its own `SET LOCAL statement_timeout` inside a `db.transaction`, and opens a pull request that changes that one function with the reason in the description, each on its own branch and linked to the alert.

## Why run it on Rush?

A missing timeout is invisible until the night the database is slow, and then every request waits with it. The fix is a few options and a code mapping, but proving it means a real Postgres, a query that genuinely runs too long and the error that comes back. The agent does that in its own sandbox and the record keeps the run, so the pull request carries the proof instead of a promise.

A company with several Next.js services on Drizzle and postgres.js runs this once per repository, each in its own sandbox with its own database and its own pull request, and reviews the same client file and the same mapping in each.

## Frequently asked questions

### Why set statement_timeout on the connection and not on each query?

The `connection` option makes postgres.js send it as a session parameter on every connection it opens, so every query function gets the limit with no per-call code. A function that legitimately needs longer wraps its statement in `db.transaction` with `SET LOCAL statement_timeout`, which the pull request shows once as the pattern.

### Will migrations time out?

No. `migrate.ts` keeps its own client with `max: 1` and a longer timeout, since adding an index or rewriting a table is expected to take longer than any request. The two clients share the connection string and nothing else.

### What does the user see when a query is cancelled?

The same generic database message as today, with a 504 instead of a 400, because the `database` surface keeps its `log` visibility in `lib/errors.ts`. The cause, with the SQLSTATE, goes to the server log, which is where the alert will point.

### Does this change the Playwright suite?

No. The e2e tests mock the model and run against whatever database `POSTGRES_URL` names, and a timeout of several seconds is far above anything they do. The proof for this change is the small script the agent adds, which the pull request shows how to run.

## More Drizzle jobs

- [Add Read Replicas to a Drizzle App](https://getrush.ai/run/add-read-replicas/drizzle/)
- [Add a Seed Script to a Drizzle ORM Project](https://getrush.ai/run/add-seed-data/drizzle/)
- [Add Slow Query Logging to a Drizzle App](https://getrush.ai/run/add-slow-query-logging/drizzle/)

## The same job on other stacks

- [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/)
- [Add Query Timeouts to a sqlc Project](https://getrush.ai/run/add-query-timeouts/sqlc/)

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