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.
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
| Step | Done by | When |
|---|---|---|
| Enable keepalive and set its timers | Program, with setsockopt | Once, after connecting |
| Count idle time, send probes, count unanswered ones | Kernel timers | With no system call from the program |
| Answer a probe | Peer’s kernel | Even when the peer process is stopped |
| Report a dead peer | Kernel, as ETIMEDOUT | On the program’s next recv(), send(), or poll() |
| Send pings, time pongs, give up | Program | In 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, andrecv()returns only when the connection fails. ss -oshows the kernel’s timer: a socket with keepalive enabled showedtimer:(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.
| Device | Idle timeout for established TCP |
|---|---|
Linux conntrack, nf_conntrack_tcp_timeout_established | 432,000 s, 5 days |
| AWS Network Load Balancer | 350 s, configurable from 60 to 6,000 s; sends RST after |
| AWS NAT gateway | 350 s; sends RST after |
| Google Cloud NAT | 1,200 s, 20 minutes |
| Azure Load Balancer | 4 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.
| Setting | Linux sysctl, default | Socket option |
|---|---|---|
| On or off | off | SO_KEEPALIVE |
| Idle time before the first probe | tcp_keepalive_time, 7,200 s | TCP_KEEPIDLE |
| Time between unanswered probes | tcp_keepalive_intvl, 75 s | TCP_KEEPINTVL |
| Unanswered probes before giving up | tcp_keepalive_probes, 9 | TCP_KEEPCNT |
- A dead peer is found
idle + interval × countafter the last packet. With Linux’s defaults, that’s 7,200 + 75 × 9 = 7,875 s, about 2 hours 11 minutes. SO_KEEPALIVEalone uses the sysctls:ss -oshowedtimer:(keepalive,119min,0)on a new connection. WithoutSO_KEEPALIVE,ssshowed 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:
| Time | Client packet | Sequence number |
|---|---|---|
| 0.000 s | SYN | 3,724,823,879, the initial sequence number |
| 0.000 s | ACK that ends the handshake | 3,724,823,880, the next byte to send |
| 3.021 s | Keepalive probe, no data | 3,724,823,879, one less |
| 6.010 s | FIN, at close | 3,724,823,880 |
- In a run with
TCP_KEEPIDLE5,TCP_KEEPINTVL3, andTCP_KEEPCNT3, 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 connect | Event |
|---|---|
| 5.2 s | Probe 1, no answer |
| 8.2 s | Probe 2, no answer |
| 11.2 s | Probe 3, no answer |
| 14.3 s | recv() 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_TIMEOUTbounds 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.
| Client | Conntrack entry | Ping sent after 30 s idle |
|---|---|---|
| No keepalive | 17 s left at 2 s; gone at 27 s | Dropped at the router, with every retransmission: 9 packets. The server saw nothing after the handshake. No pong within 30 s |
| Keepalive every 10 s | Back to 20 s after each probe, at 10.4 s and 20.6 s | Arrived; 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:
| Client | Result |
|---|---|
| Keepalive only | Probes 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 heartbeat | Pings 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.
| Protocol | Heartbeat | Defaults |
|---|---|---|
| HTTP/2 | PING frame, type 0x6, with 8 bytes of any data; the peer must answer with a PING with the ACK flag and the same 8 bytes | None in the protocol |
| WebSocket | Ping control frame, opcode 0x9; the peer must answer with a Pong, opcode 0xA. An unsolicited Pong is a one-way heartbeat | None in the protocol |
| gRPC | HTTP/2 PING after KEEPALIVE_TIME, closed if no answer within KEEPALIVE_TIMEOUT | Client: off. Server: every 2 hours. Timeout 20 s |
| SSH | ServerAliveInterval sends a request through the encrypted channel; ServerAliveCountMax misses disconnect | Off; 3 misses. TCPKeepAlive is on |
| BGP | KEEPALIVE message every third of the hold time | Hold 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_CALLSis 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.DefaultTransportcloses idle connections afterIdleConnTimeout, 90 s.http.Server.IdleTimeoutfalls back toReadTimeout, 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.Dialerandnet.ListenConfigturn 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 negativeKeepAliveturns it off.http.DefaultTransportdials withKeepAliveset to 30 s.conn.SetReadDeadlineis the timer for a heartbeat: aReadthat passes the deadline returns an error whoseTimeout()is true, and the program decides to ping again or close.http.HTTP2Config.SendPingTimeoutsends an HTTP/2 PING after that long with no frame received, andPingTimeout, 15 s by default, closes the connection if no answer arrives. ZeroSendPingTimeout, the default, sends no pings.- A keepalive failure surfaces as
syscall.ETIMEDOUTon the nextReadorWrite.
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