Networking
TCP Keepalive Tuning on Linux: Stop Idle Connections From Silently Dying
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيA database connection that worked a minute ago suddenly hangs. An SSH session freezes after you step away for coffee. A worker waits forever for a reply from a peer that rebooted hours ago. These problems usually share one cause: an idle TCP connection that was silently dropped somewhere in the middle, while both ends still believe it is alive. TCP keepalive is the built-in mechanism for detecting that situation. This guide explains how it works, why the Linux defaults are rarely what you want, and how to tune it system-wide and per application.
What TCP keepalive does
TCP has no built-in heartbeat. If neither side sends data, an established connection can sit idle indefinitely without a single packet crossing the wire. That is efficient, but it means a crashed peer, an unplugged cable or a firewall that forgot the connection goes unnoticed until you next try to send something.
When keepalive is enabled on a socket, the kernel sends a small probe after a period of idleness. The probe is an empty segment the peer must acknowledge. If the peer answers, the timer resets. If several probes go unanswered, the kernel declares the connection dead and the application gets an error instead of waiting forever.
As a useful side effect, the probes are real traffic, so they also refresh idle timers in NAT gateways, stateful firewalls and load balancers along the path.
The Linux defaults
Three kernel parameters control the behavior:
| Parameter | Default | Meaning |
|---|---|---|
net.ipv4.tcp_keepalive_time | 7200 | Seconds of idleness before the first probe |
net.ipv4.tcp_keepalive_intvl | 75 | Seconds between unanswered probes |
net.ipv4.tcp_keepalive_probes | 9 | Unanswered probes before giving up |
With these values a dead peer is detected after 7200 + 75 x 9 = 7875 seconds, a little over two hours. Many middleboxes forget idle connections far sooner than that, so the first probe often arrives after the path has already been broken.
Two important details: despite the ipv4 in the name, these settings also apply to IPv6 TCP sockets, and they only affect sockets where the application turned on SO_KEEPALIVE. Changing the sysctl does nothing for programs that never enable keepalive.
Step 1: Inspect current values and live timers
sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes
ss -tno state established | grep keepaliveIn the ss output, sockets with keepalive enabled show a timer such as timer:(keepalive,1h59min,0). If your database or app connections do not show one, keepalive is off for them.
Step 2: Set sensible system-wide values
A common, conservative choice for servers is to probe after 10 minutes of idleness and give up after about 5 more minutes:
sudo tee /etc/sysctl.d/80-tcp-keepalive.conf <<'EOF'
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 60
net.ipv4.tcp_keepalive_probes = 5
EOF
sudo sysctl --systemIf you know a NAT device or load balancer between your services drops idle flows after, say, 5 minutes, set tcp_keepalive_time comfortably below that, for example 240. Avoid very aggressive values such as a few seconds: they add needless traffic on servers with many connections and can kill connections during short network hiccups.
Step 3: Enable keepalive in your applications
System values only matter where keepalive is switched on. Common services:
Nginx: on a listening socket, so_keepalive takes idle, interval and count:
listen 443 ssl so_keepalive=10m:60s:5;For upstream connections, proxy_socket_keepalive on; enables keepalive on sockets to your backend using the system values.
PostgreSQL (postgresql.conf):
tcp_keepalives_idle = 300
tcp_keepalives_interval = 30
tcp_keepalives_count = 5Client libraries usually accept the same options in the connection string, for example keepalives_idle=300 with libpq.
Redis: tcp-keepalive 300 in redis.conf (300 seconds is the default in modern versions).
SSH: OpenSSH has two mechanisms. TCPKeepAlive yes uses kernel TCP keepalive, while ClientAliveInterval on the server and ServerAliveInterval on the client send encrypted application-level messages, which are more reliable through firewalls. In /etc/ssh/sshd_config:
ClientAliveInterval 60
ClientAliveCountMax 3On your own computer, add ServerAliveInterval 60 under the relevant Host entry in ~/.ssh/config.
Your own code can enable keepalive per socket. In Python on Linux:
import socket
s = socket.create_connection(("db.internal", 5432))
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 300)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)Keepalive is not the same as HTTP keep-alive
HTTP keep-alive (persistent connections) means reusing one TCP connection for several HTTP requests, controlled in Nginx by keepalive_timeout. TCP keepalive is a liveness check on any idle TCP connection. They share a name but solve different problems, and you can use either without the other. For broader troubleshooting of hanging or refused connections, see our guide on connection timeouts.
Quick checklist
- Confirm which connections actually have keepalive enabled with
ss -tno. - Lower
tcp_keepalive_timebelow the shortest idle timeout on your network path. - Enable keepalive explicitly in databases, proxies and client libraries.
- Prefer application-level heartbeats (SSH alive messages, WebSocket pings) where available.
- Document your values so the next person tuning the server understands why they were chosen.
These changes are small and reversible, so they are worth applying on every new server you deploy.
FAQ
Will TCP keepalive keep my SSH session alive through a NAT router?
Usually yes, as long as the probe interval is shorter than the router's idle timeout. SSH's own ServerAliveInterval is often more reliable, because some devices ignore empty TCP probes but must pass encrypted application data.
Does keepalive add noticeable load?
No. A probe is a tiny packet sent only on idle connections, at most once per interval. Even thousands of connections with a 10-minute idle time create negligible traffic.
How is keepalive different from TCP_USER_TIMEOUT?
Keepalive detects dead peers on idle connections. TCP_USER_TIMEOUT limits how long sent data may remain unacknowledged before the connection is closed, which covers connections that are actively sending. Many applications benefit from setting both.