SuperAPI AI 工具集

prisma-connection-pool-exhaustion

部署与运维

查看项目

更新于 10-16 09:29

技能介绍

用途:该技能用于修复 Serverless 环境(Vercel、AWS Lambda、Netlify Functions 等)中 Prisma 报出的「Too many connections」与连接池耗尽错误。触发条件包括:出现 P2024: Timed out fetching a new connection from the connection pool;PostgreSQL 报 FATAL: too many connections for role;MySQL 报 Too many connections;本地 npm run dev 正常但生产出错;错误在流量高峰出现后自行恢复;数据库面板连接数接近上限。

主要能力:

  1. 使用连接池服务。推荐在 Serverless 函数与数据库之间加 PgBouncer 或 Prisma Accelerate。Supabase 改用池化连接串(端口 6543 而非 5432):DATABASE_URL="postgresql://user:pass@db.xxx.supabase.co:6543/postgres?pgbouncer=true";Neon 自带池化;Prisma Accelerate 用 npx prisma generate --accelerate。
  2. 配置 Prisma 连接限制,如 datasource 中 relationMode = "prisma",或在 PrismaClient 的 datasources 中拼接 ?connection_limit=1。
  3. 开发环境单例模式,避免热重载反复创建客户端。
  4. URL 参数:?connection_limit=1&pool_timeout=20&connect_timeout=10,分别限制每实例连接数、等待可用连接时长、连接失败超时。

验证方式:部署后用 npx autocannon -c 100 -d 30 https://your-app.com/api/test 做负载测试,观察数据库面板连接数是否在限额内、日志中是否仍有 P2024。

限制与注意事项:不同托管数据库的池化方案不同,需查各自文档;PlanetScale(MySQL)架构不同,不存在该问题;connection_limit=1 较激进,若延迟升高可上调;单例模式仅对开发有效,生产 Serverless 每个实例相互隔离;使用 Next.js API 路由时每次调用可能都是独立函数。更多信息见 https://www.prisma.io/accelerate。