Skip to main content
Home/Engineering Blog/Stop Using Default Prisma Clie...
PERFORMANCE // INFRASTRUCTURE

Stop Using Default Prisma Client Settings in Serverless Environments

Your app works perfectly with 10 users and falls over at 100. It's not your code, it's the connection math. Here is exactly why Prisma exhausts Postgres on Vercel and Lambda, and the five fixes we apply, in order.

ROOT CAUSEPool × InstancesEvery function instance opens its own pool
SYMPTOMP2024 / 504sRequests queue for a free connection, then time out
HIDDEN TAXRegion LatencyEvery query pays the round trip, many times per request
THE FIXPooler + Limit 1Transaction pooling, tiny per-instance pools
HawkInspect Pro Engineering
•12 min read

You shipped your Next.js app to Vercel. Ten users: buttery smooth. Then a launch post lands, a hundred people show up at once, and your API starts throwing 504s. The database dashboard says CPU is at 12%. Nothing in your code changed. So what broke?

Almost always, the answer is connections. Not slow queries, not a missing index, not "Vercel being flaky". Prisma is a fantastic ORM, but its defaults were designed for a long-running Node.js server: one process, one connection pool, shared by every request. Serverless quietly breaks that assumption, and Postgres has a hard ceiling on how many connections it will accept.

We untangle this exact failure in rescue projects more often than any other database issue. This guide walks through why it happens (with real numbers), the error messages that give it away, and the five fixes we apply in order, from a two-minute change to the architecture decisions that let a small Postgres instance serve serious traffic.


1.The Connection Math Nobody Shows You

On a traditional server you create one PrismaClient. It opens a small pool of connections, and every request borrows one and gives it back. A hundred concurrent users might share ten connections and never notice.

Serverless works differently. When traffic rises, the platform doesn't make one function faster, it starts more copies of it. Each copy is a separate process with its own PrismaClient and its own pool. By default Prisma sizes that pool as num_physical_cpus × 2 + 1, which on a typical 2-vCPU function is 5 connections per instance.

Concurrent instancesPool per instanceConnections requestedPostgres default limit
5525100 ✓
205100100, full
605300100 ✗

Postgres ships with max_connections = 100, and a few of those are reserved for superusers. Small managed instances (a starter RDS, a free-tier Supabase project) often allow even fewer direct connections. Twenty busy function instances can fill the database completely, and twenty instances is not "viral launch" traffic. It's a decent Tuesday.

The part that surprises people

Instances don't disappear the moment a request ends. Platforms freeze idle instances and keep them around for reuse, and a frozen instance still holds its open connections. The database counts those idle "zombie" connections against your limit until they time out. That's why you can hit the ceiling while the dashboard shows almost no queries running.


2.How It Fails in Production

Connection exhaustion rarely announces itself clearly. It shows up as a cluster of errors that look unrelated until you know the pattern. If you see any of these, especially only under load, this article is about you:

  • P2024, Timed out fetching a new connection from the connection pool. Your function waited (10 seconds by default) for a free connection in its own pool and gave up.
  • FATAL: sorry, too many clients already, Postgres itself refused the connection: the global limit is reached. You may also see “remaining connection slots are reserved…”.
  • P1001 / P1017, Can't reach the database, or the server closed the connection. Often a pooler or the database dropping connections under pressure.
  • 504 Gateway Timeout, The function hit its execution limit while still queued for a connection. The user just sees a spinner, then an error.

The tell-tale sign: everything is fine in development and at low traffic, failures appear in bursts during spikes, and the database's CPU and memory look healthy the whole time. The database isn't overworked. It's just out of seats.


3.Fix #1: One Client per Instance, Not per Request

Before tuning anything, check the most common self-inflicted wound. We regularly find code like this, frequently generated by AI coding tools:

Anti-pattern
app/api/users/route.ts
export async function GET() {
  const prisma = new PrismaClient();   // brand-new pool on every request
  const users = await prisma.user.findMany();
  await prisma.$disconnect();          // ...torn down again right after
  return Response.json(users);
}

Every request pays for a fresh TCP + TLS handshake and authentication, often 20 to 100 ms before your first query even runs, and under concurrency it multiplies the connection count. Create the client once, at module scope, so warm invocations reuse it:

Fix
lib/prisma.ts
import { PrismaClient } from '@prisma/client';

// Reuse one client per instance. In development, hot reload re-runs this file,
// so keep the client on globalThis to avoid opening a new pool on every save.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

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

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

Then import prisma from this file everywhere, and don't call $disconnect() at the end of each request in a serverless function. Disconnecting throws away the warm connection the next invocation could have reused.


4.Fix #2: Size the Pool for Serverless

A serverless instance usually handles one request at a time, so a pool of five is mostly wasted seats that still count against the database. Prisma reads pool settings straight from the connection string:

Per-instance pool
.env
DATABASE_URL="postgresql://USER:PASS@HOST:5432/db?connection_limit=1&pool_timeout=20"
  • connection_limit=1 cuts each instance's footprint from five connections to one. That alone gives you roughly five times the headroom.
  • pool_timeout=20 lets a request wait a little longer for the connection instead of failing with P2024 during short bursts.
  • If your handlers fire queries in parallel with Promise.all, a limit of 1 serialises them. Raise it to 2 or 3 only where you actually need that parallelism.
Necessary, not sufficient

A smaller pool raises the ceiling but doesn't remove it: 150 concurrent instances × 1 connection is still 150 connections. Fewer seats per instance buys time. To actually decouple your traffic from the database's limit, you need the next fix.


5.Fix #3: Put a Pooler in Front of Postgres

A connection pooler sits between your functions and the database. Hundreds of short-lived function connections land on the pooler, which forwards their queries over a small, fixed set of real database connections. In transaction mode, a real connection is only borrowed for the length of a single transaction, then handed to the next caller. That's how a database with 100 seats serves thousands of concurrent functions.

SupabaseBuilt-in pooler (Supavisor). Use the pooled connection string on port 6543 (transaction mode).
NeonUse the pooled connection string: the hostname contains -pooler.
AWS RDS / AuroraRDS Proxy, or self-hosted PgBouncer in transaction mode.
Prisma AccelerateManaged pooling plus an optional global query cache, configured from Prisma itself.

Transaction pooling has one catch: features that depend on a long-lived session don't survive it. For Prisma that means two settings. Add pgbouncer=true to the pooled URL (it stops Prisma relying on cached prepared statements, which a transaction pooler can't guarantee; newer PgBouncer versions can be configured to support them, but the flag is the safe default). And give migrations a direct connection, because prisma migrate needs session features the pooler won't provide.

Runtime vs migrations
.env
# App runtime: through the pooler, tiny per-instance pool
DATABASE_URL="postgresql://USER:PASS@POOLER_HOST:6543/postgres?pgbouncer=true&connection_limit=1&pool_timeout=20"

# Migrations only: straight to the database
DIRECT_URL="postgresql://USER:PASS@DB_HOST:5432/postgres"
prisma/schema.prisma
datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")   // used by prisma migrate, not by your app
}

On the newest Prisma versions the datasource URLs can live in prisma.config.ts instead of the schema. The principle is identical: the app talks to the pooler, migrations talk to the database directly.

Hosting on Vercel?

Vercel's Fluid compute lets one function instance serve several requests concurrently, which means fewer instances and fewer connections for the same traffic. It doesn't make a pooler unnecessary, but it changes the math in your favour. Their @vercel/functions package also includes a helper (attachDatabasePool) that closes idle pool connections before an instance is suspended, which tackles the zombie-connection problem from section 1.


6.Fix #4: Cold Starts and the Region Tax

Connections are the outage. Latency is the slow bleed. Two things dominate it in serverless Prisma apps.

The engine on cold start

Historically, Prisma shipped a native Rust query engine with your function. Loading it on a cold start adds weight to every new instance. Recent Prisma versions (6.16 and later, and the default in Prisma 7) can run without it: queries are compiled in TypeScript and sent through a driver adapter using a standard database driver. The result is a smaller bundle, faster cold starts, and support for edge runtimes.

Driver adapter
lib/prisma.ts
import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });

export const prisma = new PrismaClient({ adapter });

The exact generator settings differ between Prisma versions, so follow the upgrade guide for yours. On Neon, @prisma/adapter-neon can query over HTTP and WebSockets, which avoids long-lived TCP connections from the function entirely.

The region tax (the one almost everyone misses)

Every Prisma query is a network round trip. If your functions run in one region and your database in another, every round trip pays that distance. Vercel functions default to Washington, D.C. (iad1); if your database lives in Singapore or Frankfurt, each query costs on the order of 100 to 250 ms of pure travel time.

Do the multiplication

A dashboard page that makes 20 queries, each paying 150 ms of cross-region latency, spends 3 seconds just waiting on the network. No index or query rewrite will fix that. Moving the function region next to the database (one line in your project settings or vercel.json) often makes an app feel several times faster overnight.


7.Fix #5: Stop Wasting Round Trips and Connection Time

Once the plumbing is right, the remaining gains come from how the code talks to the database. Two patterns cause most of the damage.

The N+1 loop

51 round trips
orders.ts
const orders = await prisma.order.findMany({ take: 50 });

for (const order of orders) {
  // one extra query per order: 50 more round trips
  order.customer = await prisma.customer.findUnique({
    where: { id: order.customerId },
  });
}
1–2 round trips
orders.ts
const orders = await prisma.order.findMany({
  take: 50,
  select: {
    id: true,
    total: true,
    customer: { select: { name: true, email: true } },  // fetched with the orders
  },
});

Use select rather than pulling whole rows with include: less data over the wire and less work to serialise. On recent versions with PostgreSQL, relationLoadStrategy: 'join' can fetch the relation in a single database query instead of two.

Holding a connection hostage

Pool starvation
checkout.ts
await prisma.$transaction(async (tx) => {
  const order = await tx.order.create({ data });
  await stripe.paymentIntents.create({ ... });   // 1–3 s external call
  await sendConfirmationEmail(order);            // another network call
  await tx.order.update({ ... });
});

An interactive transaction holds a database connection for its entire duration, through a pooler too. Put slow external calls inside one and every checkout pins a connection for seconds. Under load the pool drains and everything else queues behind it. Keep transactions to database work only: do the Stripe call and the email outside, and use short transactions (or a single batched $transaction([...])) for the writes.


8.Diagnose Your Own App in 10 Minutes

You don't need to guess. Run these against your database (with a direct connection, not through the pooler) while the app is under normal load:

Read-only
diagnose.sql
-- 1. What's the ceiling?
SHOW max_connections;

-- 2. How many seats are taken, and by what?
SELECT state, count(*)
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state
ORDER BY count(*) DESC;

-- 3. Who has been sitting idle the longest? (zombie candidates)
SELECT client_addr, application_name, state,
       now() - state_change AS idle_for
FROM pg_stat_activity
WHERE datname = current_database() AND state = 'idle'
ORDER BY idle_for DESC
LIMIT 20;
  • If idle connections make up most of your total and are close to max_connections, you have the serverless pool problem. Fixes #1 to #3 are for you.
  • Many connections stuck in idle in transaction point to long transactions holding seats, which is fix #5.
  • Few connections but slow pages? Turn on query logging with new PrismaClient({ log: ['query'] }) for a single request and count the queries. Then check your function region. That's fix #4.

9.The Production Checklist

Serverless scaling isn't magic, it's arithmetic. Get these right and a modest Postgres instance will comfortably handle traffic that would otherwise take it down:

  • One PrismaClient per instance, created at module scope (with the globalThis guard for development).
  • No new PrismaClient() or $disconnect() inside request handlers.
  • Runtime traffic goes through a pooler in transaction mode, with pgbouncer=true.
  • connection_limit=1 (or a small number you've measured) and a sensible pool_timeout.
  • Migrations use a separate direct URL.
  • Functions deployed in the same region as the database.
  • Driver adapters / the Rust-free client on recent Prisma, for lighter cold starts.
  • No N+1 loops; select only the fields you need.
  • No external API calls inside interactive transactions.
  • A quick look at pg_stat_activity after every launch spike.

If your app was built quickly, especially with AI tools, there's a good chance several of these are missing, and they compound. The good news: none of them require a rewrite. Most are configuration and a few targeted code changes, and the difference under load is night and day.

Note on Organization Security:We never require full GitHub/GitLab organization admin access. A read-only invite to the specific repository and branch being audited is all that is required, keeping your broader infrastructure completely isolated.

Not sure which methodology fits your application?

We'll analyze your stack, endpoints, and repo requirements in a quick 10-minute triage.