Trung BìnhNetwork iconNetwork

HTTP Keep-Alive và Connection Pooling: cơ chế và tác động đến performance?

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: truemaxSockets: 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.

Xem toàn bộ Network cùng filter theo level & chủ đề con.

Mở danh sách Network