Deploying a Next.js API route, Cloudflare Worker, or AWS Lambda function backed by Prisma and Supabase often works smoothly during single-user staging tests, then throws intermittent 500 Internal Server Error crashes the moment two users click at the same time. In your logs, Prisma prints PostgresError { code: "42P05", message: "prepared statement \"s0\" already exists" }, frequently paired minutes later with code: "26000" (prepared statement "s1" does not exist).
Both errors have one deterministic cause and take less than five minutes to eliminate permanently.
Why transaction poolers break Prisma named prepared statements
Prisma's query engine prepares numbered SQL statements (s0, s1, s2) per session, assuming it owns the underlying Postgres backend process, while transaction poolers (Supavisor :6543, PgBouncer, Neon -pooler) rotate backend Postgres processes between every transaction.
Look at the exact stack trace emitted by Prisma Client under concurrent serverless load:
PrismaClientKnownRequestError:
Invalid `prisma.user.findUnique()` invocation:
Error occurred during query execution:
ConnectorError(ConnectorError {
user_facing_error: None,
kind: QueryError(PostgresError {
code: "42P05",
message: "prepared statement \"s0\" already exists",
severity: "ERROR",
detail: None,
column: None,
hint: None
}),
transient: false
})
Here is the exact sequence happening across your pooler on port 6543:
- Lambda/Worker A opens client connection #1, runs
SELECT ... WHERE id = $1, and Prisma registersPREPARE s0on Postgres backend PID 4102. Once the query finishes, Supavisor returns PID 4102 to the shared pool without clearing session-scoped prepared statements. - Lambda/Worker B boots cold 50 ms later, thinks it has a fresh session, and sends
PREPARE s0, which Supavisor routes onto PID 4102. Postgres rejects the duplicate name with42P05: prepared statement "s0" already exists. - Conversely, when Lambda/Worker A runs
EXECUTE s0a second time and Supavisor routes it onto PID 4199 (which has never seens0), Postgres throws26000: prepared statement "s0" does not exist.
| Connection Endpoint | Port / Host Suffix | Pooler Mode | Supports Named Prepared Statements? | Use For |
|---|---|---|---|---|
| Supabase Transaction Pooler | :6543 (pooler.supabase.com) |
Transaction | No - requires ?pgbouncer=true |
Vercel, Workers, Lambda runtime queries |
| Supabase Session Pooler | :5432 (pooler.supabase.com) |
Session | Yes - capped by compute tier | IPv4 prisma migrate deploy & CLI tasks |
| Neon Pooled Endpoint | -pooler.<region>.aws.neon.tech |
Transaction (PgBouncer) | Requires ?pgbouncer=true (unless protocol cache configured) |
Serverless runtime queries |
| Neon Direct Endpoint | <ep>.<region>.aws.neon.tech |
Direct Postgres | Yes | Schema migrations & pg_dump |
The exact DATABASE_URL and DIRECT_URL fix for Prisma
Add ?pgbouncer=true&connection_limit=1 to your pooled runtime DATABASE_URL (port 6543) so Prisma switches to unnamed statements, and configure a separate DIRECT_URL on port 5432 for prisma migrate deploy.
First, update your environment variables in .env and your production secret manager (Vercel, Cloudflare Workers, Railway, or GitHub Actions):
# Runtime traffic: Transaction mode (port 6543) + pgbouncer=true + 1 connection per serverless isolate
DATABASE_URL="postgresql://postgres.abcdefghijkl:YOUR_PASSWORD@aws-0-us-east-1.pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1&pool_timeout=15"
# Migrations & introspection ONLY: Session mode / Direct port 5432 (NO pgbouncer=true)
DIRECT_URL="postgresql://postgres.abcdefghijkl:YOUR_PASSWORD@aws-0-us-east-1.pooler.supabase.com:5432/postgres"
Watch the URL separator carefully: if your DATABASE_URL already contains ?sslmode=require, append &pgbouncer=true&connection_limit=1 with an ampersand (&), never a second question mark (?).
Next, wire both URLs cleanly in schema.prisma (or prisma.config.ts if using the newer driver-adapter config):
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
generator client {
provider = "prisma-client-js"
}
And instantiate a singleton PrismaClient so Next.js hot reloads or warm serverless containers never leak extra sockets (if you hit MaxClientsInSessionMode alongside 42P05, see our Supabase connection pool exhaustion runbook):
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["warn", "error"] : ["error"],
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
Why setting connection_limit=1 saves compute upgrade bills on Supabase
By default, Prisma sets its internal connection pool size to num_cpus * 2 + 1 (often 5 to 9 connections per serverless container), which rapidly saturates Supabase Micro/Small pooler slots and forces premature compute instance upgrades.
On Supabase Pro ($25/mo base, which includes $10 covering a Micro 1 GB RAM instance), backend Postgres connections are finite (60 direct connections, 200 pooler client slots on Micro). If 35 concurrent Vercel functions each open 5 Prisma connections (175 slots) and accidentally hit port 5432 instead of 6543, your app crashes, pushing teams to upgrade to Medium ($60/mo compute = +$50/mo extra) when connection_limit=1 on port 6543 handles the exact same traffic on Micro or Small ($15/mo compute = +$5/mo net). Model compute instance step-ups in our Supabase vs Firebase vs Neon Cost Calculator.
Edge runtimes, driver adapters (@prisma/adapter-pg), and interactive $transaction traps
When running Prisma on Cloudflare Workers or Vercel Edge with @prisma/adapter-pg, pass your ?pgbouncer=true pooled string into a per-request pg.Pool({ max: 1 }) instance, and cap interactive prisma.$transaction timeouts below 5 seconds so transaction poolers never hold scarce backend slots open across slow external HTTP calls.
Standard Node.js servers keep a warm singleton PrismaClient, whereas V8 isolates on Cloudflare Workers disallow sharing open TCP sockets across separate incoming requests. Creating a Pool at global module scope on Workers causes intermittent Cannot perform I/O on behalf of a different request failures right alongside 42P05 collisions when pg attempts to cache named statements. Instantiate a max: 1 pool inside the request handler (or pair it with Cloudflare Hyperdrive) and disable statement caching:
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";
export async function withWorkerPrisma<T>(
connectionString: string,
fn: (db: PrismaClient) => Promise<T>
): Promise<T> {
const pool = new Pool({
connectionString, // Must include ?pgbouncer=true on port 6543
max: 1,
idleTimeoutMillis: 5_000,
connectionTimeoutMillis: 5_000,
});
const adapter = new PrismaPg(pool);
const db = new PrismaClient({ adapter });
try {
return await fn(db);
} finally {
await pool.end();
}
}
Also audit every interactive await prisma.$transaction(async (tx) => { ... }) block when running behind port 6543. Because transaction mode pins a real Postgres backend process from BEGIN until COMMIT or ROLLBACK, calling a slow third-party webhook, Stripe checkout API, or LLM completion inside the $transaction callback locks that backend Postgres process for several seconds. Move all external fetch() calls outside the database transaction boundary and pass explicit { maxWait: 3000, timeout: 5000 } options so stalled queries fail fast instead of starving sibling workers.
Verification test: Confirming zero 42P05 errors under parallel bursts
Fire 30 parallel queries across separate processes or concurrent HTTP requests against your staging route and verify pg_prepared_statements stays empty on backend workers.
Run a quick concurrency smoke test from your terminal against your deployed API endpoint:
# Fire 25 parallel requests to verify zero 42P05 / 26000 collisions
seq 1 25 | xargs -n1 -P25 -I{} curl -s -o /dev/null -w "%{http_code}\n" https://your-app.example.com/api/health-db | sort | uniq -c
- Confirm all 25 responses return
200with zero500spikes in your function logs. - Run
npx prisma migrate statusin CI to confirmDIRECT_URLconnects cleanly over port5432for advisory locks. - While auditing your Supabase setup, check that your queries select explicit columns instead of
select: undefinedwide rows to avoid uncached 250 GB egress overages.