agent.maxFreeSockets Property in Node.js

The agent.maxFreeSockets property defines the maximum number of sockets that can be kept open in the free state for connection reuse. This is part of Node.js HTTP agent configuration and helps optimize HTTP connection pooling.

Syntax

agent.maxFreeSockets = number

Parameters

  • number - Specifies the maximum number of sockets that can remain open in the free state. Default value is 256.

Understanding Free Sockets

Free sockets are HTTP connections that have completed their current request but remain open for potential reuse. This improves performance by avoiding the overhead of establishing new connections for subsequent requests to the same host.

Example with Built-in HTTP Agent

const http = require('http');

// Create a custom agent with maxFreeSockets configuration
const agent = new http.Agent({
    maxSockets: 50,
    maxFreeSockets: 5,
    keepAlive: true
});

console.log("Default maxFreeSockets:", http.globalAgent.maxFreeSockets);
console.log("Custom agent maxFreeSockets:", agent.maxFreeSockets);

// Modify the maxFreeSockets property
agent.maxFreeSockets = 10;
console.log("Updated maxFreeSockets:", agent.maxFreeSockets);
Default maxFreeSockets: 256
Custom agent maxFreeSockets: 5
Updated maxFreeSockets: 10

Example with agentkeepalive Module

// Using agentkeepalive module for advanced keep-alive features
const http = require('http');

// Note: This example shows the concept
// In practice, you would install: npm install agentkeepalive
const AgentKeepAlive = require('agentkeepalive');

const keepaliveAgent = new AgentKeepAlive({
    maxSockets: 100,
    maxFreeSockets: 10,
    timeout: 60000,
    freeSocketTimeout: 30000,
});

console.log("Max free sockets:", keepaliveAgent.maxFreeSockets);
console.log("Agent status:", keepaliveAgent.getCurrentStatus());

Impact on Performance

maxFreeSockets Value Memory Usage Connection Reuse Performance
Low (1-5) Lower Limited Slower for multiple requests
High (50+) Higher Better Faster for multiple requests

Key Points

  • Free sockets reduce connection establishment overhead for repeated requests

  • Higher values improve performance but consume more memory

  • Must balance between performance gains and resource consumption

  • Works in conjunction with keepAlive: true setting

Conclusion

The maxFreeSockets property is essential for optimizing HTTP connection pooling in Node.js applications. Set it based on your application's request patterns and memory constraints to achieve optimal performance.

Updated on: 2026-03-15T23:19:00+05:30

564 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements