🗄️ Databases

Connection Pool

Connection Pool

A technique for reusing DB connections. Reduces overhead.

Detailed Explanation

A Connection Pool is a technique that creates database connections in advance and reuses them. Because a DB connection is an expensive operation involving a TCP handshake, authentication, and session initialization, instead of creating and closing a connection for every request, you borrow one from the pool and return it.

A connection pool lets you configure the minimum/maximum number of connections, idle connection timeout, connection validation, and so on. Proper sizing is important: if it is too small, waiting occurs, and if it is too large, it burdens the DB server. In general, (number of CPU cores * 2) + effective spindle count is recommended.

It can be implemented at the application level (HikariCP, DBCP) and at the middleware level (pgBouncer, ProxySQL). In serverless environments there is the problem of connection surges, so an external pooler such as PgBouncer or AWS RDS Proxy is sometimes used.

Code Example

# Python - SQLAlchemy 커넥션 풀 설정
from sqlalchemy import create_engine

engine = create_engine(
    'postgresql://user:password@localhost/mydb',
    pool_size=10,           # 기본 풀 크기
    max_overflow=20,        # 최대 추가 연결 수
    pool_timeout=30,        # 연결 대기 타임아웃 (초)
    pool_recycle=1800,      # 연결 재활용 주기 (초)
    pool_pre_ping=True      # 연결 상태 확인
)

# Java - HikariCP 설정
# application.yml
spring:
  datasource:
    hikari:
      minimum-idle: 5
      maximum-pool-size: 20
      idle-timeout: 300000      # 5분
      max-lifetime: 1800000     # 30분
      connection-timeout: 30000 # 30초
      validation-timeout: 5000
      leak-detection-threshold: 60000

# Node.js - pg Pool 설정
const { Pool } = require('pg');

const pool = new Pool({
    host: 'localhost',
    database: 'mydb',
    user: 'user',
    password: 'password',
    max: 20,                    // 최대 연결 수
    idleTimeoutMillis: 30000,   // 유휴 타임아웃
    connectionTimeoutMillis: 10000
});

// 커넥션 사용
const client = await pool.connect();
try {
    const result = await client.query('SELECT * FROM users WHERE id = $1', [userId]);
    return result.rows;
} finally {
    client.release();  // 풀에 반환 (닫지 않음!)
}

// Django - 커넥션 풀 설정
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': 'localhost',
        'NAME': 'mydb',
        'CONN_MAX_AGE': 600,    # 연결 유지 시간 (초)
        'CONN_HEALTH_CHECKS': True,
    }
}

Practical Conversation Example

Backend developer: We get "too many connections" errors when traffic spikes.

DBA: What's your connection pool's max_pool_size? And the DB's max_connections?

Backend developer: The pool is 50 per server, and with 10 servers that's 500, while max_connections is 200.

DBA: Then of course it's exceeded. Use pgBouncer for connection pooling, or reduce the application pool size.

Interviewer: How do you decide on an appropriate connection pool size?

Candidate: HikariCP's official guidance recommends (number of CPU cores * 2) + effective spindle count. With SSDs, it's roughly 2 to 3 times the number of cores. In practice, though, you have to find the optimal value through load testing, because it varies with query characteristics.

Interviewer: What should you watch out for with connection pools?

Candidate: You must always return connections. Prevent leaks with try-finally or the using pattern, and catch problems early with leak detection settings.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Senior: The connection.close() here isn't inside a finally block.

Junior: Doesn't it get closed if no exception occurs?

Senior: If an exception occurs midway, the connection isn't returned and the pool gets exhausted. Always return it in finally or use a with statement. Connection leaks are hard-to-find bugs.

Cautions

Related Terms

Learn More