Course contentsShow
← Node.js
Lesson 521 of 1,9806. Networking and HTTP FundamentalsFree lesson

Socket Timeouts and Resource Cleanup

Establish automated cleanup routines to prevent memory leaks from abandoned or unresponsive socket connections.

In this lesson, you will learn how to proactively manage memory by enforcing strict expiration policies on unresponsive network connections.

When building networked applications in Node.js, you might encounter "zombie" connections—sockets that are technically open but are no longer sending or receiving data. If these aren't cleaned up, they persist in your server's memory, slowly consuming file descriptors and RAM. This is a common source of memory leaks that can eventually crash your process.

To prevent this, you should treat every incoming socket as a resource with a finite lifespan. Node.js provides a simple mechanism to enforce this: the .setTimeout() method. By setting a threshold, you instruct the socket to trigger a timeout event if there is no activity for a specific duration.

Implementing a Timeout Routine

The most robust approach is to listen for that timeout event and explicitly destroy the connection. This ensures the memory associated with that stream is released back to the system.

const net = require('net');

const server = net.createServer((socket) => {
  // Set a 5-second inactivity threshold
  socket.setTimeout(5000);

  socket.on('timeout', () => {
    console.log('Socket timed out. Cleaning up resources...');
    // Destroy the socket to free memory and file descriptors
    socket.destroy();
  });

  socket.on('data', (data) => {
    // Reset the timer whenever data is received
    socket.setTimeout(5000);
  });
});

server.listen(8080);

In this pattern, every time data flows through the socket, we reset the timer. If the client goes silent for more than 5,000 milliseconds, the server assumes the connection is abandoned and triggers the cleanup logic.

Using socket.destroy() is crucial because it ensures the underlying handle is closed immediately, even if there are pending operations. By integrating this routine, you turn potentially infinite, leaked connections into deterministic, short-lived resources, keeping your event loop and memory footprint healthy under heavy network load.

Key Takeaway: Always pair socket activity with an explicit timeout mechanism to ensure abandoned connections are purged, preventing long-term memory leaks.