Octet

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

  1. 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.
  2. 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:

Shell
sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes

Per 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.

Traps

  • Confusing HTTP keep-alive (connection reuse) with TCP keepalive (idle probes).
How did you do?Book 5.2 Reliable Byte Stream (TCP)