What are TCP keepalives, what are the Linux defaults, and how are they different from HTTP keep-alive and BGP keepalives?
Show the answer
Say this first
A TCP keepalive is an empty probe the stack sends on an idle connection, carrying a sequence number one below what the peer expects, so the peer must answer with an ACK. If enough probes go unanswered, the connection is reset and the application gets an error. It is off unless the application sets SO_KEEPALIVE. Linux defaults are 7,200 seconds idle, 75 seconds between probes and 9 probes, so a dead peer is found after about 2 hours 11 minutes. HTTP keep-alive just means reusing a connection for more requests. BGP keepalives are BGP messages, every 60 seconds with a 180-second hold time on Cisco.
Go deeper
Two jobs
- Find dead peers. A peer that crashed or lost its state leaves a half-open connection: our side thinks it is ESTABLISHED forever if we never send. A probe gets a RST or no answer.
- Keep middlebox state alive. Firewalls and NAT remove idle flows after their idle timeout, often an hour or less. A 2-hour default keepalive is too slow to help; the application's next packet then hits a device with no state and is dropped or reset.
Tuning
System-wide on Linux:
sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probesPer socket, which is better: TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT. A common rule is an idle time shorter than the shortest idle timeout in the path, for example 300 seconds.
Related
TCP_USER_TIMEOUT caps how long sent data may stay unacknowledged before the connection is dropped, which catches dead peers on busy connections where keepalive never triggers.
They will ask next
What is a half-open connection, and how is it different from half-closed?
Half-open: one side has state and the other does not, because of a crash, reboot or lost NAT state. Half-closed: one side sent FIN and the other is still legitimately sending. Half-closed is normal TCP; half-open is a failure that keepalives or the next send reveal.
Why do applications often add their own heartbeat instead?
TCP keepalive only proves the peer's kernel is alive. An application heartbeat (BGP keepalive, HTTP/2 PING, WebSocket ping) proves the process is working, and its timers are under the application's control.
Traps
- Confusing HTTP keep-alive (connection reuse) with TCP keepalive (idle probes).