or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-agentkeepalive

Enhanced HTTP/HTTPS agents with keepalive functionality for Node.js applications

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/agentkeepalive@4.6.x

To install, run

npx @tessl/cli install tessl/npm-agentkeepalive@4.6.0

index.mddocs/

Agent Keep Alive

Agent Keep Alive provides enhanced HTTP and HTTPS agents with keepalive functionality for Node.js applications. It extends the native Node.js http.Agent with features like automatic keepalive enablement, socket timeout management, TTL for active sockets, and Nagle's algorithm disabling to improve performance and prevent socket leaks.

Package Information

  • Package Name: agentkeepalive
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install agentkeepalive

Core Imports

// Default export is HttpAgent class
const Agent = require('agentkeepalive');
// Named exports
const { HttpAgent, HttpsAgent, constants } = require('agentkeepalive');

For ES modules:

// Default export is HttpAgent class
import Agent from 'agentkeepalive';
// Named exports
import { HttpAgent, HttpsAgent, constants } from 'agentkeepalive';

TypeScript:

// Default export is HttpAgent class
import Agent, { HttpAgent, HttpsAgent, constants } from 'agentkeepalive';
import type { AgentStatus, HttpOptions, HttpsOptions } from 'agentkeepalive';

Basic Usage

const Agent = require('agentkeepalive');

// Create HTTP agent with default settings
const agent = new Agent({
  keepAlive: true,
  freeSocketTimeout: 4000,
  timeout: 8000,
  socketActiveTTL: null
});

// Use with http.request
const http = require('http');
const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET',
  agent: agent
};

const req = http.request(options, (res) => {
  console.log('reused socket:', req.reusedSocket);
  res.on('data', (chunk) => {
    console.log(chunk.toString());
  });
});

req.end();

// Check agent status
console.log(agent.getCurrentStatus());

Architecture

Agent Keep Alive is built around several key components:

  • HttpAgent: Core HTTP agent class extending Node.js http.Agent with keepalive features
  • HttpsAgent: HTTPS agent class extending HttpAgent with SSL/TLS support
  • Socket Management: Automatic socket lifecycle management with timeout handling
  • Status Monitoring: Real-time agent and socket statistics tracking
  • Browser Compatibility: Noop implementations for browser environments

Capabilities

Module Exports

The package exports structure from index.js:

// Default export is HttpAgent class
module.exports = HttpAgent;
// Named exports
module.exports.HttpAgent = HttpAgent;
module.exports.HttpsAgent = HttpsAgent;
module.exports.constants = constants;

HttpAgent Class

Enhanced HTTP agent with keepalive functionality and socket management.

/**
 * Enhanced HTTP agent with keepalive functionality
 * @param {HttpOptions} options - Configuration options
 */
class HttpAgent extends http.Agent {
  constructor(options?: HttpOptions);
  
  /** Check if agent status has changed since last check */
  readonly statusChanged: boolean;
  
  /** Calculate timeout for socket based on TTL and freeSocketTimeout
   * @returns {number} timeout in ms if should update, <= 0 if should destroy, undefined if no custom timeout */
  calcSocketTimeout(socket: Socket): number | undefined;
  
  /** Determine if socket should be kept alive and set appropriate timeout */
  keepSocketAlive(socket: Socket): boolean;
  
  /** Handle socket reuse, mark request as reused and update counters */
  reuseSocket(...args: any[]): void;
  
  /** Create new connection with proper initialization */
  createConnection(options: NetConnectOpts, cb?: Function): Socket;
  
  /** Create socket for request (inherited from http.Agent) */
  createSocket(req: IncomingMessage, options: RequestOptions, cb: Function): void;
  
  /** Get current agent and socket status information */
  getCurrentStatus(): AgentStatus;
  
  // Deprecated getters (use options instead) - these log deprecation warnings
  get freeSocketKeepAliveTimeout(): number;
  get timeout(): number;
  get socketActiveTTL(): number;
}

interface HttpOptions extends http.AgentOptions {
  /** Enable keepalive (default: true) */
  keepAlive?: boolean;
  /** Timeout for free sockets in milliseconds (default: 4000) */
  freeSocketTimeout?: number;
  /** Deprecated: use freeSocketTimeout instead */
  freeSocketKeepAliveTimeout?: number;
  /** Timeout for active sockets in milliseconds */
  timeout?: number;
  /** Time-to-live for active sockets in milliseconds */
  socketActiveTTL?: number;
}

HttpsAgent Class

HTTPS agent extending HttpAgent with SSL/TLS support.

/**
 * HTTPS agent extending HttpAgent with SSL/TLS support
 * @param {HttpsOptions} options - Configuration options
 */
class HttpsAgent extends HttpAgent {
  constructor(options?: HttpsOptions);
  
  /** Create HTTPS connection with SSL/TLS support */
  createConnection(options: NetConnectOpts, cb?: Function): Socket;
  
  /** Create socket for HTTPS request (inherited from http.Agent) */
  createSocket(req: IncomingMessage, options: RequestOptions, cb: Function): void;
  
  // Inherited from Node.js https.Agent
  getName(options: RequestOptions): string;
  _getSession(sessionId: string): any;
  _cacheSession(sessionId: string, session: any): void;
  _evictSession(sessionId: string): void;
}

interface HttpsOptions extends https.AgentOptions {
  /** Enable keepalive (default: true) */
  keepAlive?: boolean;
  /** Timeout for free sockets in milliseconds (default: 4000) */
  freeSocketTimeout?: number;
  /** Deprecated: use freeSocketTimeout instead */
  freeSocketKeepAliveTimeout?: number;
  /** Timeout for active sockets in milliseconds */
  timeout?: number;
  /** Time-to-live for active sockets in milliseconds */
  socketActiveTTL?: number;
}

Agent Status Monitoring

Real-time monitoring of agent and socket statistics.

interface AgentStatus {
  /** Total number of sockets created */
  createSocketCount: number;
  /** Number of socket creation errors */
  createSocketErrorCount: number;
  /** Number of sockets closed */
  closeSocketCount: number;
  /** Number of socket errors */
  errorSocketCount: number;
  /** Number of socket timeouts */
  timeoutSocketCount: number;
  /** Total number of requests processed */
  requestCount: number;
  /** Current free sockets by hostname */
  freeSockets: { [key: string]: number };
  /** Current active sockets by hostname */
  sockets: { [key: string]: number };
  /** Current pending requests by hostname */
  requests: { [key: string]: number };
}

Request Enhancement

Automatic enhancement of HTTP requests with socket reuse information.

// Properties added to http.IncomingMessage
interface IncomingMessage {
  /** Indicates if the request is using a reused socket */
  reusedSocket?: boolean;
}

Constants

Internal symbols used by the agents for socket management.

interface Constants {
  /** Symbol for tracking current ID counter */
  CURRENT_ID: Symbol;
  /** Symbol for create ID method */
  CREATE_ID: Symbol;
  /** Symbol for socket initialization method */
  INIT_SOCKET: Symbol;
  /** Symbol for HTTPS connection creation method */
  CREATE_HTTPS_CONNECTION: Symbol;
  /** Symbol for tracking socket creation timestamp */
  SOCKET_CREATED_TIME: Symbol;
  /** Symbol for socket name/identifier */
  SOCKET_NAME: Symbol;
  /** Symbol for tracking total request count on socket */
  SOCKET_REQUEST_COUNT: Symbol;
  /** Symbol for tracking finished request count on socket */
  SOCKET_REQUEST_FINISHED_COUNT: Symbol;
}

const constants: Constants;

Browser Compatibility

For browser environments, the package provides noop implementations since native browser APIs don't use agents.

// In browser.js - noop implementations for browser compatibility
function noop(): void;

// CommonJS exports
module.exports = noop;
module.exports.HttpsAgent = noop;

Configuration Options

Socket Timeout Options

  • freeSocketTimeout (default: 4000ms): Timeout for idle sockets in the free pool
  • freeSocketKeepAliveTimeout (deprecated): Use freeSocketTimeout instead
  • timeout: Timeout for active sockets (default: freeSocketTimeout * 2 or 8000ms minimum)
  • socketActiveTTL: Maximum lifetime for active sockets regardless of activity

Socket Behavior Options

  • keepAlive (default: true): Enable HTTP keepalive
  • keepAliveMsecs (default: 1000): Initial delay for TCP keepalive packets
  • All standard Node.js http.AgentOptions and https.AgentOptions

Error Handling

The agents provide enhanced error handling with custom error types and automatic error recovery:

// Socket timeout errors
const error = new Error('Socket timeout');
error.code = 'ERR_SOCKET_TIMEOUT';
error.timeout = timeoutValue; // timeout value in milliseconds

// Handle connection reuse errors
const req = http.request(options, (res) => {
  // handle response
}).on('error', (err) => {
  if (req.reusedSocket && err.code === 'ECONNRESET') {
    // This is a keep-alive race condition - safe to retry
    console.log('Connection reset on reused socket - consider retry');
  }
});

Deprecation Warnings

The package logs deprecation warnings for legacy options:

  • options.keepAliveTimeout → use options.freeSocketTimeout
  • options.freeSocketKeepAliveTimeout → use options.freeSocketTimeout
  • agent.freeSocketKeepAliveTimeout → use agent.options.freeSocketTimeout
  • agent.timeout → use agent.options.timeout
  • agent.socketActiveTTL → use agent.options.socketActiveTTL

Performance Features

  • Nagle's Algorithm Disabled: Automatic socket.setNoDelay(true) for improved performance
  • Socket Reuse Detection: req.reusedSocket property indicates connection reuse
  • Automatic Cleanup: Smart socket timeout and cleanup to prevent memory leaks
  • Connection Reset Handling: Improved resilience to ECONNRESET errors

Usage Examples

HTTPS Agent with Custom Options

const { HttpsAgent } = require('agentkeepalive');

const httpsAgent = new HttpsAgent({
  keepAlive: true,
  freeSocketTimeout: 5000,
  timeout: 10000,
  socketActiveTTL: 60000,
  maxSockets: 50,
  maxFreeSockets: 10,
  // Standard https.AgentOptions
  rejectUnauthorized: true,
  ca: certificateAuthority
});

const https = require('https');
https.globalAgent = httpsAgent;

Monitoring Agent Status

const agent = new Agent();

// Check if status has changed
if (agent.statusChanged) {
  const status = agent.getCurrentStatus();
  console.log('Agent Status:', {
    activeSockets: status.sockets,
    freeSockets: status.freeSockets,
    requests: status.requests,
    totalRequests: status.requestCount,
    errors: status.errorSocketCount
  });
}

Socket Lifecycle Management

const agent = new Agent({
  freeSocketTimeout: 3000,  // 3 seconds for idle sockets
  socketActiveTTL: 30000,   // 30 seconds max lifetime
  timeout: 10000            // 10 seconds for active requests
});

// Agent automatically handles:
// - Socket creation and initialization
// - Timeout management for idle and active sockets
// - Cleanup of expired sockets
// - Error handling and socket destruction