In this lesson, you will learn how to configure TCP Keep-Alive to detect silent, "dead" network connections that haven't formally closed.
Why do we need Keep-Alive?
Sometimes, a network connection doesn't "break" cleanly—perhaps a router power-cycles or a cable is unplugged. The OS doesn't receive a FIN packet to signal that the connection is over, leaving your Node.js application waiting indefinitely for data on a socket that will never wake up. These are called "half-open" connections.
TCP Keep-Alive solves this by periodically sending empty "probe" packets on idle connections. If the remote side fails to respond to these probes after a set number of retries, the OS concludes the connection is dead and emits an error, allowing your application to clean up the resource.
Implementing Keep-Alive in Node.js
In Node.js, you can enable this mechanism directly on a net.Socket instance using the setKeepAlive() method. It takes two arguments: a boolean to enable the feature, and an initial delay in milliseconds before the first probe is sent.
const net = require('net');
const client = net.createConnection({ port: 8080 }, () => {
// Enable keep-alive with a 10-second initial delay
client.setKeepAlive(true, 10000);
});
client.on('error', (err) => {
console.log('Connection dead:', err.message);
});
When you set this up, the underlying TCP stack handles the heartbeat. You don't need to manually send data across the wire. If the connection becomes silent, the kernel will send an empty ACK packet. If the remote peer is unreachable, it won't respond, and eventually, the socket will trigger an error event.
This mechanism is essential for persistent communication tunnels (like long-lived web sockets or backend-to-backend data feeds) because it prevents your server from accumulating "ghost" connections that consume file descriptors and memory. By configuring these probes, you ensure that your stream lifecycle accurately reflects the state of the physical network, rather than waiting forever for a dead client.
Key Takeaway: TCP Keep-Alive proactively detects and terminates unresponsive connections by sending background probes, preventing resource leaks caused by half-open network states.