Keepalive

Created · Updated

A keepalive is a small message sent on an idle connection to check that the other end is still there, or to keep devices on the path from forgetting the connection. An idle TCP connection sends nothing at all. If the peer loses power or its network, no FIN or RST arrives, and the connection looks open forever. If a NAT router or firewall drops the connection’s state after an idle timeout, the next packet is dropped or reset. Keepalives turn both into errors on a known schedule.

Keepalive happens at two levels:

  • TCP keepalive: the kernel sends an empty probe after an idle time, and the peer’s kernel must ACK it. It checks the path and the peer’s kernel, and its traffic refreshes NAT and firewall state.
  • Application heartbeat: the program sends a message, such as a ping, and the peer’s program answers, such as with a pong. It checks that the peer process still works, and it crosses proxies.
  • HTTP keep-alive is a different thing with a similar name: reusing one TCP connection for many requests.

Four rows, processes on the left and kernels on the right: client, then a NAT router that forgets idle flows, then a proxy, then the server. Heartbeat arrows run from the client process to the proxy process, which relays bytes, and on to the server process, so a heartbeat reaches the server. Probe arrows run from the client kernel through the NAT router and end at the proxy kernel, which sends its own probes to the server kernel.

The lab is three Alpine containers on Linux 6.12: client at 10.60.1.10, router with an address on each network, 10.60.1.254 and 10.60.2.254, and server at 10.60.2.20. A Python server on port 9000 answers ping with pong, and a Python client sets the keepalive options per run. tcpdump captured on the client and server, iptables on the router dropped or tracked traffic, and conntrack showed the router’s table.

The kernel and the program

StepDone byWhen
Enable keepalive and set its timersProgram, with setsockoptOnce, after connecting
Count idle time, send probes, count unanswered onesKernel timersWith no system call from the program
Answer a probePeer’s kernelEven when the peer process is stopped
Report a dead peerKernel, as ETIMEDOUTOn the program’s next recv(), send(), or poll()
Send pings, time pongs, give upProgramIn its own code, with its own timers
  • With TCP keepalive, the program can stay blocked in recv() the whole time. The kernel sends every probe, and recv() returns only when the connection fails.
  • ss -o shows the kernel’s timer: a socket with keepalive enabled showed timer:(keepalive,1.956sec,0), the time to the next probe and the count of unanswered probes.
  • A heartbeat is ordinary data, so the program needs a timer of its own, such as a read deadline, and a thread or event loop to send pings.

Why idle connections need probing

  • A peer that disappears sends nothing. The TCP page’s lab left an idle connection without keepalive ESTABLISHED for 17 minutes after the server’s network went away, and it would have stayed that way.
  • The other side ends up with a half-open connection: one end still has it, the other has dropped it. In the lab, after the client gave up on a dead server, the server, which had no keepalive, still listed the connection as ESTABLISHED.
  • Stateful devices on the path remove idle flows after a timeout. After that, the next packet is dropped or answered with an RST, depending on the device.
DeviceIdle timeout for established TCP
Linux conntrack, nf_conntrack_tcp_timeout_established432,000 s, 5 days
AWS Network Load Balancer350 s, configurable from 60 to 6,000 s; sends RST after
AWS NAT gateway350 s; sends RST after
Google Cloud NAT1,200 s, 20 minutes
Azure Load Balancer4 minutes, configurable up to 100 (120 for outbound rules)
  • Any traffic resets these timers, including TCP keepalive probes. AWS documents keepalive probes as a way to keep an NLB flow open.

TCP keepalive

RFC 1122 makes keepalive optional and sets its rules: off by default, sent only on an idle connection, an interval that defaults to no less than two hours, and no failure from one lost probe.

SettingLinux sysctl, defaultSocket option
On or offoffSO_KEEPALIVE
Idle time before the first probetcp_keepalive_time, 7,200 sTCP_KEEPIDLE
Time between unanswered probestcp_keepalive_intvl, 75 sTCP_KEEPINTVL
Unanswered probes before giving uptcp_keepalive_probes, 9TCP_KEEPCNT
  • A dead peer is found idle + interval × count after the last packet. With Linux’s defaults, that’s 7,200 + 75 × 9 = 7,875 s, about 2 hours 11 minutes.
  • SO_KEEPALIVE alone uses the sysctls: ss -o showed timer:(keepalive,119min,0) on a new connection. Without SO_KEEPALIVE, ss showed no timer.
  • The probe is an ACK segment with no data whose sequence number is one less than the next byte to send. The peer has already received that byte number, so it must answer with an ACK of the current position.

A capture of the client’s packets on a connection with TCP_KEEPIDLE 3, idle after the handshake:

TimeClient packetSequence number
0.000 sSYN3,724,823,879, the initial sequence number
0.000 sACK that ends the handshake3,724,823,880, the next byte to send
3.021 sKeepalive probe, no data3,724,823,879, one less
6.010 sFIN, at close3,724,823,880
  • In a run with TCP_KEEPIDLE 5, TCP_KEEPINTVL 3, and TCP_KEEPCNT 3, the server’s kernel answered each probe within 0.02 ms with an ACK of the initial sequence number plus one, the client’s current position.
  • With the peer answering, probes came about 5.1 s apart, the idle time, not the interval: each ACK makes the connection newly idle. The interval only spaces probes that got no answer.
  • In that 20-second idle run, the client sent 3 probes, and the program received nothing.

Detecting a dead peer

With the same 5, 3, 3 settings, the router dropped every packet of the connection in both directions, 1 s after it opened:

Time after connectEvent
5.2 sProbe 1, no answer
8.2 sProbe 2, no answer
11.2 sProbe 3, no answer
14.3 srecv() fails with ETIMEDOUT
  • 14.3 s matches 5 + 3 × 3: the third probe gets one more interval to be answered.
  • The server had no keepalive and no data to send, so it kept the connection ESTABLISHED, a half-open connection.
  • Keepalive only runs on an idle connection. With unacknowledged data, retransmission takes over, and TCP_USER_TIMEOUT bounds it, as the TCP page shows.

Keeping NAT state

The router masqueraded the client’s traffic and accepted only packets of tracked connections. Its idle timeout for established TCP, nf_conntrack_tcp_timeout_established, was set to 20 s, and nf_conntrack_tcp_loose to 0, so it wouldn’t pick up a connection again from a packet in the middle of it.

ClientConntrack entryPing sent after 30 s idle
No keepalive17 s left at 2 s; gone at 27 sDropped at the router, with every retransmission: 9 packets. The server saw nothing after the handshake. No pong within 30 s
Keepalive every 10 sBack to 20 s after each probe, at 10.4 s and 20.6 sArrived; pong after 0.1 ms
  • The client had no way to know the router had forgotten the connection: its own state stayed ESTABLISHED, and its send() succeeded.
  • A keepalive idle time shorter than the smallest idle timeout on the path keeps the state alive. Linux’s default of 2 hours is longer than every timeout in the table above except conntrack’s.

What TCP keepalive can’t see

The server process was stopped with SIGSTOP, 3.1 s after two clients connected. Both had keepalive at 5, 3, 3. One relied on keepalive only; the other also sent ping every 2 s and expected pong within 5 s:

ClientResult
Keepalive onlyProbes at 5, 10, 15, 20, and 25 s, each ACKed by the server’s kernel. The connection stayed healthy for 30 s, until the test ended
Keepalive and heartbeatPings at 0, 2, and 4 s. The kernel ACKed the 4 s ping’s bytes 42 ms later, but no pong came. The heartbeat failed at 9.0 s
  • The kernel answers probes and ACKs data with no help from the process. A deadlocked, frozen, or overloaded process looks alive to TCP keepalive.
  • A TCP proxy ends one TCP connection and opens another. A client’s probes every 3 s were all answered by the proxy’s kernel; on the proxy-to-server connection, nothing passed between the handshake and the close.
  • Load balancers that work at the HTTP level do the same, so TCP keepalive tells a client only about the nearest proxy.

Application heartbeats

  • A heartbeat is a message the program sends and the peer’s program must answer. Its answer proves the whole path and the peer process work.
  • It needs three numbers: how often to send, how long to wait for an answer, and how many misses end the connection.
  • It’s data, so it refreshes NAT and firewall state like any other packet, and it passes through proxies that relay bytes.
  • It costs more than a TCP probe: the peer’s process wakes up and answers each one, and a server with many connections answers many heartbeats.
ProtocolHeartbeatDefaults
HTTP/2PING frame, type 0x6, with 8 bytes of any data; the peer must answer with a PING with the ACK flag and the same 8 bytesNone in the protocol
WebSocketPing control frame, opcode 0x9; the peer must answer with a Pong, opcode 0xA. An unsolicited Pong is a one-way heartbeatNone in the protocol
gRPCHTTP/2 PING after KEEPALIVE_TIME, closed if no answer within KEEPALIVE_TIMEOUTClient: off. Server: every 2 hours. Timeout 20 s
SSHServerAliveInterval sends a request through the encrypted channel; ServerAliveCountMax misses disconnectOff; 3 misses. TCPKeepAlive is on
BGPKEEPALIVE message every third of the hold timeHold time 180 s in FRR, so 60 s
  • A gRPC server limits how often clients may ping: by default, pings less than 5 minutes apart with no data count as strikes, and after more than 2 strikes the server closes the connection with a GOAWAY frame carrying too_many_pings.
  • gRPC sends keepalive pings only while calls are in progress, unless KEEPALIVE_PERMIT_WITHOUT_CALLS is set on both sides.
  • SSH’s manual notes that its heartbeat runs inside the encryption and can’t be faked, while TCP keepalive probes can.

HTTP keep-alive

HTTP keep-alive means persistent connections: after a response, the TCP connection stays open for the next request instead of closing. It saves a handshake, and a TLS handshake, for each request. HTTP/1.0 asked for it with a Connection: keep-alive header; in HTTP/1.1 it’s the default, and Connection: close turns it off.

  • It sends no probes. An idle persistent connection is just an idle TCP connection, closed by whichever side’s idle timer runs out first.
  • nginx closes idle client connections after keepalive_timeout, 75 s by default.
  • Go’s http.DefaultTransport closes idle connections after IdleConnTimeout, 90 s. http.Server.IdleTimeout falls back to ReadTimeout, and to no limit when both are zero.
  • A client that sends a request on a connection the server has just closed gets an error instead of a response.

In a program

In Go:

  • net.Dialer and net.ListenConfig turn on TCP keepalive for every connection: 15 s idle, probes every 15 s, 9 probes. KeepAliveConfig, added in Go 1.23, sets each value; a negative KeepAlive turns it off.
  • http.DefaultTransport dials with KeepAlive set to 30 s.
  • conn.SetReadDeadline is the timer for a heartbeat: a Read that passes the deadline returns an error whose Timeout() is true, and the program decides to ping again or close.
  • http.HTTP2Config.SendPingTimeout sends an HTTP/2 PING after that long with no frame received, and PingTimeout, 15 s by default, closes the connection if no answer arrives. Zero SendPingTimeout, the default, sends no pings.
  • A keepalive failure surfaces as syscall.ETIMEDOUT on the next Read or Write.

The TCP page covers retransmission timeouts and TCP_USER_TIMEOUT, NAT covers connection tracking, and BGP covers its hold timer.

References: RFC 1122: Requirements for internet hosts, TCP keep-alives, RFC 9293: Transmission Control Protocol, tcp(7), socket(7), Linux IP sysctl, Linux netfilter conntrack sysctl, ss(8), RFC 9113: HTTP/2, PING, RFC 6455: WebSocket, Ping and Pong, gRPC keepalive, ssh_config(5), RFC 9112: HTTP/1.1, persistence, nginx keepalive_timeout, AWS Network Load Balancer idle timeout, AWS NAT gateway troubleshooting, Google Cloud NAT timeouts, Azure Load Balancer TCP reset and idle timeout, Go net package, Go net/http package