All jobs

Add Connection Pooling Limits to a Prisma App on Serverless

Yes. An agent sets connection_limit and pool_timeout on the Prisma URL for serverless, keeps one client per process, and proves the pool size against a real MySQL.

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

What the agent does

The pool already exists; nothing in the repository sizes it. In a Next.js app laid out like shadcn-ui/taxonomy, lib/db.ts builds new PrismaClient() with no options and caches it on global.cachedPrisma only when NODE_ENV is not production. prisma/schema.prisma uses the mysql provider with url = env("DATABASE_URL"), .env.example gives mysql://root:root@localhost:3306/taxonomy?schema=public, env.mjs checks only that the variable is a non-empty string, and the README says the database is on PlanetScale. Prisma is 4.13.0 in pnpm-lock.yaml. Eight files import db: the dashboard page, the editor page, the posts, post and users Route Handlers, the Stripe webhook, lib/auth.ts through PrismaAdapter, and lib/subscription.ts. On Vercel each of those runs as its own function, every function makes its own PrismaClient with its own pool, and Prisma 4 sizes that pool at num_physical_cpus * 2 + 1 connections with a 10 second pool_timeout, both documented as connection URL parameters.

The agent moves the two settings onto the URL, where Prisma 4 reads them. .env.example gains connection_limit and pool_timeout on DATABASE_URL, and the README's environment section explains the choice: Prisma's serverless guidance is to start at connection_limit=1 when no external pooler sits in front of the database, because every concurrent function multiplies that number, and to raise it only for a handler that sends queries in parallel. The agent reads each of the eight call sites for a Promise.all around db calls and finds none: app/api/posts/route.ts runs getUserSubscriptionPlan, db.post.count and db.post.create one after another, and the dashboard page makes one findMany. One connection per function is enough. lib/db.ts changes so the global cache applies in every environment, which costs nothing in production, where the module is evaluated once per process, and stops a hot reload in development from opening a second pool.

Proof needs a real MySQL, so in its sandbox the agent installs mysql-server with apt-get, starts it, creates the taxonomy database, runs pnpm install (the postinstall script runs prisma generate) and prisma migrate deploy, which applies the two migrations under prisma/migrations. Then it writes a throwaway script that fires twenty db.post.count() calls at once while a second connection polls SHOW STATUS LIKE 'Threads_connected'. With connection_limit=1 the reading stays one above the idle baseline; with the parameter removed it climbs toward the default; with connection_limit=1&pool_timeout=2 and the same twenty calls, some fail with Prisma's P2024 pool timeout, which is the error the pull request tells the reader to alert on. The script is deleted before the commit and its output is quoted in the description.

It runs pnpm lint and tsc --noEmit, the two checks the repository has, and leaves the deploy target's own settings to the reader: the pull request cannot edit the DATABASE_URL stored in Vercel, so the description ends with the exact value to paste there. It adds no pooler. PlanetScale already fronts this database, and whether to put Prisma Accelerate or a ProxySQL between the functions and it, instead of a small per-function limit, is a decision the description names and leaves open.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add connection pool settings to this Next.js and Prisma app for a serverless deploy. Read lib/db.ts, prisma/schema.prisma, .env.example, env.mjs, README.md and every file that imports db from @/lib/db first. Put connection_limit and pool_timeout on DATABASE_URL in .env.example, starting from Prisma's serverless guidance of connection_limit=1, and raise it only for a call site that sends queries in parallel; list the call sites you checked. Make lib/db.ts reuse one PrismaClient in every environment. Install MySQL in the sandbox, run pnpm install and prisma migrate deploy, then run twenty concurrent queries while polling SHOW STATUS LIKE 'Threads_connected' and quote the readings with and without the limit, and show the P2024 error a too-small pool_timeout produces. Run pnpm lint and tsc --noEmit. Do not add an external pooler; name it as an open decision. Open a pull request whose description gives the exact DATABASE_URL to set in the deploy target.",
  "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 .env.example, lib/db.ts and the README's environment section, and nothing under prisma/. The description lists the eight call sites and says none sends parallel queries, quotes the Threads_connected readings with and without connection_limit=1, quotes the P2024 error from the short pool_timeout run, and quotes pnpm lint and the type check.

The run's record keeps the MySQL install, the migrations, the load script and its output, so a reviewer can see the pool size change in the server's own counter rather than take the description's word for it.

Before merging, a reviewer sets the new DATABASE_URL in the deploy target, since the pull request cannot, and decides the open question the description names: a per-function limit of one, or an external pooler so handlers can grow. A team that expects a handler to fan out queries raises the limit for that function and says so in the README.

Run it on every database connection alert

A Grafana alert on Threads_connected approaching MySQL's max_connections is the moment to run this. Grafana's contact point can send a custom Authorization: Bearer <its secret> header, so it posts straight to an automation's webhook trigger URL in the Project that holds the app. The automation's prompt asks the agent to read the alert, the current DATABASE_URL parameters in the repository and the call sites, and open a pull request that lowers the limit or proposes a pooler, with the same Threads_connected proof; the webhook's body reaches the agent after the prompt as event text. The automation's max_runs_per_hour keeps a flapping alert from opening a pull request a minute.

A team whose monitoring cannot send that header runs a handler on their own server instead: the monitoring service calls the handler, and the handler calls POST /o/{org}/sessions with this page's body and a request_id that is a UUID v5 of the alert id, so a repeated notification returns the run already started instead of a second pull request.

The use case this job follows, with its automation and trigger: Fix a bug from an alert.

Why run it on Rush?

Pool sizing is only provable with a database and concurrency, which is why it usually ships as a guess. In a Rush sandbox the agent has a MySQL of its own, runs the migrations the repository already carries, and reads the server's connection counter under a real burst, so the number in the pull request is one it watched rather than one it read in a blog post.

Every command and its output stays in the run's record, and the pull request carries the quoted readings, so review is a comparison of numbers rather than a re-derivation. A team with several Prisma apps on serverless runs the job on each at once, one sandbox and one pull request each, each sized from that app's own call sites.

Frequently asked questions

Why connection_limit=1 when the default is bigger?

Because the default is per process, and on serverless every warm function is a process. Prisma's guidance for functions with no external pooler is to start at one connection and raise it only where a handler sends queries in parallel. None of the eight call sites in this app does, so one is enough, and since the limit is a URL parameter, raising it later is a deploy setting rather than a code change.

Does this change the PlanetScale setup?

No. PlanetScale is the host the README names, and the pull request only limits how many connections each function opens to it. Whether to put Prisma Accelerate or another pooler between the functions and the database is the decision the description leaves to the reviewer.

What does P2024 mean and should I expect it?

It is Prisma's pool timeout: a query waited pool_timeout seconds for a connection and none came free. The pull request shows it on purpose, with a two second timeout and twenty parallel queries on a pool of one, so the reader knows what the error looks like before an alert shows it. In normal traffic with serial handlers it should not appear; if it does, that handler needs a bigger limit.

Why cache the client in production too?

lib/db.ts already caches it outside production to survive hot reloads. Making the cache unconditional changes nothing on a cold start, since the module runs once per process, and removes a branch that behaves differently in the two environments, which is one less thing to reason about when reading connection counts.

More Prisma jobs

The same job on other stacks

Keep reading