How-To Guide

How to Detect and Handle Broken Connections

Detect half-open TCP connections, use keepalive and heartbeats, handle unexpected socket resets, and retry only when it is safe.

On this page

  1. Introduction
  2. Why half-open connections are invisible
  3. Enable keepalive and heartbeats
  4. Classify the failure
  5. Retry only when it is safe
  6. Clean up sockets and pools
  7. Test detection and retry safety
  8. Common pitfalls
  9. Conclusion

Introduction

Networks fail in ways that application code rarely anticipates. A cable is unplugged, a load balancer reboots, a container is rescheduled, and the connection from the peer’s perspective simply stops delivering bytes. If the remote side never sends a FIN or a reset, your end has no signal that anything is wrong; it holds a socket it believes is healthy and writes into a void. These half-open connections are the reason a service can appear to hang while the peer is long gone.

This tutorial explains how to detect broken connections, how keepalive and application heartbeats complement each other, how to classify the failure so retries match the cause, and how to clean up sockets so a dead connection is not returned to a pool. The examples use Node.js and touch WebSockets, but the principles apply to any long-lived connection.

Why half-open connections are invisible

TCP gives a reader no immediate signal when the peer dies without a graceful close. If the host is powered off or the network path is severed, no FIN or RST ever arrives, and the local stack keeps the connection in an established state indefinitely. Writes go into the send buffer and are acknowledged by the local stack, so the writer sees success. Only when the local stack retransmits enough times and the retransmission timeout expires does the connection finally error, and that can take minutes with default settings.

A graceful close is the easy case: the peer sends FIN, the stack reports end-of-stream, and the reader learns immediately. A reset, from a crash that sends RST or a middlebox that drops the flow, is also detectable, though the error is abrupt. The dangerous case is the silent one, and it is precisely the case that keepalive and heartbeats are designed to catch.

Enable keepalive and heartbeats

TCP keepalive sends a probe on an idle connection after a configured interval and declares the connection dead if probes go unanswered. The default interval on many systems is two hours, which is useless for interactive services. Lower it to application-appropriate values, for example probes every thirty seconds and a handful of failures before declaring the connection dead. This detects a dead peer at the transport level without any application awareness.

Application heartbeats are the complement: a small message the application sends and expects an answer to, such as a WebSocket ping and pong. Heartbeats detect not only a dead peer but also a stuck peer that is alive at the TCP level yet not processing. Use both: keepalive catches a vanished host, heartbeats catch a frozen process and also keep middleboxes from dropping an idle flow.

// TCP keepalive on a raw socket
import { connect } from 'node:net';

const socket = connect({ host: 'db.internal', port: 5432, keepAlive: true });
socket.setKeepAlive(true, 30000); // probe after 30s idle

// Application heartbeat over a WebSocket
import WebSocket from 'ws';
const ws = new WebSocket('wss://api.internal/stream');
let lastPong = Date.now();
ws.on('pong', () => { lastPong = Date.now(); });
const hb = setInterval(() => {
  if (Date.now() - lastPong > 45000) { ws.terminate(); return; }
  ws.ping();
}, 15000);

Classify the failure

Distinguish the failure classes so a retry policy can be sensible. A clean close is a normal lifecycle event and usually just means reconnect. A reset often indicates a crash or a proxy dropping an idle flow and is frequently transient. A connect timeout points at the network or an unreachable host. A resolution failure points at DNS. A read timeout on an established connection points at a slow or stuck peer. Each maps to a different response: reconnect, retry with backoff, fail fast, or alert.

Record the error code from the socket layer, because it encodes the class: ECONNRESET, ECONNREFUSED, ETIMEDOUT, EPIPE, ENOTFOUND. Map each to a policy in one place rather than scattering try/catch blocks, so the behavior is consistent and testable.

function classifySocketError(err: NodeJS.ErrnoException): 'reset' | 'refused' | 'timeout' | 'dns' | 'broken-pipe' | 'other' {
  switch (err.code) {
    case 'ECONNRESET': return 'reset';
    case 'ECONNREFUSED': return 'refused';
    case 'ETIMEDOUT': return 'timeout';
    case 'ENOTFOUND': return 'dns';
    case 'EPIPE': return 'broken-pipe';
    default: return 'other';
  }
}

Retry only when it is safe

A broken connection does not tell you whether the request was processed. If the reset arrived after the server committed a side effect, retrying duplicates it. Retry freely when the request is idempotent, such as a GET or a PUT that replaces a known state. For a POST or any non-idempotent action, require an idempotency key so the server can recognize the replay, and retry only then. When in doubt, fail the request to the caller and let a higher layer decide, rather than silently duplicating work.

Bound the retries. A connection that keeps resetting is not a transient blip; it may be a misconfigured proxy or a crash loop. Use exponential backoff with jitter and a small maximum, and surface the persistent failure as an alert rather than retrying forever.

Clean up sockets and pools

A dead connection must not be reused. Return the socket state to the pool as broken so the next request gets a fresh connection, and never hand a half-open socket to a caller. Cancel any in-flight reads and writes on the dead connection, clear its timers, and remove its event listeners so it can be garbage collected. Leaked listeners on repeatedly reconnected sockets are a common slow leak.

When a reconnect loop is involved, add jitter and a maximum backoff so a fleet reconnecting after an outage does not synchronize into a thundering herd. Terminate a WebSocket that stops responding to heartbeats rather than assuming it will recover, and then reconnect with backoff.

function reconnectWithBackoff(connectFn, maxAttempts = 5) {
  let attempt = 0;
  return new Promise((resolve, reject) => {
    const tryOnce = () => {
      connectFn()
        .then(resolve)
        .catch((err) => {
          attempt++;
          if (attempt >= maxAttempts) return reject(err);
          const base = Math.min(30000, 500 * 2 ** attempt);
          const jitter = Math.random() * base;
          setTimeout(tryOnce, base / 2 + jitter);
        });
    };
    tryOnce();
  });
}

Test detection and retry safety

Simulate a half-open connection by abruptly ending reads from a fake peer without sending FIN, and assert that the heartbeat logic detects it within the configured window. Simulate a reset midway through a request and assert that an idempotent request is retried and a non-idempotent one without a key is not. Assert that a dead socket is not returned to the pool. These tests make an otherwise invisible failure mode observable.

Common pitfalls

Relying on default keepalive intervals measured in hours, using no application heartbeat so a stuck peer looks alive, retrying non-idempotent requests after a reset, reusing a dead socket from a pool, and accumulating event listeners across reconnects are the recurring mistakes. Lower the keepalive, add heartbeats, gate retries on idempotency, mark dead sockets, and clean up listeners to address them all.

Conclusion

A connection can be dead while the local side believes it is healthy, so detection must be explicit. Lower TCP keepalive, add an application heartbeat, classify socket errors into a policy, retry only idempotent or keyed requests, and never reuse a dead socket. Self-check by simulating a silent peer and a mid-request reset and asserting detection and retry behavior. Handled deliberately, a broken connection becomes a reconnect instead of a hang.

Sources: RFC 1122: Requirements for Internet Hosts, RFC 6455: The WebSocket Protocol, MDN: TCP keepalive and connection reuse concepts.

FAQ

What is a half-open connection?
A connection where one side has crashed or lost network access but no FIN or RST reached the other side, so the survivor believes it is still open. Writes appear to succeed into a buffer and are never delivered, which is why keepalive and heartbeats are needed to detect it.
Is it safe to retry after a connection reset?
Only if the request is idempotent or carries an idempotency key. A reset can happen after the server received the request, so retrying a POST without a key may create the resource twice.

Related Examples