TCP Keepalive Tuning for Overnight Agent Connections

Shorter keepalive windows prevent silent connection loss to cloud NAT timeouts.

Cover illustration for “TCP Keepalive Tuning for Overnight Agent Connections”

Overnight agent connections need TCP keepalive settings that match the infrastructure they cross, requiring a shorter window than Linux’s default of more than two hours. Tuning three kernel parameters keeps a socket that looks open from outlasting its NAT mapping. A complete configuration also accounts for unacknowledged data and application-layer timeouts, then verifies that the intended protection is active.

Why Linux's default TCP keepalive window outlasts the infrastructure agents run on

An intermediate router can discard an idle connection without telling either endpoint. The agent still has its socket, but the NAT mapping it needs to pass traffic is gone. Nothing announces the loss at the moment it happens. Without a keepalive signal, the agent may learn about the drop only when it next tries to write, long after the infrastructure stopped recognizing the connection.

Linux’s default keepalive window leaves ample room for that silent failure. Its idle wait extends beyond two hours before probing, while the NAT devices, load balancers, and cloud gateways that overnight agents traverse discard idle connections much sooner. The two timers serve different purposes. The kernel waits before testing an idle peer, while the intermediate device limits how long it retains unused connection state.

The kernel’s detection window also includes time spent waiting for unanswered probes. After tcp_keepalive_time seconds of inactivity, it sends probes at tcp_keepalive_intvl intervals, up to tcp_keepalive_probes times. The total dead-connection detection window is tcp_keepalive_time + (tcp_keepalive_probes × tcp_keepalive_intvl). For an overnight agent, an open local socket is not evidence that the path remains usable.

How cloud NAT gateways impose idle timeouts that Linux defaults cannot beat

AWS EC2 TCP connection management guidance specifies that connections through a NAT gateway time out after 350 seconds or more of inactivity. That interval expires long before Linux’s default keepalive probing begins. The expiry itself does not notify the agent. If a resource subsequently tries to use the connection, the gateway returns an RST rather than a FIN, exposing the lost mapping only when traffic resumes.

Azure NAT Gateway likewise removes the associated SNAT flow state when a TCP connection remains idle beyond its configured timeout. It does not proactively close the connection with a FIN or RST at expiry. If either endpoint later sends traffic on the dropped flow, the gateway responds with a TCP RST, so a quiet client can remain unaware throughout the intervening period.

GCP Cloud NAT drops the NAT mapping without warning when its tcp-established-idle-timeout timer runs out. The settings differ across these cloud environments, but in each one, intermediate state can expire without either endpoint being told. The kernel can still be waiting to send its first probe after the gateway has already removed the state that the agent depends on.

An RST received during a write identifies when the application encountered the problem. The loss may have happened much earlier.

What a hung agent connection costs in practice

An agent holding a stale socket can block silently until an application-layer timeout fires, leaving the work waiting on a connection that no longer has a usable path. The delay obscures the actual failure point. A later “broken pipe” or “connection reset” error describes the failed attempt to use the socket, while the idle-timeout event that caused it may be hours old.

If a computation leaves the connection idle longer than the path permits, the response cannot reach the client over the expired flow. Retrying does not change that timing relationship. A request that consistently exceeds the idle threshold can fail on every attempt, even though the underlying computation is simply taking longer than the network allows the connection to remain quiet.

A nightly Ldio:HttpInPoller seed query against Apache Jena Fuseki on an Azure Container Instance, accessed from Azure Container Apps, was consistently dropped at the approximately 4-minute idle timeout. At the same time, a separate pipeline polled the same server every 5 seconds all night. The server was receiving traffic throughout the query’s wait. That traffic nevertheless did not preserve the connection used by the seed query.

The idle timer belongs to the connection. Traffic on another socket to the same server does not reset it, regardless of how frequently that traffic arrives. Each long-lived connection has its own period of inactivity, and each can lose its mapping while other connections to the same destination continue working.

The three kernel parameters that close the gap, and how to set them

The primary fix is to reduce tcp_keepalive_time, tcp_keepalive_intvl, and tcp_keepalive_probes from their defaults to a window suited to the path. The first controls when probing begins after inactivity. The second controls the spacing of probes, while the third limits unanswered attempts.

For database connections and persistent API clients, set the idle period below the firewall’s or gateway’s timeout, typically well within a minute. The first probe must precede infrastructure expiry. A value comfortably inside the path’s tightest threshold gives keepalive traffic a chance to preserve the mapping before it vanishes. For AWS NAT Gateway, the relevant constraint is its 350-second idle timeout.

Shorter intervals find failures sooner but send more probe traffic, while probing less often uses fewer resources. The settings must be considered as a group. Setting an early first probe leaves part of the time it takes to detect a failure unset unless the interval and unanswered-probe count are set too.

To apply host-wide defaults, write the settings to /etc/sysctl.d/99-tcp-keepalive.conf and apply them with sysctl -p /etc/sysctl.d/99-tcp-keepalive.conf. Where different applications need different timing, a host-wide setting cannot express those distinctions on its own.

When the application controls its socket, use setsockopt with TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT to override the defaults for that socket. This keeps the policy local to the connection. In either configuration path, enable SO_KEEPALIVE on the socket, because the three timing parameters have no effect without that flag. Setting intervals is not the same as enabling probing.

Finally, use ss -tnop to connect the intended policy to the connections the agent actually holds by confirming that established target connections have active keepalive timers. This check belongs in the tuning step, before another overnight failure casts doubt on the settings.

Where OS-level keepalive alone is insufficient and what to layer on top

Tuned keepalive protects idle TCP connections, but another timer takes control when data is already unacknowledged. Linux sends no keepalive probes in that state. Instead, the retransmission timer governs, and default retransmission behavior can leave a stuck connection open for many minutes. This calls for a limit on how long data can stay unacknowledged, even with a shorter idle-probe schedule.

Set TCP_USER_TIMEOUT in relation to the chosen keepalive window. Derive it from tcp_keepalive_time + tcp_keepalive_intvl × tcp_keepalive_probes, expressed in milliseconds. A mismatched value can cause TCP_USER_TIMEOUT to override the probe count, disrupting the intended interval by closing the connection on the probe-timer tick after the user timeout expires.

Proxy-traversing connections have a separate limitation because some proxies require application-layer activity to satisfy their idle policies. For those connections, application-layer heartbeats are required to address the proxy’s idle policy. TCP probes alone cannot satisfy every intermediary. WebSocket ping/pong and gRPC PING frames provide protocol-level activity where those mechanisms are available, with TCP keepalive serving as an additional lower-level safety net.

SSH tunnels offer the same layered approach through OpenSSH’s ServerAliveInterval and ServerAliveCountMax settings in ~/.ssh/config. These operate at the application level and complement TCPKeepAlive yes. The application-level mechanism supplements the operating system’s checks rather than asking one timer to cover both the tunnel’s responsiveness and the underlying TCP connection.

Increasing the operating system’s TCP timeout beyond the gateway’s idle threshold does not preserve a NAT mapping. The gateway evicts its state according to its own timer, regardless of how long the host remains willing to wait. Longer patience does not produce network activity. Only traffic through the connection, including keepalive probes, resets that idle timer, so the defensive posture combines tuned keepalive, a matched TCP_USER_TIMEOUT, and application-layer heartbeats where the protocol provides them.

Applying keepalive tuning to an overnight agent: a concrete configuration path

For an overnight agent, begin with the tightest idle timeout on the connection’s path. Set the keepalive idle period well below that threshold, staying comfortably inside 350 seconds for AWS NAT Gateway or inside the configured gateway timeout on Azure. The shortest applicable window governs the choice.

Next, apply the three timing parameters through host-wide sysctl defaults or per-socket setsockopt, according to the control available to the application. Enable SO_KEEPALIVE so that the timing settings take effect on the sockets that need them. Then match TCP_USER_TIMEOUT to the keepalive window. Where the protocol supports them, add gRPC PING, WebSocket ping/pong, or SSH ServerAliveInterval to cover application-layer inactivity as well as idle TCP state.

Datalore’s TCP timeout configuration shows how per-container keepalive defaults can be customized, which is relevant when an agent runs in Docker and host-level sysctl access is restricted. The scope changes, but the timing requirement does not. The container’s effective settings still need to fit the path, and the application still needs keepalive enabled on its connections.

After configuration, use ss -tnop to verify active keepalive timers on the target sockets rather than relying on the presence of the settings alone. Monitoring then shows when connections fail while the agent is running and would otherwise wait without an immediate signal. OneUptime’s observability platform provides connection-level health monitoring that complements kernel tuning by surfacing silent socket failures before they become overnight outages.

Sources

  1. Best Practices for TCP Connection Management on EC2

    Provided the 350-second NAT gateway idle timeout figure cited in the AWS section.

  2. Datalore 2025.6 Help

    Cited as an example of customizing per-container TCP keepalive defaults when host-level sysctl access is restricted.

  3. NAT Gateway TCP idle timeout causes silent connection resets - Microsoft Q&A

    Informed the description of Azure NAT Gateway silently dropping SNAT flow state and responding with RST when traffic resumes.

  4. NAT Gateway Resource

    Provided details on Azure NAT Gateway removing SNAT flow state on idle timeout without sending FIN or RST at expiry.

  5. Troubleshoot configuration  |  Cloud NAT  |  Google Cloud Documentation

    Informed the description of GCP Cloud NAT dropping NAT mappings without warning when the established-idle-timeout expires.

  6. Implementing long-running TCP Connections within VPC networking

    Supported the discussion of long-running TCP connections within VPC networking and how NAT state expires without endpoint notification.

  7. Detecting Dead TCP Connections with Heartbeats and TCP Keepalives

    Informed the recommendation to layer application-level heartbeats over TCP keepalive for proxy-traversing connections.

Priya Venkataraman