1. A new connection pool per serverless invocation
Symptom
Fine in development. In production the database hits max_connections under moderate traffic and everything stalls.
The pattern
// lib/db.ts
import { PrismaClient } from "@prisma/client";
export const db = new PrismaClient(); // new pool on every cold startWhy it bites
Each serverless instance constructs its own client, and each client opens its own pool. Fifty concurrent instances at a default pool size of ten is five hundred connections against a Postgres box configured for a hundred. The failure is a connection error, not a slow query, so it gets misdiagnosed as a database outage.
The fix
// Reuse across hot invocations, and put a real pooler in front.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const db =
globalForPrisma.prisma ??
new PrismaClient({ datasourceUrl: process.env.DATABASE_URL });
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db;
// DATABASE_URL should point at PgBouncer / Prisma Accelerate in transaction
// mode, with ?connection_limit=1 per instance.