How to Configure Keep-Alive in Axios for Node.js
Configuring HTTP keep-alive connections in Axios for Node.js allows
your application to reuse underlying TCP connections across multiple
HTTP/HTTPS requests. By default, Node.js terminates connections after
each request, introducing latency and unnecessary resource overhead.
This guide explains how to enable and configure persistent keep-alive
connections in Axios using Node.js native http and
https agents.
Why Enable Keep-Alive?
When making repeated requests to the same server, establishing a new TCP connection (and performing the TLS handshake for HTTPS) for every request wastes CPU and adds network latency. Enabling HTTP Keep-Alive keeps the socket open, allowing multiple requests to share the same connection.
Implementing Keep-Alive in Axios
Axios relies on Node.js's built-in http and
https modules to dispatch network requests on the server
side. To enable keep-alive, create custom instances of
http.Agent and https.Agent with the
keepAlive option set to true, then pass them
to an Axios instance.
const axios = require('axios');
const http = require('http');
const https = require('https');
// 1. Create HTTP and HTTPS agents with keep-alive enabled
const httpAgent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 1000, // Duration (ms) to keep idle sockets alive
maxSockets: 50, // Max simultaneous sockets allowed per host
maxFreeSockets: 10, // Max free sockets to keep open in idle state
timeout: 60000 // Socket timeout in milliseconds
});
const httpsAgent = new https.Agent({
keepAlive: true,
keepAliveMsecs: 1000,
maxSockets: 50,
maxFreeSockets: 10,
timeout: 60000
});
// 2. Create an Axios instance using the custom agents
const apiClient = axios.create({
httpAgent,
httpsAgent,
baseURL: 'https://api.example.com'
});
// 3. Make requests using the configured instance
async function fetchData() {
try {
const response = await apiClient.get('/data');
console.log(response.data);
} catch (error) {
console.error('Request failed:', error.message);
}
}
fetchData();Key Configuration Options
When defining custom agents, adjust the following parameters based on your application's concurrency and workload:
keepAlive(boolean): Must be set totrueto reuse sockets.keepAliveMsecs(number): The initial delay in milliseconds for TCP Keep-Alive packets.maxSockets(number): The maximum number of concurrent open sockets allowed per origin. Defaults toInfinityin Node.js.maxFreeSockets(number): The maximum number of sockets left open in an idle state waiting for new requests. Defaults to256.timeout(number): Socket inactivity timeout in milliseconds before an idle socket is destroyed.
Global Axios Configuration
If you prefer applying keep-alive globally across all Axios requests
instead of creating an instance, assign the agents to
axios.defaults:
axios.defaults.httpAgent = httpAgent;
axios.defaults.httpsAgent = httpsAgent;Using custom agents with keep-alive significantly reduces connection latency, minimizes DNS lookups, and enhances throughput for high-volume Node.js services.