본문 바로가기
C.W.K.
Stream
Lesson 08 of 10 · published

연결 풀과 pgBouncer

~12 min · apps, pooling

Level 0스키마 새싹
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

PostgreSQL 연결은 공짜가 아니야

백엔드 연결 하나는 프로세스와 약 10MB 메모리를 쓰고 운영 데이터베이스의 max_connections는 흔히 100-200이야. Lambda나 Vercel 같은 서버리스 환경에서 수천 개 실행이 각각 직접 연결하면 감당할 수 없어.

작은 실제 연결 집합을 공유해

pgBouncer는 앱의 많은 연결을 받아 적은 PostgreSQL 연결로 다중화해. 세션 풀링은 클라이언트 세션 동안, 트랜잭션 풀링은 트랜잭션 동안만 실제 연결을 붙잡아. 문장 풀링은 문장마다 연결을 돌려주므로 여러 문장으로 이루어진 트랜잭션을 유지할 수 없어 거의 쓰지 않아.

세션 기능의 대가를 알아

트랜잭션 풀링에서는 SET, prepared statement, LISTEN, 세션 advisory lock처럼 같은 연결에 기대는 기능이 깨질 수 있어. 서버리스에는 대개 트랜잭션 모드가 맞지만 기능별로 확인해.

Code

연결 풀 크기 계산하기·text
목표: max_connections=100 인 Postgres 에 1000 동시 앱 프로세스 지원.

직접 connection: 1000 / 100 = 10× 용량 초과 → connection storm, 에러.

pgBouncer (transaction 모드) 로:
  - 1000 앱 프로세스가 pgBouncer 에 연결 (싸).
  - pgBouncer 가 진짜 Postgres connection 100 유지.
  - 평균 트랜잭션 10ms → 효과적 처리량 100*1000/10 = 초당 10,000 tx.
앱의 연결 풀 설정·python
# psycopg pool — 앱 레벨, pgBouncer 보완
from psycopg_pool import ConnectionPool

pool = ConnectionPool(
    "postgresql://app:****@pgbouncer:6432/mydb",
    min_size=4,
    max_size=20,
    timeout=10.0,
)

with pool.connection() as conn:
    conn.execute("SELECT 1")
Supabase의 pgBouncer URL·bash
# 직접 connection (port 5432) — 진짜 Postgres connection 사용
postgresql://postgres.PROJECT:****@aws-0-region.pooler.supabase.com:5432/postgres

# Transaction pooler (port 6543) — 연결 싸, transaction-mode
postgresql://postgres.PROJECT:****@aws-0-region.pooler.supabase.com:6543/postgres
# Serverless / Lambda / Vercel 에 사용.

External links

Exercise

프로젝트가 연결 풀러를 거치는지 데이터베이스에 직접 연결하는지 확인해. 직접 연결한다면 동시에 실행될 앱 프로세스의 연결 수가 max_connections 안에 들어오는지 계산하고, 넘는다면 pgBouncer나 관리형 대안으로 옮길 계획을 세워.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.