HTTP Keep-Alive và Connection Pool đều tránh overhead tạo kết nối mới cho mỗi request — quan trọng cho performance của cả HTTP calls và database queries.
HTTP Keep-Alive (persistent connection): HTTP/1.0 default là close connection sau mỗi request (mỗi request = TCP handshake + TLS handshake + request + response + close = nhiều overhead). HTTP/1.1 default Connection: keep-alive — reuse TCP connection cho nhiều request liên tiếp, tránh handshake overhead. Keep-Alive: timeout=5, max=1000 — connection idle 5s thì close, tối đa 1000 requests.
Connection Pool (client-side): client maintain pool of pre-established connections — khi cần request, lấy connection từ pool thay vì tạo mới. Cần thiết cho database connections (PostgreSQL/MySQL pool), HTTP connections đến external services.
Config quan trọng: pool size (số connections tối đa — quá nhỏ: queuing, quá lớn: resource waste), idle timeout (close connections không dùng), connection lifetime (rotate để tránh stale connections).
Node.js http.globalAgent: mặc định pool HTTP connections, keepAlive: true và maxSockets: Infinity. Với database: pg-pool, Prisma connection pool — thiếu pool là lỗi phổ biến khiến DB bị overloaded với quá nhiều short-lived connections.
HTTP Keep-Alive and Connection Pool both avoid the overhead of creating a new connection for every request — critical for the performance of both HTTP calls and database queries.
HTTP Keep-Alive (persistent connection): HTTP/1.0 defaults to closing the connection after each request (each request = TCP handshake + TLS handshake + request + response + close = significant overhead). HTTP/1.1 defaults to Connection: keep-alive — the TCP connection is reused for multiple successive requests, avoiding handshake overhead. Keep-Alive: timeout=5, max=1000 — the connection closes after 5 seconds of idle time, up to 1000 requests.
Connection Pool (client-side): the client maintains a pool of pre-established connections — when a request is needed, it takes a connection from the pool rather than creating a new one. Essential for database connections (PostgreSQL/MySQL pools) and HTTP connections to external services.
Key config: pool size (max connections — too small: requests queue, too large: wasted resources), idle timeout (close unused connections), and connection lifetime (rotate to avoid stale connections).
Node.js http.globalAgent: HTTP connections are pooled by default; set keepAlive: true and maxSockets: Infinity. For databases: pg-pool, Prisma connection pool — missing a pool is a common mistake that causes DB overload from too many short-lived connections.