Vercel Fluid Compute로 전환하고 일주일 운영 중인데 인스턴스가 점진적으로 OOM 됩니다. 디버그해보니 pg Pool의 connection count가 시간에 따라 증가만 합니다.
// db.ts
import { Pool } from 'pg'
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20,
})
export { pool }
// api/route.ts
import { pool } from '@/lib/db'
export async function GET() {
const client = await pool.connect()
try {
const r = await client.query('SELECT ...')
return Response.json(r.rows)
} finally {
client.release() // 여기서 release하는데...
}
}
매 요청 release 하는데도 idle connection이 1시간에 약 30개씩 누적. Postgres max_connections 한도 도달. Fluid Compute 환경에서 pg Pool 사용 패턴 잘못된 게 있을까요?
환경: Vercel Pro, Fluid Compute ON, Next 17, pg 8.13, Neon Postgres
댓글 4
Fluid Compute의 가장 흔한 함정입니다. 원인은 두 가지 중 하나.
원인 1 — Neon serverless driver 미사용
Neon Postgres는 pg(node-postgres)로 직접 연결하면 TCP 기반이라 인스턴스가 살아있는 동안 connection 유지. Fluid는 인스턴스가 N시간 살아있으니 connection이 풀로 계속 쌓입니다.
HTTP driver는 connection 개념 자체가 없어서 누수 불가. 트랜잭션 자주 쓰면 serverless Pool driver.
원인 2 — 에러 path에서 release 누락
Fluid Compute는 동시 요청 처리.
try-finally안 쓰고 if/else로 분기한 경로에서 release를 빠뜨리면 누수. 위 코드는 OK해 보이지만 다른 파일도 확인.디버깅
idle in transaction이 쌓이면 release 누락 확정. idle만 쌓이면 Pool max 초과 또는 connection을 어디서 명시 close 안 함.
해결
저희 팀도 같은 문제 겪고 serverless driver로 옮기니 즉시 해결됐습니다.
PgBouncer를 앞단에 두는 방법도 있습니다. Neon이 자체 pooler 옵션 제공하니 connection string에
?pgbouncer=true추가해보세요. 단 prepared statement 호환성 깨지는 케이스 있으니 주의.