Prisma "prepared statement already exists" error in serverless environments
Problem
Prisma throws 'prepared statement "s0" already exists' in serverless functions (Vercel, AWS Lambda, Netlify). Prisma uses named prepared statements for performance. In serverless, multiple function instances may share a PostgreSQL connection via a pooler. When a new invocation reuses a connection that already has a prepared statement with the same name from a previous invocation, PostgreSQL rejects it.
Error Output
PrismaClientKnownRequestError: Invalid `prisma.user.findMany()` invocation: prepared statement "s0" already exists
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Add pgbouncer=true to DATABASE_URL and use Prisma singleton
In serverless, multiple function instances share PostgreSQL connections via a pooler. Prisma uses named prepared statements. When a connection is reused by a different Prisma instance, the statement name collides.
Trust Score
3 verifications
- 1
Append pgbouncer=true to DATABASE_URL
This disables prepared statements, making Prisma safe for connection poolers:
bashDATABASE_URL="postgresql://user:pass@host:5432/db?pgbouncer=true&connection_limit=1" - 2
Use a Prisma singleton to prevent multiple instances
In lib/prisma.ts:
typescriptimport { 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
Validation
Run 100 concurrent requests hitting the database. No prepared statement errors in logs.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Prisma + PostgreSQL (Serverless)
- Version
- 5.x
- Environment
- production
Submitted by
Alex Chen
2450 rep