Axios Connection Pooling with http and https Agent

This article explores the critical role of Node.js's native http.Agent and https.Agent in managing connection pooling and socket reuse within the Axios HTTP client. You will learn how enabling persistent connections through keepAlive optimizes network performance, eliminates latency caused by repetitive TCP/TLS handshakes, prevents socket exhaustion in high-concurrency applications, and how to properly configure custom agents in Axios.

What Are http.Agent and https.Agent?

In Node.js, http.Agent and https.Agent are built-in classes responsible for managing the lifecycle, reuse, and pooling of underlying TCP sockets for outgoing HTTP and HTTPS requests. By default, every new network request creates a new socket connection and tears it down immediately after the response is received unless explicitly instructed to maintain it.

When configured as a connection pool, an Agent holds open idle sockets so that subsequent requests to the same origin (host and port) can reuse an existing connection rather than establishing a new one from scratch.

Why Connection Pooling Matters in Axios

Axios relies on the native Node.js HTTP/HTTPS modules when executed in a server environment. Without a persistent connection pool, high-volume Axios traffic introduces several performance bottlenecks:

How to Configure Connection Pooling in Axios

Axios provides the httpAgent and httpsAgent configuration options to attach custom agent instances.

const axios = require('axios');
const http = require('http');
const https = require('https');

// Create persistent agents for HTTP and HTTPS
const httpAgent = new http.Agent({
  keepAlive: true,
  maxSockets: 50,
  maxFreeSockets: 10,
  timeout: 60000
});

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

// Attach agents to a global Axios instance
const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  httpAgent,
  httpsAgent,
  timeout: 10000 // Request timeout in ms
});

module.exports = apiClient;

Key Agent Configuration Options

When configuring http.Agent or https.Agent for Axios, the following options control connection behavior:

Best Practices for Axios Agents