Understanding TCP Keepalive and HTTP Keepalive Mechanisms
This article explains the concepts, purposes, and inner workings of TCP keepalive and HTTP keepalive, compares their roles in maintaining network connections, and provides practical guidance on configuring related parameters and handling socket lifecycles in server environments.
TCP Keepalive is a kernel‑level timer that periodically sends a probe packet when no data has been exchanged for tcp_keepalive_time seconds. If the probe receives no response, a secondary timer sends up to tcp_keepalive_probes probes at intervals of tcp_keepalive_intvl . These parameters are stored in /proc/sys/net/ipv4/tcp_keepalive_time , /proc/sys/net/ipv4/tcp_keepalive_intvl , and /proc/sys/net/ipv4/tcp_keepalive_probes . The mechanism prevents half‑open connections by closing sockets that no longer respond.
On the application side, HTTP Keepalive (also called persistent connection) reuses a single TCP connection for multiple HTTP request/response pairs, reducing the overhead of establishing new connections. After a response is received, a timer starts; if no new request arrives before the timeout, the connection is closed. The article illustrates this flow with a Python socket example and explains why higher‑level libraries like requests hide the raw socket handling.
The relationship between the two mechanisms is that TCP keepalive acts as a low‑level safety net to reclaim dead sockets, while HTTP keepalive gives the application layer finer control over connection lifetimes, often using shorter timeouts than the kernel defaults.
Practical deployment tips include configuring server‑side keepalive parameters such as Gunicorn 's keepalive and Nginx 's keepalive_timeout . When multiple services share a host, the global nature of TCP keepalive must be balanced with per‑service HTTP settings to avoid premature disconnections or resource exhaustion.
To inspect active sockets, the command lsof -i :8080 (replace 8080 with the actual port) can be used, showing the underlying socket file descriptors that each process holds.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.