🔍 검색 키워드: PostgreSQL connection pool, 데이터베이스 연결 풀, pg-pool, pgBouncer, 데이터베이스 성능 최적화, 커넥션 풀 설정
PostgreSQL Connection Pool 설정과 최적화 전략
PostgreSQL 데이터베이스에서 성능 병목의 70%는 연결 관리 문제에서 비롯됩니다. 특히 고트래픽 환경에서는 연결 수가 제한되어 있어서, 적절한 Connection Pool 설정이 없으면 요청이 대기 상태에 빠지고 타임아웃이 발생합니다.
문제 증상
다음과 같은 에러가 주기적으로 발생합니다:
Error: connect ECONNREFUSED 127.0.0.1:5432
Error: Client already has a client in it
FATAL: remaining connection slots are reserved
Error: query timeout - Client request timeout
원인 분석
원인 1: Connection Pool 미설정
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
// 각 쿼리마다 새 연결 생성 → 연결 고갈
원인 2: Connection Leak - 연결 반환 미흡
const client = await pool.connect();
const result = await client.query('SELECT * FROM users');
// ✗ client.release()를 호출하지 않음
해결 방법
해결책 1: Connection Pool 설정
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
statement_timeout: '30s'
});
app.get('/user/:id', async (req, res) => {
let client;
try {
client = await pool.connect();
const result = await client.query(
'SELECT * FROM users WHERE id = $1',
[req.params.id]
);
res.json(result.rows[0]);
} finally {
if (client) client.release();
}
});
해결책 2: pgBouncer 설정 (고트래픽 환경)
sudo apt-get install pgbouncer
# /etc/pgbouncer/pgbouncer.ini
[databases]
myapp = host=127.0.0.1 port=5432 dbname=myapp_prod
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25
idle_in_transaction_timeout = 60
성능 최적화
| 항목 | 최적값 |
| max 연결 수 | CPU 코어 × 2~4 |
| idleTimeoutMillis | 30~60초 |
| statement_timeout | 30~60초 |
Connection Pool을 올바르게 설정하면 데이터베이스 성능이 2~5배 향상될 수 있습니다.
댓글 없음:
댓글 쓰기