All jobs

Add Slow Query Logging to a Drizzle App

Yes. An agent adds a Drizzle logger for query text in development and a timing wrapper that reports any query function over a threshold, proved with pg_sleep.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

In a Next.js app laid out like vercel/chatbot, lib/db/queries.ts builds the client at module scope with postgres(process.env.POSTGRES_URL ?? "") and drizzle(client) with no options, and exports thirty async functions, from getUser to getStreamIdsByChatId, each wrapping its calls in a try that rethrows a ChatbotError("bad_request:database", { cause }). lib/errors.ts gives the database surface a visibility of log, so a failed query is logged rather than shown. Versions are drizzle-orm 0.45.2 and postgres 3.4.9 in pnpm-lock.yaml. instrumentation.ts registers @vercel/otel and the AI SDK's telemetry, so model calls are traced; database calls are not, because Drizzle's own tracer at this version is switched off: in drizzle-orm/src/tracing.ts the import of @opentelemetry/api is commented out, so tracer.startActiveSpan runs its callback with no span. Nothing in the repository says how long a query took.

Drizzle's Logger interface has one method, logQuery(query, params), and in the postgres-js session it is called before client.unsafe runs the statement, so a logger sees the SQL and its parameters and never a duration. The agent uses it for what it can do: a logger passed as drizzle(client, { logger }) that, only when isDevelopmentEnvironment from lib/constants.ts is true, prints the SQL and the number of parameters. It never prints parameter values, because message bodies, emails and password hashes pass through them. The timing lives one level up, where the duration is knowable: a timed(name, fn) helper in lib/db/queries.ts wraps the body of each exported function, measures it with performance.now(), and when the elapsed time exceeds SLOW_QUERY_MS, a new environment variable that leaves the feature off when unset, writes one slow_query line with the function name and the milliseconds, and adds the same as an event on the active OpenTelemetry span through @opentelemetry/api, which is already a dependency, so the line shows up in the trace Vercel's OTel setup already exports.

The functions that matter most get a name that reads well in a dashboard: getChatsByUserId, which the sidebar pages with startingAfter and endingBefore and runs two queries when either is set; getMessagesByChatId; getMessageCountByUserId, which the chat route runs on every message to count the last hour; and deleteChatById, which deletes votes, messages and streams before the chat. The wrapper changes none of their bodies or their ChatbotError handling, since the timing is taken around the try, and a thrown error is timed and rethrown unchanged.

Proof runs in the sandbox: the agent installs PostgreSQL with apt-get, sets POSTGRES_URL, runs pnpm install and pnpm db:migrate, then a throwaway tsx script that sets SLOW_QUERY_MS low, seeds a user and a chat through createUser and saveChat, calls getChatsByUserId to show no line for a fast query, and runs db.execute(sql.raw('select pg_sleep(2)')) through the same wrapper to show the slow_query line with its duration. It quotes both, deletes the script, and runs pnpm check, the Biome lint that lint.yml runs, on the changed file. The server's own log_min_duration_statement is named in the pull request as the complement on the database side, left to whoever administers it.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add slow query logging to this Next.js and Drizzle app. Read lib/db/queries.ts, lib/db/migrate.ts, lib/errors.ts, lib/constants.ts, instrumentation.ts, drizzle.config.ts, package.json and .github/workflows/lint.yml first. Pass a Drizzle Logger that prints the SQL and the parameter count in development only, never parameter values. Add a timing wrapper around every exported function in lib/db/queries.ts that, when SLOW_QUERY_MS is set and the call takes longer, writes one slow_query line with the function name and the milliseconds and adds an event on the active OpenTelemetry span; leave the feature off when the variable is unset and leave every function's body and ChatbotError handling unchanged. Install PostgreSQL in the sandbox, run pnpm install and pnpm db:migrate, then show with a throwaway script that a fast query logs nothing and a pg_sleep through the wrapper logs the line; quote both and delete the script. Run pnpm check. Open a pull request.",
  "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 changes lib/db/queries.ts and adds SLOW_QUERY_MS to .env.example with a line saying it is off when unset. No schema, migration or route changes. The description explains in two sentences why the duration is measured around the function rather than in the Drizzle logger, quotes the script's output for the fast call and the pg_sleep call, and quotes pnpm check.

The run's record keeps the PostgreSQL setup, the migration and the script run, so a reviewer can see the slow_query line with a real duration rather than a description of one.

Before merging, a reviewer sets SLOW_QUERY_MS in the deploy target to the threshold they care about, which the pull request cannot set, and decides whether the development logger's SQL output is wanted in their local logs or should be guarded by a second variable.

Run it on every latency alert

Once the lines exist, an alert on them is the trigger for the next job. A Grafana alert rule on the count of slow_query lines per minute posts to an automation's webhook trigger URL with the Authorization: Bearer <its secret> header Grafana's contact point can send; the automation's prompt asks the agent to read the function names in the alert, find the queries behind them in lib/db/queries.ts, run EXPLAIN ANALYZE on each against a database seeded from the migrations, and open a pull request with an index or a rewritten query and the plans before and after. The webhook's body reaches the agent after the prompt as event text.

A monitoring service that cannot send that header calls a handler on the reader's server instead, and the handler calls POST /o/{org}/sessions with a request_id that is a UUID v5 of the alert id, so a repeated notification returns the run already started.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The obvious place to time a query, the ORM's logger, cannot do it here, and finding that out means reading the library's session code at the pinned version. In a Rush sandbox the agent reads it, puts the timing where the duration is real, and proves the line appears with a query it slowed on purpose, so the pull request is built on what the library does rather than what its documentation implies.

The script run and its output stay in the run's record and the pull request quotes them, so review is checking a wrapper and a threshold variable rather than reproducing a slow query. A team with several Drizzle services runs the job on each at once, one sandbox and one pull request each, each wrapping that service's own query module.

Frequently asked questions

Why not log the duration from Drizzle's logger?

Because logQuery is called before the statement runs: in the postgres-js session at this version it fires and then client.unsafe executes, so the logger has no end time. It is still the right place for the SQL text in development, which is what the pull request uses it for.

Does this add spans for every query?

No. Drizzle's tracer is off at this version, with its OpenTelemetry import commented out, and the pull request does not turn it on. It adds an event to whatever span is active when a call crosses the threshold, through the @opentelemetry/api package the app already depends on, so the slow call shows inside the request trace Vercel's setup exports.

Will parameter values end up in logs?

No. The development logger prints the SQL and the count of parameters, never their values, since messages, emails and password hashes travel in them. The slow_query line carries the function name and the milliseconds only.

What about the database's own slow query log?

PostgreSQL's log_min_duration_statement logs slow statements on the server side with the real SQL, and it is the better tool when you administer the database. The pull request names it as the complement; the app-side line exists because a managed database may not expose that setting and because it carries the function name rather than the SQL.

More Drizzle jobs

The same job on other stacks

Keep reading