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

Persistent Connections and Keep-Alive

Optimize server throughput by reusing TCP connections across multiple HTTP request/response cycles.

In this lesson, you will learn how to optimize your server’s throughput by reusing existing TCP connections for multiple HTTP requests rather than creating a new one every time.

The Problem: The Handshake Tax

When a client makes an HTTP request, it first initiates a TCP handshake (a "three-way" conversation to synchronize sequence numbers). If you perform one request per connection, the overhead of this handshake—combined with the delay of tearing the connection down afterward—creates significant latency. As you learned in our lesson on Network Latency, every extra round-trip adds up.

The Solution: Keep-Alive

Persistent connections, often called "Keep-Alive," allow the server and client to keep the underlying TCP socket open after a response is sent. Instead of closing the socket (as seen in our Socket Lifecycle States lesson), the server leaves it idle, waiting for the next request from the same client.

If a second request arrives, the client sends it through the existing, "warm" connection. You skip the handshake, save CPU cycles, and reduce memory allocation on the server.

How it looks in Node.js

In Node.js, the http module handles this automatically for you. When a client sends a request with the header Connection: keep-alive, Node’s server will wait to see if more data follows.

const http = require('http');

const server = http.createServer((req, res) => {
  // The connection remains open after this response
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello! I am keeping this connection open.');
});

// The server automatically manages connection reuse
server.listen(3000);

Why it improves throughput

By reusing a socket, your server avoids the "TCP Slow Start" phase, where a connection must slowly ramp up to maximum speed. Furthermore, because you aren't constantly spawning new sockets, you keep your TCP Backlog usage low, allowing your server to handle more concurrent users without hitting file descriptor limits. It turns a "one-and-done" interaction into a continuous pipe of data exchange.

Key Takeaway: Persistent connections maximize efficiency by eliminating redundant TCP handshakes, allowing your server to process multiple HTTP requests over a single, pre-warmed network path.