A server may maintain an open connection with a client for hours, even though the client has disconnected from the network or closed the application without properly terminating the connection.
If the server fails to detect this situation, these inactive connections can continue consuming valuable system resources. This is where TCP Keepalive comes into play.
TCP Keepalive is a mechanism built into the TCP protocol that periodically sends small probe packets to verify whether the remote endpoint is still reachable.
If no response is received after several attempts, the connection is considered dead and is automatically closed.
The process typically follows these steps:
Closes stale or abandoned connections, freeing server resources.
Prevents dead connections from accumulating and affecting overall system performance.
Essential for applications that maintain persistent TCP sessions.
TCP Keepalive is widely used in:
Although they serve similar purposes, they operate at different layers.
TCP Keepalive works at the TCP protocol level, verifying that the network connection still exists.
Heartbeat, on the other hand, is an application-level message used to confirm that the service itself is functioning correctly—not just that the connection remains open.
To get the most from TCP Keepalive:
Only slightly. Keepalive packets are very small and are transmitted infrequently, making their impact on network bandwidth minimal.
It depends on the operating system and the application's configuration. Many systems support it, but it often needs to be explicitly enabled or tuned.
TCP Keepalive helps servers detect stale or abandoned TCP connections, allowing them to reclaim resources and maintain application stability. It is especially valuable for services that rely on long-lived connections, such as databases, VPNs, SSH, WebSockets, and other persistent network applications.