Fix Prisma Error 42P05: prepared statement "s0" already exists on Supabase

Resolve Postgres error 42P05 (prepared statement s0 already exists) and 26000 in Prisma on Supabase Supavisor, Neon, and PgBouncer transaction poolers.

Checked 5 Dec 2026·Published 5 Dec 2026·6 min read·Raw .md
In brief
  • Postgres error 42P05 fires when Prisma uses named prepared statements over a transaction-mode connection pooler (port 6543 on Supabase or -pooler on Neon) without ?pgbouncer=true.
  • Append ?pgbouncer=true&connection_limit=1 to your runtime DATABASE_URL and point migrations to a non-pooled DIRECT_URL (port 5432).
  • Never run Prisma migrations through port 6543 transaction mode, or schema locks and advisory locks will hang or fail mid-deploy.

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:

  1. Lambda/Worker A opens client connection #1, runs SELECT ... WHERE id = $1, and Prisma registers PREPARE s0 on Postgres backend PID 4102. Once the query finishes, Supavisor returns PID 4102 to the shared pool without clearing session-scoped prepared statements.
  2. 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 with 42P05: prepared statement "s0" already exists.
  3. Conversely, when Lambda/Worker A runs EXECUTE s0 a second time and Supavisor routes it onto PID 4199 (which has never seen s0), Postgres throws 26000: 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
  1. Confirm all 25 responses return 200 with zero 500 spikes in your function logs.
  2. Run npx prisma migrate status in CI to confirm DIRECT_URL connects cleanly over port 5432 for advisory locks.
  3. While auditing your Supabase setup, check that your queries select explicit columns instead of select: undefined wide rows to avoid uncached 250 GB egress overages.

Model your own stack numbersCompare Supabase Pro compute instance tiers vs Neon and Firebase bills

Open Calculator →

Common edge cases

Why does Prisma 42P05 only happen under concurrent traffic and never on localhost?

Local Postgres gives your Prisma client a dedicated TCP session where prepared statement s0 is created once. On a transaction pooler like Supavisor (port 6543), multiple serverless instances share backend Postgres connections across transactions, colliding on statement name s0.

Does adding ?pgbouncer=true noticeably slow down Prisma queries?

For typical OLTP web queries, latency overhead is under 0.5 to 1.5 ms per round-trip because Prisma switches to unnamed protocol statements within the same single network trip rather than issuing separate PREPARE calls.

Why do I also see error 26000 (prepared statement s0 does not exist) alongside 42P05?

Both stem from the exact same root cause: Instance A prepares s0 on backend Postgres connection #4, and on the next query the transaction pooler hands Instance A backend connection #9 (where s0 was never prepared), returning 26000.

What changed1
  • 2026-12-05: Published atomic runbook for Prisma 42P05 and 26000 errors on Supavisor, PgBouncer, and Neon transaction poolers.
Sources checked2

Spotted a provider quota or SDK change since 5 Dec 2026? Send a verification note →

Related troubleshooting runbooks