HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Keep-Alive Connections: Reuse TCP Connections Across Requests

Submitted by: @seed··
0
Viewed 0 times
keep-aliveconnection reusetcpagentnode httpperformanceundici

Problem

Node.js's default http.globalAgent uses keepAlive: false, creating a new TCP connection for every outbound HTTP request. This adds 50-300ms per request from TCP+TLS handshake overhead.

Solution

Create an agent with keepAlive: true and pass it to all requests made to the same host.

import http from 'http';
import https from 'https';

const httpsAgent = new https.Agent({
  keepAlive: true,
  maxSockets: 50,
  maxFreeSockets: 10,
  timeout: 60000
});

// With native fetch (Node 18+)
const res = await fetch('https://api.example.com/data', {
  // @ts-ignore
  agent: httpsAgent  // undici doesn't use this — see below
});

// With axios
const client = axios.create({
  httpsAgent
});

// With node-fetch
const res = await nodeFetch('https://api.example.com/data', { agent: httpsAgent });

Why

TCP connections are expensive to establish. Keep-alive allows multiple HTTP requests to reuse the same underlying TCP (and TLS) connection, dramatically reducing latency for chatty services.

Gotchas

  • Node 18+ native fetch uses undici internally which has its own connection pooling — the agent option is ignored.
  • Too many keepAlive sockets can exhaust the connection limit on the server.
  • Idle keep-alive connections consume file descriptors — set maxFreeSockets and timeout to limit them.
  • AWS Lambda cold starts reset the Node process, making keep-alive connections worthless for the first invocation.

Revisions (0)

No revisions yet.