TCP keepalive is a way of sending probe packets that carry no data to an idle TCP connection at set intervals. If the other side acknowledges a probe, the connection counts as alive. If no answer comes, the operating system closes it. NAT devices and firewalls along the path treat these packets as traffic and keep the entry. The trap is in the defaults: Linux and Windows wait two hours before the first probe. This post covers the three settings, the differences between operating systems, setup in Python, Node and curl, and application-level pings.
Why idle connections drop
NAT devices and firewalls keep a table entry for every TCP connection and delete entries that see no traffic for a while. Home routers, corporate firewalls and carrier NAT all do this. We explained how shared NAT on the carrier side works in what is CGNAT.
When the entry is deleted, neither end knows. The connection looks open on both sides. The problem shows up on the first write. The device either rejects the connection with an RST packet or silently drops the packet. RFC 5382 asks NATs not to drop an established TCP connection in less than 2 hours and 4 minutes. In practice, many devices use a much shorter timeout.
In our local test we set up a proxy that closed an idle tunnel after 5 seconds. The two behaviors produced different symptoms:
| Device behavior | First write | First read |
|---|---|---|
| Sends RST | ConnectionResetError (10054 on Windows) | — |
| Drops silently | Appears to succeed | No answer, the read times out |
The silent drop costs more. The application waits without an error. With no read timeout set, it can wait forever. For diagnosing the RST side, see the err_connection_reset error post.
One distinction: HTTP keep-alive reuses a connection for several HTTP requests. TCP keepalive probes an idle connection. The names are similar, the jobs are different.
Three settings and their defaults
Keepalive is turned on per socket and is off by default. The SO_KEEPALIVE option enables it. Three settings control the timing:
TCP_KEEPIDLE: how long the connection stays idle before the first probe.TCP_KEEPINTVL: how long to wait between unanswered probes.TCP_KEEPCNT: how many unanswered probes before the connection is closed.
A dead connection is detected within idle + intvl × cnt at the latest. The defaults vary by operating system:
| System | First probe | Interval | Count |
|---|---|---|---|
| Linux | 7200 s | 75 s | 9 |
| Windows (Vista and later) | 2 hours | 1 s | 10 |
| macOS | Check with sysctl | Check with sysctl | Check with sysctl |
On Linux, the system-wide values are read with sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes. They apply only to sockets that have keepalive turned on. According to the Linux kernel docs, with the defaults a dead connection is probed for about 11 more minutes after the two-hour wait.
On Windows, the system-wide values come from the KeepAliveTime and KeepAliveInterval registry keys. In our test on Windows 11, a newly opened socket read TCP_KEEPIDLE as 7200. On macOS the values are in milliseconds and show up with sysctl net.inet.tcp.keepidle net.inet.tcp.keepintvl net.inet.tcp.keepcnt. On macOS, the per-socket first-probe time is set with the TCP_KEEPALIVE constant.
A two-hour wait is useless against a NAT that deletes entries within minutes. Shorten the values inside your application, per socket.
How far the probe reaches through a proxy
TCP keepalive probes a single TCP connection and does not cross to the far end of the tunnel. When you use a proxy, there are two separate connections. One runs between you and the proxy, the other between the proxy and the target site. The keepalive you enable protects only the first.
The probe carries no data. The proxy server's kernel acknowledges it, not the proxy software. That is why the proxy does not forward the probe to the target. The NAT between the proxy and the target, and the target's own idle timeout, never see it.
Our test showed this. Our local proxy closed any tunnel that saw no data for 5 seconds. On the client, keepalive was on with a 2-second first probe and a 1-second interval. The tunnel still closed. The tunnel of a client that sent a small application message every 2 seconds stayed open.
The same rule applies to SOCKS5 Proxy tunnels. Keepalive keeps the NAT on your network and the path to the proxy alive. End-to-end liveness needs a message at the application layer.
Keepalive in Python
In Python, keepalive is turned on per socket with socket.setsockopt. Requests has no parameter for socket options, but the urllib3 layer underneath accepts socket_options. An adapter applies them to both direct and proxy connections:
import socket
import requests
from requests.adapters import HTTPAdapter
from urllib3.connection import HTTPConnection
# TCP_KEEPIDLE on Linux and Windows, TCP_KEEPALIVE on macOS
IDLE = getattr(socket, "TCP_KEEPIDLE", getattr(socket, "TCP_KEEPALIVE", None))
KEEPALIVE = HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
(socket.IPPROTO_TCP, IDLE, 30), # first probe after 30 s idle
(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10), # 10 s between probes
(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3), # close after 3 unanswered probes
]
class KeepAliveAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
kwargs["socket_options"] = KEEPALIVE
super().init_poolmanager(*args, **kwargs)
def proxy_manager_for(self, proxy, **kwargs):
kwargs["socket_options"] = KEEPALIVE
return super().proxy_manager_for(proxy, **kwargs)
session = requests.Session()
session.mount("http://", KeepAliveAdapter())
session.mount("https://", KeepAliveAdapter())
proxy = "http://user:pass@pr.proxynet.io:8000"
r = session.get("https://example.com",
proxies={"http": proxy, "https": proxy}, timeout=30)In our test, Requests 2.34.2 applied these four options to the proxy socket both for a plain HTTP request and inside a CONNECT tunnel. On Windows, TCP_KEEPIDLE and TCP_KEEPINTVL arrived with Python 3.7 and need Windows 10 version 1709.
httpx has a trap. httpx.HTTPTransport(socket_options=...) works on connections without a proxy. In our test with httpx 0.28.1 and httpcore 1.0.9, once a proxy was set the options were never applied to the proxy socket, and no error was raised. If you use httpx with a proxy, don't rely on keepalive; add an application ping.
Node and curl
In Node, keepalive is set with the keepAlive option when the connection opens, or with setKeepAlive on an open socket:
import net from "node:net";
const socket = net.connect({
host: "pr.proxynet.io",
port: 8000,
keepAlive: true,
keepAliveInitialDelay: 30_000, // first probe after 30 s idle (ms)
});
// can also be called on an open socket
socket.setKeepAlive(true, 30_000);Node sets the interval and probe count itself: according to the docs, the defaults are 1 second and 10 probes. These two values can be changed with the interval and count arguments added in v26.4.0. Older versions accept only the initial delay. Millisecond values are rounded down when converted to seconds.
curl turns keepalive on by default and uses 60 seconds. --keepalive-time sets both the initial wait and the probe interval. --keepalive-cnt arrived in curl 8.9.0 and defaults to 9:
curl --keepalive-time 30 --keepalive-cnt 3 \
-x http://user:pass@pr.proxynet.io:8000 \
https://example.comTo turn keepalive off, use --no-keepalive. In that case --keepalive-cnt has no effect.
Application-level ping
An application ping is a small message sent inside the protocol itself, and it reaches both ends of the tunnel. WebSocket has Ping and Pong frames for this. Under RFC 6455, an endpoint that receives a Ping must answer with a Pong. Database drivers usually do the same with a "ping" or a SELECT 1 query.
Because a ping carries data, the proxy forwards it to the target. Every NAT entry on the path and the target's idle counter are reset. If no answer comes, the application can close the connection right away and open a new one.
| Need | Tool |
|---|---|
| Your NAT and the path to the proxy | TCP keepalive |
| The path between the proxy and the target | Application ping |
| Detecting a dead peer | Both, ping is faster |
| A tool whose code you can't change | System-wide keepalive setting |
Pick a ping interval below the shortest idle timeout on the path. If you don't know it, start with a short interval and check the disconnect logs.
Troubleshooting
If a long connection drops, look at the symptom first. If the first write on an idle connection returns ECONNRESET or 10054, a device on the path deleted the entry and sent an RST. If the write appears to succeed but no answer ever arrives, the packet is being dropped silently.
- Set a read timeout. With a silent drop, only the timeout makes the error visible.
- Confirm that keepalive is on. On Linux,
ss -tnoshows akeepalivetimer next to the connection. - Measure the timeout. Leave the connection idle for 1, 5 and 15 minutes, then write. The point where drops start is the device's timeout.
- If the drop is beyond the tunnel, keepalive is not enough. Add an application ping.
How we tested
We ran the tests on December 1, 2026, on Windows 11 (10.0.26200). Versions: Python 3.13.17, Requests 2.34.2, urllib3 2.6.3, httpx 0.28.1, httpcore 1.0.9, Node v24.22.2, curl 8.23.0. Setup: a local HTTP CONNECT proxy that required a password, and a local echo server as the target. The proxy closed any tunnel that saw no data for 5 seconds in two ways: by sending an RST and by silently stopping forwarding.
We confirmed that the options were applied to the socket with getsockopt and by logging the setsockopt calls. We did not capture the probe packets on the wire. We ran the code examples through the same local proxy.
The bottom line
For long proxy connections, turn keepalive on and bring the first probe down to minutes. Add an application ping for the far end of the tunnel and put a timeout on every read. Above all, remember this: keepalive keeps the connection open, it does not pin the IP. If you need the same exit IP, use a 1-60 minute session with Sticky Proxy.
Sources
- IP Sysctl, tcp_keepalive_time: docs.kernel.org
- SIO_KEEPALIVE_VALS Control Code: learn.microsoft.com
- Node.js net, socket.setKeepAlive: nodejs.org
- RFC 5382, NAT Behavioral Requirements for TCP: rfc-editor.org
- RFC 6455, The WebSocket Protocol, 5.5.2 Ping: rfc-editor.org
Frequently asked questions
Is TCP keepalive the same as HTTP keep-alive?
No. HTTP keep-alive leaves a TCP connection open and reuses it for several HTTP requests. TCP keepalive sends probe packets that carry no data to an idle connection. The first lives at the application layer and cuts the cost of opening a connection per request. The second works at the operating system level and checks whether an idle connection is still alive.
Is TCP keepalive on by default?
No. On most systems it is off per socket, and the application turns it on with SO_KEEPALIVE. Some tools turn it on themselves: curl uses keepalive by default with 60 seconds. Even when it is on, the system default on Linux and Windows is two hours. That is not enough against NAT devices with short timeouts, so shorten it inside the application.
How many seconds should the keepalive time be?
It should be shorter than the shortest NAT or firewall timeout on the path. If you don't know that timeout, a first probe at 30-60 seconds is a reasonable start. A value that is too short creates needless packets, one that is too long does nothing. The most reliable approach is to leave the connection idle for different periods and measure where drops begin.
Does keepalive reach the target site through a proxy?
No. The probe carries no data, and the proxy server's kernel acknowledges it on its own. The connection between the proxy and the target is a separate TCP connection and never sees the probe. Against the idle timeout on the target side, you need an application message, such as a WebSocket Ping frame or a database ping query.
Why does my WebSocket connection drop after a few minutes?
Most likely a NAT, firewall or load balancer on the path is deleting the idle connection. The connection looks open at both ends, then the first message fails or gets no answer. The fix is to send WebSocket Pings regularly. Pick an interval below the shortest timeout on the path, and reconnect if no Pong comes back.
Why don't socket_options work in httpx?
In our test they were not applied when a proxy was set. With httpx 0.28.1 and httpcore 1.0.9, HTTPTransport(socket_options=...) worked on a connection without a proxy. Once a proxy was given, the keepalive options never reached the proxy socket, and no error appeared. If you hold long connections through a proxy on these versions, use an application ping or switch to the socket_options support in Requests and urllib3.




