Skill站外收录 @skilllib/skill-2014279376144117762
prisma-connection-pool-exhaustion
解决 Serverless 环境下 Prisma 数据库连接耗尽问题,通过连接池服务(如 PgBouncer 或 Prisma Accelerate)、限制单实例连接数、优化连接参数及复用客户端实例,确保高并发时数据库连接稳定可控。
数据库 AI 技能
Skills.MD
# Prisma Connection Pool Exhaustion in Serverless
## Problem
Serverless functions create a new Prisma client instance on each cold start. Each
instance opens multiple database connections (default: 5 per instance). With many
concurrent requests, this quickly exhausts the database's connection limit (often
20-100 for managed databases).
## Context / Trigger Conditions
This skill applies when you see:
- `P2024: Timed out fetching a new connection from the connection pool`
- PostgreSQL: `FATAL: too many connections for role "username"`
- MySQL: `Too many connections`
- Works fine locally with `npm run dev` but fails in production
- Errors appear during traffic spikes, then resolve
- Database dashboard shows connections at or near limit
Environment indicators:
- Deploying to Vercel, AWS Lambda, Netlify Functions, or similar
- Using Prisma with PostgreSQL, MySQL, or another connection-based database
- Database is managed (PlanetScale, Supabase, Neon, RDS, etc.)
## Solution
### Step 1: Use Connection Pooling Service
The recommended solution is to use a connection pooler like PgBouncer or Prisma
Accelerate, which sits between your serverless functions and the database.
**For Supabase:**
```
# .env
# Use the pooled connection string (port 6543, not 5432)
DATABASE_URL="postgresql://user:pass@db.xxx.supabase.co:6543/postgres?pgbouncer=true"
```
**For Neon:**
```
# .env
DATABASE_URL="postgresql://user:pass@ep-xxx.us-east-2.aws.neon.tech/dbname?sslmode=require"
# Neon has built-in pooling
```
**For Prisma Accelerate:**
```bash
npx prisma generate --accelerate
```
### Step 2: Configure Prisma Connection Limits
In your `schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
// Limit connections per Prisma instance
relationMode = "prisma"
}
```
In your connection URL or Prisma client:
```typescript
// lib/prisma.ts
import { PrismaClient } from '@prisma/client'
const globalForPrisma = global as unknown as { prisma: PrismaClient }
export const prisma = globalForPrisma.prisma || new PrismaClient({
datasources: {
db: {
url: process.env.DATABASE_URL + '?connection_limit=1'
}
}
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
```
### Step 3: Singleton Pattern (Development)
Prevent hot-reload from creating new clients:
```typescript
// lib/prisma.ts
import { 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
```
### Step 4: URL Parameters
Add these to your connection string:
```
?connection_limit=1&pool_timeout=20&connect_timeout=10
```
- `connection_limit=1`: One connection per serverless instance
- `pool_timeout=20`: Wait up to 20s for available connection
- `connect_timeout=10`: Fail fast if can't connect in 10s
## Verification
After applying fixes:
1. Deploy to production
2. Run a load test: `npx autocannon -c 100 -d 30 https://your-app.com/api/test`
3. Check database dashboard—connections should stay within limits
4. No more P2024 errors in logs
## Example
**Before** (error under load):
```
[ERROR] PrismaClientKnownRequestError:
Invalid `prisma.user.findMany()` invocation:
Timed out fetching a new connection from the connection pool.
```
**After** (with connection pooling):
```
# Using Supabase pooler URL
DATABASE_URL="postgresql://...@db.xxx.supabase.co:6543/postgres?pgbouncer=true&connection_limit=1"
```
Database connections stable at 10-15 even under heavy load.
## Notes
- Different managed databases have different pooling solutions—check your provider's docs
- PlanetScale (MySQL) uses a different architecture and doesn't have this issue
- `connection_limit=1` is aggressive; start there and increase if you see latency
- The singleton pattern only helps in development; in production serverless, each
instance is isolated
- If using Prisma with Next.js API routes, each route invocation may be a separate
serverless function
- Consider Prisma Accelerate for built-in caching + pooling: https://www.prisma.io/accelerate
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「prisma-connection-pool-exhaustion」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次