A Prisma 7 API on a serverless platform starts failing with too-many-connections errors during a traffic spike; why does it happen, and how do you fix it?
answer
- count the pools, not the clients
- instances times max
- where the client is constructed
- a pooler between functions and database
basics
~20 sEvery function instance runs its own PrismaClient and PrismaPg pool, default max 10, so a spike multiplies connections by the instance count. Build the client outside the handler, shrink max, cap concurrency, and route runtime traffic through a connection pooler.
solid answer
~40 sOn a serverless platform each concurrent instance loads the module and constructs its own `PrismaClient`, and in Prisma 7 each client's `PrismaPg` adapter owns a `pg` pool with `max` 10 by default. A spike to 30 instances can therefore ask PostgreSQL for up to 300 connections, and the database refuses the rest; `PrismaPg` reports that as `P2037`, "Too many database connections opened". Paused or retiring instances can keep theirs open too. The fix: construct the client at module scope so warm invocations reuse its pool, do not `$disconnect()` per invocation, set a small `max` on the adapter, cap the function's concurrency below the database limit divided by connections per instance, and, if you need more, put a pooler such as PgBouncer in transaction mode in front and give `PrismaPg` its URL.
code
typescript · 15 linesimport { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";
// Module scope: built once per instance, reused while the instance stays warm.
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
max: 2,
connectionTimeoutMillis: 5_000,
});
const prisma = new PrismaClient({ adapter });
export async function handler() {
const users = await prisma.user.findMany({ take: 20 });
return { statusCode: 200, body: JSON.stringify(users) };
}go deeper
Remember that every serverless instance has its own PrismaClient and its own pool, so instances multiply connections.
Explain the product of instances and pool max, the P2037 mapping, and why the client belongs at module scope.
Diagnose from instance and connection counts, then apply the fixes in order: module-scope client, small max, concurrency cap, pooler.
Weigh a per-function pool budget and a pooler's operating cost against the platform's scaling, and set the limits as team defaults.
## The arithmetic behind the failure A **serverless platform** runs your handler in instances it starts and stops on demand. When traffic rises it starts more instances in parallel, and each one is a separate process that loads your modules from scratch. In Prisma 7 that means each instance constructs its own `PrismaClient` with its own driver adapter, and `PrismaPg` gives each one a node-postgres pool. Nothing is shared between instances. The connection count the database sees is roughly: `instances running at once x connections each instance's pool opens` | Instances | Pool `max` | Worst-case connections | |---|---|---| | 3 | 10 (default) | 30 | | 30 | 10 (default) | 300 | | 30 | 2 | 60 | PostgreSQL has a fixed connection limit. Once it is reached, new connection attempts fail with SQLSTATE `53300`, which `PrismaPg` maps to Prisma error **`P2037`**, "Too many database connections opened". The failures look random because they hit whichever instance tried to connect last. ## Why it gets worse than the arithmetic - **Clients built inside the handler.** If `new PrismaClient({ adapter })` runs per invocation, a single warm instance accumulates pools, since nothing closes the previous one. - **Paused and retiring instances.** The Prisma docs note that paused functions keep their connections open by default, and instances marked for removal may hold them for an undocumented time. - **Parallel queries.** A handler that fires many queries with `Promise.all` uses several connections from its pool at once, pushing each instance towards its `max`. ## Fixes, in the order to apply them 1. **Construct the client at module scope.** Build the adapter and `PrismaClient` outside the handler so a warm instance reuses one pool across invocations. 2. **Do not `$disconnect()` per invocation.** The instance may be reused; disconnecting forces a reconnect on the next request. Disconnect only a client you created for a single job. 3. **Shrink the per-instance pool.** Pass a small `max` to `PrismaPg`; the docs advise starting small when no pooler is in front. Also set `connectionTimeoutMillis`, because the `pg` default of `0` lets a starved invocation wait without limit. 4. **Cap concurrency.** Set the platform's concurrency limit below the database's connection limit divided by the connections each instance may open, leaving headroom for migrations and other clients. 5. **Add an external pooler.** Put PgBouncer in **transaction mode** in front of PostgreSQL and give `PrismaPg` the pooled URL, so many function connections share a few server connections. Keep `datasource.url` in `prisma.config.ts` on the direct URL, because Prisma Migrate needs a direct connection. ## What not to do - Raise PostgreSQL's connection limit without more memory; each connection costs RAM on the server. - Expect `$disconnect()` at the end of every invocation to solve it; it trades exhaustion for reconnect latency and does nothing about concurrent instances. - Leave Prisma 6 URL parameters such as `connection_limit` in the connection string and assume they still cap the pool; in Prisma 7 the cap is the adapter's `max`. ## Turning the limits into numbers The Prisma docs give the relationship for the concurrency cap: keep it below the database's connection limit divided by the connections each instance may open. A worked example: - the database allows 100 connections, and you reserve 10 for migrations, administration and other services, leaving 90; - each instance's adapter has `max: 2`; - so the function's concurrency should stay at or below 45. If 45 concurrent instances cannot carry the peak, the levers are a pooler in front of the database or a larger database, not a larger `max`, because a larger `max` lowers the safe instance count by the same factor. ## Reading the evidence Confirm the diagnosis before changing settings. Compare the number of concurrent instances at the moment of failure with the database's active connection count; if connections roughly equal instances times pool size, the multiplication is the cause. If the count keeps rising while instances stay flat, look for clients constructed per invocation instead.
- Why does moving the client outside the handler not fix the spike by itself?Module scope only lets a warm instance reuse its own pool across invocations. During a spike the platform starts more instances, and each still builds one client with its own pool, so the total remains instances times `max`. You still need a small `max`, a concurrency cap or a pooler to bound that product.
- With PgBouncer in front, which URL goes where in a Prisma 7 project?`PrismaPg` gets the pooled PgBouncer URL, so runtime connections are multiplexed. `datasource.url` in `prisma.config.ts` gets the direct database URL, because Prisma Migrate's Schema Engine needs its own connection and can fail with prepared-statement errors through PgBouncer.
Picture a car park with a fixed number of spaces and tenants who each hold ten permits. On a quiet day nobody notices; at rush hour every new tenant arrives and uses all ten, and the gate closes. You can issue fewer permits per tenant, admit fewer tenants at once, or hire a valet who parks for everyone in a small reserved block.
- One PrismaClient per process means one pool for the whole deployment.
- Calling $disconnect() after every invocation fixes connection exhaustion.
- Prisma 7 shares connections between serverless instances on its own.
- P2037 means the pool's acquire timeout was set too short.
- Adding connection_limit to the URL still caps each instance's pool.
Assumes Prisma 7, where each instance's pool is a node-postgres pool configured on PrismaPg (default max 10) rather than Prisma 6's engine pool sized by connection_limit.