All articles
PrismaNext.jsPostgreSQLServerless

Fixing Prisma Too Many Connections Errors in Next.js and Serverless

Why Prisma on Vercel exhausts Postgres connections (too many clients, P2024, P1001) and how a singleton, connection_limit and a pooler fix it.

Tushar Pachouri11 min read

Prisma and PostgreSQL work great on a laptop, then fall over once the app is deployed to Vercel or another serverless platform. The database starts refusing connections, requests hang until Prisma times out, and in development your terminal fills with warnings about too many Prisma Client instances. This post explains where all those connections come from and walks through the fixes in the order I would apply them.

TL;DR

  • Every PrismaClient has its own connection pool. Its default size is based on the number of physical CPUs (num_physical_cpus * 2 + 1), not on what your database can handle.
  • Serverless platforms run many function instances at once, and each one has its own client and pool. Multiply them together and you pass Postgres's max_connections quickly.
  • In development, Next.js hot reload re-runs your modules and creates a new client on every change unless you cache it on globalThis.
  • Fixes: one shared client per process, connection_limit=1 (or a small number) in serverless, and a connection pooler such as PgBouncer, Supabase's pooler or Neon's pooled endpoint, with directUrl set for migrations.
  • Never create PrismaClient inside a request handler, and only call $disconnect() in scripts and jobs.

The errors you will see

These usually show up together, and they all point to the same root cause.

From PostgreSQL itself, when it has no connection slots left:

Text
FATAL: sorry, too many clients already
FATAL: remaining connection slots are reserved for non-replication superuser connections

The second message means the regular slots are gone and the few left over are held back for admins. The exact wording differs between Postgres versions, but the meaning is the same.

From Prisma, when a query waits too long for a free connection in its own pool:

Text
PrismaClientKnownRequestError: Timed out fetching a new connection from the connection pool.
(Current connection pool timeout: 10, connection limit: 5)
code: 'P2024'

From Prisma, when it cannot open a connection to the server at all:

Text
PrismaClientInitializationError: Can't reach database server at `db.example.com:5432`
code: 'P1001'

P1001 has other causes as well (wrong host, firewall rules, a serverless database still waking up), but when it appears under load next to the errors above, connection exhaustion is the likely cause.

And in local development, after you have saved files a few times:

Text
warn(prisma-client) There are already 10 instances of Prisma Client actively running.

Why serverless runs out of connections

Each PrismaClient has its own pool

When you call new PrismaClient(), Prisma sets up a connection pool for that instance. By default its size is:

Text
connection_limit = num_physical_cpus * 2 + 1

On a long-running Node server that is fine. You create one client at startup, it opens up to a handful of connections, and every request shares them.

Serverless multiplies the pools

On Vercel, AWS Lambda and similar platforms, your API routes and server components run in function instances that the platform creates and destroys as traffic changes. Each instance is its own process, so each one loads its own copy of lib/prisma.ts, creates its own PrismaClient and gets its own pool.

The math gets ugly quickly. As an illustration: if a traffic spike scales you to 40 concurrent instances and each pool may open 5 connections, that is up to 200 connections. PostgreSQL's default max_connections is 100, and managed plans often allow fewer. Warm instances also keep their idle connections open until the platform shuts them down, so the count stays high even after the spike.

Every function instance opens its own pool, and the pools add up against one database.

Dev hot reload creates new clients

In next dev, editing a file causes Next.js to re-run the affected modules. If lib/prisma.ts says export const prisma = new PrismaClient(), each reload creates a new client and the old ones are not closed. After enough saves you hit the warning above, and eventually the database limit too, even though you are the only user.

Fix 1: one PrismaClient per process

This is the standard lib/prisma.ts for Next.js. Copy it as is:

TypeScript
// lib/prisma.ts
import { PrismaClient } from "@prisma/client";

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}

How it works:

  • globalThis survives hot reloads in development, while module-level variables do not. The first load creates the client and stores it there. Later reloads find it and reuse it.
  • In production the code is not reloaded, so the module-level prisma is already a single instance per process. Warm serverless invocations reuse it automatically.

Then import it everywhere instead of creating clients:

TypeScript
// app/api/users/route.ts
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  const users = await prisma.user.findMany({ take: 20 });
  return NextResponse.json(users);
}

Never create a client in a handler

This is the version that causes trouble. It looks harmless, but every request creates a brand-new pool:

TypeScript
// app/api/users/route.ts (broken)
import { NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";

export async function GET() {
  const prisma = new PrismaClient(); // new pool on every request
  const users = await prisma.user.findMany({ take: 20 });
  return NextResponse.json(users);
}

Under load this opens connections much faster than they are closed. The same applies to server actions, getServerSideProps, tRPC context factories and middleware. Search the codebase for new PrismaClient( and make sure the only hit is lib/prisma.ts.

Tip: If you use a Prisma Client extension (prisma.$extends(...)), extend the client inside lib/prisma.ts and export the extended client. Do not call $extends per request.

Fix 2: limit the pool size in serverless

A single function instance usually handles one request at a time, so it rarely needs more than one or two connections. Set the limit in the connection string:

Diff
- DATABASE_URL="postgresql://USER:PASSWORD@HOST:5432/mydb"
+ DATABASE_URL="postgresql://USER:PASSWORD@HOST:5432/mydb?connection_limit=1"

Now the worst case is roughly one connection per running instance, not five or more.

Tune pool_timeout

pool_timeout is how many seconds a query waits for a free connection in Prisma's pool before throwing P2024. The default is 10. With a small pool, a slow query or a page that fires several queries in parallel with Promise.all can queue the rest. You can give them more time:

Terminal
DATABASE_URL="postgresql://USER:PASSWORD@HOST:5432/mydb?connection_limit=1&pool_timeout=20"

Warning: Raising pool_timeout hides the symptom, not the cause. If you see P2024 with connection_limit=1, check for long transactions, N+1 query loops, or a platform that runs several requests at once inside one instance. In that last case, raise connection_limit to a small number like 3 to 5, and put a pooler in front of the database.

Setting pool_timeout=0 turns off the timeout completely, so queries wait for as long as it takes. That is rarely what you want in a request path.

Fix 3: put a connection pooler in front of Postgres

Limiting each instance helps, but it does not cap how many instances exist. A connection pooler does. Your functions connect to the pooler, which keeps a fixed, small set of real Postgres connections and shares them between clients, usually per transaction.

WITHOUT A POOLER WITH A POOLER λ 1λ 2λ 3λ 4λ 5 Postgres 15 conns λ 1λ 2λ 3λ 4λ 5 pooler Postgres 3 conns
Without a pooler every instance holds its own connections; with one, they share a small fixed set.

Common options:

OptionPooled connectionDirect connection
Self-hosted PgBouncerPgBouncer host and portPostgres host, usually port 5432
SupabasePooler host, transaction mode port (6543)Direct or session mode string (5432)
NeonHostname with -pooler in itHostname without -pooler

Check your provider's dashboard for the exact strings. They usually show both.

The pgbouncer flag

PgBouncer in transaction mode does not keep a session open between transactions, and older PgBouncer versions do not support the prepared statements Prisma creates. Adding pgbouncer=true tells Prisma to work in a pooler-compatible mode:

Terminal
DATABASE_URL="postgresql://USER:PASSWORD@POOLER_HOST:6543/mydb?pgbouncer=true&connection_limit=1"

Note: Some hosted poolers now support prepared statements in transaction mode, and their docs may say the flag is optional. If you are not sure, follow your provider's Prisma guide. Without it on an older pooler you typically get errors like prepared statement "s0" already exists.

Use directUrl for migrations

Migrations should not go through a transaction-mode pooler. prisma migrate needs a stable session for things like advisory locks. Prisma supports a second URL just for the CLI:

Prisma
datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}
Terminal
# .env
# Pooled: used by the app at runtime
DATABASE_URL="postgresql://USER:PASSWORD@POOLER_HOST:6543/mydb?pgbouncer=true&connection_limit=1"

# Direct: used by prisma migrate, db push and introspection
DIRECT_URL="postgresql://USER:PASSWORD@DB_HOST:5432/mydb"

Your app keeps using DATABASE_URL through the pooler, and commands like prisma migrate deploy use DIRECT_URL. Add both variables to your Vercel project settings, not only to your local .env.

Note: Newer Prisma major versions are moving connection settings out of schema.prisma and into a prisma.config.ts file. The idea stays the same, a pooled URL for the app and a direct URL for migrations, but check the docs for the version you are on.

Alternatives: Accelerate and driver adapters

There are two more options worth knowing about. Check the current docs before choosing either one, because both have changed a lot between Prisma releases.

  • Prisma Accelerate is Prisma's hosted connection pool (with optional query caching). Your app connects to Accelerate over HTTP with a special connection string and the @prisma/extension-accelerate extension, and Accelerate manages the real database connections. It is useful when you cannot run or configure a pooler yourself.
  • Driver adapters let Prisma use a JavaScript database driver instead of its built-in connection handling, for example @prisma/adapter-pg with node-postgres, or @prisma/adapter-neon with Neon's serverless driver. With an adapter, pooling is handled by that driver's pool, so you configure limits there. Depending on your Prisma version, adapters may need a preview feature flag.

Neither one removes the need for the singleton in Fix 1.

Scripts vs serverless handlers: when to disconnect

prisma.$disconnect() closes the pool. Whether you should call it depends on how long the process lives.

In a script, seed file or cron job, disconnect when you are done so the process can exit and does not leave connections open:

TypeScript
// prisma/seed.ts
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  await prisma.user.upsert({
    where: { email: "admin@example.com" },
    update: {},
    create: { email: "admin@example.com", name: "Admin" },
  });
}

main()
  .catch((error) => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

In a serverless handler, do not disconnect at the end of each request. The next invocation on the same warm instance would have to reconnect from scratch, which adds latency and causes connection churn, the opposite of what you want. Let the platform close the connections when it shuts the instance down.

TypeScript
// Don't do this in a route handler
export async function GET() {
  const users = await prisma.user.findMany();
  await prisma.$disconnect(); // forces a reconnect on the next request
  return Response.json(users);
}

Check what is actually connected

Before and after each fix, look at the database itself instead of guessing. Connect with psql or your provider's SQL editor.

How many connections exist, grouped by state:

SQL
SELECT count(*), state
FROM pg_stat_activity
GROUP BY state;

The server's limit:

SQL
SHOW max_connections;

Who is holding the connections:

SQL
SELECT usename, application_name, client_addr, state, count(*)
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY usename, application_name, client_addr, state
ORDER BY count(*) DESC;

A large number of idle connections from your app's database user, close to max_connections, is the classic serverless pattern: lots of warm instances each holding a pool open and doing nothing. After adding a pooler, you should see a small, steady set of connections from the pooler instead.

Warning: You can close connections with pg_terminate_backend(pid), but that only buys time and can kill queries that are still running. Fix the source first.

Checklist

Work through this list when Prisma starts running out of connections:

  1. new PrismaClient( appears in exactly one file, lib/prisma.ts, and that file uses the globalThis guard.
  2. No route handler, server action, middleware or context factory creates its own client or calls $extends per request.
  3. The runtime DATABASE_URL includes connection_limit=1 (or a small number if your instances handle concurrent requests).
  4. The runtime URL points at a pooler (PgBouncer, Supabase pooler, Neon -pooler host, or Accelerate), not straight at Postgres.
  5. pgbouncer=true is set if your pooler runs in transaction mode and your provider's Prisma guide calls for it.
  6. directUrl is set in schema.prisma, and DIRECT_URL exists in every environment that runs migrations.
  7. pool_timeout is reasonable, and any remaining P2024 errors have been traced to slow queries or long transactions.
  8. Scripts and seeds call $disconnect() in a finally, and serverless handlers do not.
  9. You have checked pg_stat_activity against SHOW max_connections; under realistic load.

Once the client is a singleton and a pooler sits between your functions and Postgres, connection count stops scaling with traffic, and these errors usually stop for good.

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch