TCP keepalive

On this page 7

TCP keepalive is an optional mechanism that sends small probe segments over an idle connection to verify that the remote endpoint is still alive and reachable. Among the transport protocols used in networking, TCP itself carries no traffic when neither side has data to send, so a connection can remain open indefinitely after the peer has crashed, rebooted or disappeared behind a failed link. Keepalive closes that gap by detecting dead peers and, as a side effect, by keeping stateful middleboxes from forgetting the flow.

The mechanism is described in RFC 1122 and later in the consolidated TCP specification, RFC 9293, which treat it as an optional feature that must be disabled by default and configurable per connection. Applications enable it through the SO_KEEPALIVE socket option and tune it with three timers that every operating system exposes in some form.

How TCP keepalive probes an idle connection

A keepalive probe is a segment that elicits an acknowledgment without carrying new data. The sender typically transmits a segment whose sequence number is one less than the next expected byte (SND.NXT minus one), optionally with a single garbage byte. Because the receiver has already acknowledged that byte, it treats the segment as a duplicate and replies with an ACK that restates its current state.

The process runs in three stages. First, the connection must stay idle for the keepalive time, during which no segments arrive. Second, the stack sends a probe and waits for the probe interval. Third, if no answer arrives, it repeats the probe until the probe count is exhausted, after which it aborts the connection and reports an error such as ETIMEDOUT to the application.

The peer can answer in three ways, and each answer leads to a different outcome for the local stack. The following table summarizes the possible responses.

Peer responseMeaningLocal action
ACK receivedPeer is alive and the connection is validReset the idle timer
RST receivedPeer rebooted and lost the connection stateAbort with connection reset
No responsePeer is down or the path is brokenRetry until the probe count is reached
ICMP unreachableNetwork or host is unreachableCount as failure, often abort earlier
Possible responses to a keepalive probe

Keepalive timers and default values

Three parameters control keepalive behavior, and their defaults are deliberately conservative. RFC 1122 requires that the idle threshold be no less than two hours by default, which explains why many systems wait 7,200 seconds before the first probe. With common Linux defaults, a dead peer is detected only after about two hours and eleven minutes.

ParameterLinux settingTypical defaultEffect
Keepalive timetcp_keepalive_time7,200 sIdle period before the first probe
Probe intervaltcp_keepalive_intvl75 sWait between unanswered probes
Probe counttcp_keepalive_probes9Failed probes before abort
Socket optionSO_KEEPALIVEOffEnables the mechanism per socket
Keepalive parameters on common operating systems

Applications can override system-wide values per socket with TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT on Linux, or with equivalent options on Windows and BSD-derived systems. Windows historically uses ten probes at one-second intervals after a two-hour idle period, so the worst-case detection time differs noticeably between platforms. The total detection time equals keepalive time plus interval multiplied by probe count.

TCP keepalive is only one of several ways to detect a lost peer, and it is often confused with application heartbeats and the user timeout. Each mechanism observes a different condition, so robust systems frequently combine them. The comparison below clarifies their roles.

MechanismLayerWhat it detectsMain limitation
TCP keepaliveTransportDead peer on an idle connectionCannot see a hung application
TCP user timeoutTransportUnacknowledged data in flightInactive when no data is pending
Application heartbeatApplicationUnresponsive service logicMust be designed into the protocol
SCTP heartbeatTransportPath and peer reachabilityRequires SCTP support end to end
HTTP/2 PING frameApplicationStalled multiplexed sessionSpecific to HTTP/2 and HTTP/3
Liveness mechanisms around TCP connections

The TCP user timeout defined in RFC 5482 complements keepalive: it limits how long transmitted data may remain unacknowledged, whereas keepalive covers the case where nothing is being sent. Retransmission timers already handle broken paths during active transfers, so keepalive matters mainly for long-lived, mostly silent connections such as database pools and message brokers.

Configuring TCP keepalive in practice

The most common reason to tune keepalive today is NAT and firewall state expiry. Home routers, carrier-grade NAT and cloud load balancers drop idle flows after a fixed timeout, often between 4 and 30 minutes, and a two-hour default is far too long to prevent that. Setting the keepalive time below the shortest idle timeout on the path keeps the mapping alive.

The right values depend on what the application must achieve. The decision table below links typical goals with sensible settings.

GoalSuggested settingReason
Survive NAT timeoutsIdle time of 60-300 sRefreshes state before middleboxes expire it
Fast failover in clustersIdle 10-30 s, interval 5 s, 3 probesDetects loss within about one minute
Mobile clients on batteryLong idle time or app heartbeatsEach probe wakes the radio and costs energy
Bulk server with many socketsModerate idle time near 600 sLimits probe traffic across thousands of flows
Choosing keepalive settings by goal

Keepalive must be enabled on the side that needs to detect the failure, because each endpoint runs its own timers. A server that never enables SO_KEEPALIVE will keep half-open sockets from vanished clients, slowly consuming memory and file descriptors.

Limitations and common mistakes

Keepalive proves only that the remote TCP stack is responding, not that the application behind it is healthy. A process stuck in a deadlock still has a kernel that acknowledges probes, so keepalive alone cannot replace application-level health checks. Several further pitfalls recur in production systems.

  • Assuming it is on by default: most stacks require an explicit SO_KEEPALIVE call per socket.
  • Aggressive timers on transient paths: very short intervals can kill connections during brief routing changes or Wi-Fi roaming.
  • Relying on probes through proxies: a TCP-terminating proxy answers probes itself, so the far server is never tested.
  • Ignoring probe cost at scale: millions of idle connections with short timers generate measurable background traffic.
  • Confusing it with HTTP keep-alive: persistent HTTP connections reuse a socket for multiple requests and involve no probes.

Stripped to the essentials

Two computers can keep a network connection open for hours without saying anything. The trouble is that if one of them crashes or loses its network, the other one has no way of noticing, because silence looks the same either way.

TCP keepalive is a quiet periodic check-in. After a long pause, one side sends a tiny message that asks, in effect, are you still there. If the other side answers, everything stays as it is. If several questions go unanswered, the connection is closed and the program is told. The key idea is simple: keepalive turns an endless, uncertain silence into a clear yes or no, and it also stops routers from forgetting a connection that has gone quiet.

Where it is applied

A company runs an application server in a cloud network that connects to a database through a load balancer with a 350-second idle timeout. Users reported that the first query after lunch often failed with a connection reset, because the pooled database connections had been silently dropped by the load balancer while the application still considered them open.

The operations team enabled SO_KEEPALIVE in the connection pool and set the idle time to 120 seconds, the interval to 15 seconds and the probe count to 4. The probes now refresh the load balancer state every two minutes, and a genuinely dead database node is detected in about three minutes instead of more than two hours. The lunchtime errors disappeared, and the extra traffic amounted to a few small segments per connection per hour.