Detect dead idle TCP connections with an isolated blackhole test

Detect dead idle TCP connections with an isolated blackhole test

Detect dead idle TCP connections with an isolated blackhole test

A TCP connection in a pool can remain ESTABLISHED after sitting idle, yet the next operation on it may hang for a long time. This does not necessarily indicate an application deadlock: if the peer becomes unreachable or an intermediate network path silently drops packets, the local host may receive neither FIN nor RST. The key diagnostic question is not “does the connection still exist?” but “how soon after it fails will the caller receive an error?”

This article creates an isolated, two-endpoint network inside a dedicated server, establishes a connection, and then introduces silent packet loss. The experiment does not change the host’s network interface, default route, or SSH rules. It is intended to validate keepalive strategies for long-lived client connections, not to measure application throughput.

1. Separate the responsibilities of three detection mechanisms

TCP keepalive requires the application to enable SO_KEEPALIVE. Once a connection has been idle for the configured period, the kernel sends probes. It declares the connection dead only after successive probes go unanswered. This checks whether the transport layer can still obtain a response, not whether an application request has completed.

An application heartbeat can check protocol-processing capability—for example, whether the peer can parse a message and return the matching sequence number. A request deadline serves a separate purpose: it limits how long an individual operation may wait. It should be able to time out a request even while data continues to flow over the connection.

A successful keepalive response does not mean an application thread can run. Failed keepalive probes do not prove that the peer process has crashed, either: packet loss along the path can produce the same result.

All three mechanisms can coexist. A long-lived connection pool can use keepalive to remove dead connections, but application calls must not rely solely on kernel timers. This article tests only an established, idle connection with no unacknowledged application data. When unacknowledged data is present, retransmissions and the TCP user timeout mechanism also come into play.

The following commands use Ubuntu Server 24.04 LTS as an example. They require administrator privileges and installed copies of iproute2, nftables, and python3. Run them in the same administrator shell, and first confirm that the ka-client and ka-server namespaces do not already exist. If they do, identify their owner and purpose rather than deleting them.

The two documentation addresses are assigned only inside the namespaces. The listening port, 18080, is an arbitrary choice for this experiment; it does not represent any connection port supplied with a server.

sudo -i
ip netns list

ip netns add ka-client
ip netns add ka-server
ip link add ka-c type veth peer name ka-s
ip link set ka-c netns ka-client
ip link set ka-s netns ka-server

ip -n ka-client addr add 192.0.2.1/30 dev ka-c
ip -n ka-server addr add 192.0.2.2/30 dev ka-s
ip -n ka-client link set lo up
ip -n ka-server link set lo up
ip -n ka-client link set ka-c up
ip -n ka-server link set ka-s up

LAB=$(mktemp -d /tmp/tcp-keepalive.XXXXXX)
chmod 700 "$LAB"

No default route is configured, and the virtual link is not attached to a host bridge. Network namespaces isolate the network stack, but they do not automatically isolate the filesystem. The scripts and logs therefore remain in a dedicated temporary directory on the host.

Create a server that accepts just one connection. After sending a readiness marker, it stays idle and sends no application heartbeats.

cat > "$LAB/server.py" <<'PY'
import socket
import time

with socket.socket() as listener:
    listener.bind(("192.0.2.2", 18080))
    listener.listen(1)
    conn, peer = listener.accept()
    with conn:
        conn.sendall(b"ready\n")
        print("accepted", peer, flush=True)
        time.sleep(120)
PY

3. Explicitly enable keepalive on the socket

The client sets the idle period to 5 seconds, the probe interval to 2 seconds, and the failed-probe count to 3. These values shorten the experiment; they are not production recommendations. In production, tune them to account for normal idle periods, network variability, and the acceptable risk of false positives.

cat > "$LAB/client.py" <<'PY'
import socket
import time

with socket.socket() as conn:
    conn.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5)
    conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 2)
    conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
    conn.connect(("192.0.2.2", 18080))
    if conn.recv(64) != b"ready\n":
        raise RuntimeError("Unexpected greeting")
    print("idle-ready", flush=True)
    started = time.monotonic()
    try:
        data = conn.recv(1)
        print("read-returned", repr(data), flush=True)
    except OSError as exc:
        print("socket-error", exc.errno, str(exc), flush=True)
    finally:
        print("elapsed", time.monotonic() - started, flush=True)
PY

ip netns exec ka-server python3 "$LAB/server.py" \
  > "$LAB/server.log" 2>&1 &
SERVER_PID=$!

sleep 1

ip netns exec ka-client python3 "$LAB/client.py" \
  > "$LAB/client.log" 2>&1 &
CLIENT_PID=$!

sleep 1
cat "$LAB/server.log" "$LAB/client.log"

Proceed only when the server log contains accepted and the client log contains idle-ready. If the connection fails or a script reports an error, stop the experiment first. A server that never started is not evidence that keepalive detected a failure.

This example has only a six-byte readiness message, and the first read is checked against the expected experimental result. For a real protocol, use fixed-length reads or delimiter-based framing; do not assume that a single recv always returns a complete message.

4. Introduce silent packet loss and observe the error

Create a separate ruleset table in the server namespace that drops only inbound TCP packets for the test port. Using drop rather than reject simulates a blackhole that provides no explicit rejection notice.

ip netns exec ka-server nft -f - <<'NFT'
table inet ka_lab {
    chain input {
        type filter hook input priority 0; policy accept;
        tcp dport 18080 counter drop
    }
}
NFT

ip netns exec ka-client ss -tonie
sleep 15
cat "$LAB/client.log"
ip netns exec ka-server nft list table inet ka_lab

While the client is still waiting, ss can show the connection, timers, and socket information. An increasing counter on the server rule confirms that probes reached the point where packet loss was introduced. If you check later, after the connection has been declared dead, it may no longer appear in ss. That does not mean the experiment did not run.

To validate the result, record all three observations: the connection was established, packets hit the drop rule, and the client’s blocking read eventually returned a socket error. The total duration is generally related to the idle period and multiple probes, but simple addition is not an exact timing guarantee. Acknowledgments, scheduling, and the moment packet dropping begins all affect the actual timing.

An empty byte string indicates an orderly shutdown, not the timeout error expected in this experiment. If the operation fails immediately, check whether you accidentally used active rejection. If it keeps waiting, verify that the client is still running, keepalive is enabled, and the rule counter is increasing.

5. Run control tests, then validate the real client

First, clean up the processes and rule from this run, leaving the namespaces in place for further tests:

kill "$CLIENT_PID" "$SERVER_PID" 2>/dev/null || true
wait "$CLIENT_PID" 2>/dev/null || true
wait "$SERVER_PID" 2>/dev/null || true
ip netns exec ka-server nft delete table inet ka_lab

For the first control test, keep the keepalive settings but do not install the drop rule. Run the server and client again, and observe them for longer than the probe cycle described above. The connection should continue waiting rather than close simply because it is idle.

For the second control test, copy the client script and change the value of SO_KEEPALIVE to 0. Establish a new connection and introduce the same packet loss. You should not expect the same error within a short observation window. Record how long you observed it, then terminate the process manually; there is no need to wait indefinitely. Establish a fresh connection for every run to avoid carrying over state from the previous test.

When validating the real client, also check that the settings are applied to every new socket created by the pool, dead connections are removed, and reconnection attempts have a limit. For write operations, a connection error does not prove that the server did not execute the request. Do not replay requests unconditionally; use request identifiers or an idempotency strategy.

At the end of the experiment, terminate the processes from the current run, save any logs you need, and then delete both namespaces. Remove the temporary directory only after confirming that no processes remain:

ip netns pids ka-client
ip netns pids ka-server
ip netns del ka-client
ip netns del ka-server
printf '%s\n' "$LAB"

The final evidence should include the socket parameters, rule counters, error logs, and results from both control tests. This provides a verifiable chain of failure detection, rather than merely a record of changed system defaults with no validation of application behavior.

Frequently asked questions

Do system keepalive settings enable probes on every connection?

No. The application must enable SO_KEEPALIVE on the socket. Per-socket options can also override system defaults, so inspect the application settings and verify them with an isolated packet-loss test.

Does a successful keepalive response prove the application is healthy?

No. It only demonstrates that the remote TCP stack responds. Application heartbeats and independent request deadlines are still needed to detect blocked handlers or database operations.

AMD EPYC 7543P Dedicated Bare Metal Server

From $454/month

Configure a dedicated bare metal server for your workload

AMD EPYC 7543P servers are available with two memory options. The configuration page lists available add-ons and the amount due for the current billing period.