Prisma Connection Management & Pooling
Optimizing PostgreSQL connection pools, configuring PgBouncer, preventing connection leaks in serverless functions, and Prisma Accelerate.
Prisma Connection Management & Pooling
Managing database connection limits is critical for stability in high-traffic and serverless environments.
1. Connection Pool Sizing Formula
Every instance of PrismaClient creates an internal connection pool:
Default pool size = (num_physical_cpus * 2) + 1You can explicitly configure the connection pool limit in your connection URL:
DATABASE_URL="postgresql://user:pass@localhost:5432/mydb?connection_limit=10&pool_timeout=15"connection_limit: Maximum number of concurrent connections this process will open.pool_timeout: Number of seconds to wait for a free connection before throwing an error.
2. Serverless Environments & PgBouncer
In serverless platforms (Vercel, AWS Lambda), hundreds of function instances can spin up simultaneously, easily exceeding PostgreSQL's connection limit (default 100).
When using PgBouncer (or Supabase/Neon connection poolers):
- Set
?pgbouncer=trueinDATABASE_URL(Disables prepared statements). - Set
connection_limit=1for serverless lambdas. - Use a separate
DIRECT_URLforprisma migrate(PgBouncer in transaction mode does not support advisory locks used by migrations).
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}3. Disconnecting Prisma in Short-Lived Scripts
In CLI scripts, cron jobs, and background workers, always call $disconnect():
try {
await runMaintenanceJob();
} finally {
await prisma.$disconnect();
}Related Topics
Production Migration Workflow
Deploying database migrations in CI/CD pipelines, Docker containers, Kubernetes jobs, and zero-downtime database release strategies.
Prisma Common Errors & Troubleshooting
Diagnose and fix the most common Prisma error codes: P2002 (Unique constraint), P2025 (Record not found), P1001 (Unreachable database), and P2003 (Foreign key constraint).