How to Troubleshoot HTTP Agent Exhaustion in Node.js

Production issues in Node.js applications can be challenging to diagnose, especially when different problems exhibit similar symptoms. To make troubleshooting easier, we’re introducing a Node.js Production Troubleshooting Series, where each article focuses on one specific production issue, explores its underlying causes, and demonstrates a practical, step-by-step approach to identifying the root cause.

In this article, we’re focusing on HTTP Agent Exhaustion, a production issue that can easily be mistaken for a socket leak. The Node.js process may still be running normally. CPU and memory can look fine, while users experience slow outbound calls, timeouts, or errors when the application tries to reach an upstream service.

By the time you start investigating, some of the stuck connections may already have been closed, or the application may have restarted. This can make the original problem difficult to see.

Here, outbound `http.get()` calls go through one `http.Agent`. The other side accepts the TCP connection and never responds. The agent cannot reuse those sockets, so it keeps opening new ones, and the Listeners climb with them.

In this blog, we’ll walk through how HTTP Agent Exhaustion shows up in a Node.js application, what typically causes it, and how to trace it back to the exact root cause. We’ll also simulate the issue in a sample application, capture diagnostic data as it happens, and analyze it step by step to pinpoint what’s going wrong.

What is ‘HTTP Agent Exhaustion’ in Node.js?

The `http.Agent` manages connections used by outbound HTTP requests. It keeps sockets around so they can be reused by later requests. That reuse only works when a request finishes. If the remote server accepts a connection but never sends a response, the socket remains in use.

For example, with `maxSockets: Infinity` and no request timeout, there is no limit to how many connections can build up. Every new `http.get()` can create another TCP connection while the previous ones remain stuck.

What Causes ‘HTTP Agent Exhaustion’ in Node.js?

Here is the usual list of causes for the ‘HTTP Agent Exhaustion’ problem.

  1. maxSockets: Infinity – There is no limit on concurrent connections. If the remote server is slow or stops responding, every new request can create another socket.
  2. Peer never responds – The remote server accepts the TCP connection but never completes the HTTP response. The socket stays busy and cannot be reused.
  3. timeout: 0 on the agent or request – With `timeout: 0` on the agent or request, a stuck request can remain open indefinitely.
  4. One shared agent for a noisy upstream – If many parts of the application use the same agent to call an unreliable or slow service, stuck connections can build up quickly.

How to Simulate HTTP Agent Exhaustion in Node.js?

To understand how HTTP Agent Exhaustion appears in the diagnostic data, let’s reproduce the issue using a sample Node.js application.

The following program starts a local TCP server that never writes an HTTP response. Then it fires 15 `outbound http.get()` calls every 500 ms through one Agent with `maxSockets: Infinity` and `timeout: 0`.

``` JS Code (http-agent-exhaustion.js)
const http = require('http');
const net = require('net');
class HTTPAgentExhaustionDemo {
constructor() {
this.server = null;
this.intervalId = null;
this.agent = null;
this.pending = 0;
}
start() {
if (this.intervalId) return;
// Accept TCP, never send an HTTP response.
this.server = net.createServer((socket) => {
socket.on('error', () => {});
});
this.server.listen(0, () => {
const port = this.server.address().port;
this.agent = new http.Agent({
keepAlive: false,
maxSockets: Infinity,
timeout: 0
});
this.intervalId = setInterval(() => {
for (let i = 0; i < 15; i++) {
const req = http.get(`http://127.0.0.1:${port}/`, { agent: this.agent });
req.on('error', () => {});
this.pending++;
}
console.log(`HTTP agent: ${this.pending} outbound requests still open`);
}, 500);
});
}
stop() {
clearInterval(this.intervalId);
if (this.agent) this.agent.destroy();
if (this.server) this.server.close();
}
}
module.exports = new HTTPAgentExhaustionDemo();
```

How to Capture Diagnostic Data for Troubleshooting HTTP Agent Exhaustion

yCrash is a diagnostic tool that captures runtime performance data from a live Node.js process, including CPU usage, event loop lag, worker thread activity, and call stacks, and turns that data into a report that points to the root cause. To set up yCrash for your Node.js application, follow the steps below:

1. Install yCrash

yCrash is available in both Cloud and On-premises versions. Use one of the options below to get started:

  • Cloud Service: Create an account to use the cloud version.
  • On-premises: Register for a 14-day trial and install the yCrash application on your local machine or within the organization’s environment.

2. Set up the yCrash Node.js hook first

Please note that this is a one-time setup. The hook must be loaded into your Node.js application before yCrash can capture the Node.js internal data that matters for diagnosis, things like worker thread CPU, event loop lag, method profiling, and call stacks. To set this up, follow the Hook Mode steps here: Node.js Diagnostic Capture. This hook setup adds very minimalistic, almost zero overhead to your application.

3. Launch yc-360 script

Configure and start the yc-360 script to monitor your Node.js process. The full setup and configuration options specific to your deployment are available here: Micro-metrics Monitoring (M3) Mode

When the yc-360 script detects a problem, it captures  360° diagnostic artifacts (GC log, Event loop lags, Worker threads, CPU Profile, Unhandled rejections, Call stack, Active handles, Process, Storage, Kernel, Network, etc.). It uploads them to the yCrash server automatically. yCrash server analyzes the artifacts using advanced pattern recognition and ML algorithms to identify the root cause of the problem.

How to Analyze HTTP Agent Exhaustion Using the Diagnostic Data

In this section, we’ll see how to analyze HTTP Agent Exhaustion using the diagnostic data captured by yCrash. We’ll start with the incident on the calendar dashboard, check the RCA Summary to understand what’s going on, and then open Active Handles to see TCP sockets climbing under a much larger listener line.

Step 1: Open the incident from the yCrash dashboard

When the yc-360 script detects any performance degradation in the Node.js application, it automatically captures 360° diagnostic data and transmits it to the yCrash server. The yCrash server analyses this data and creates an incident in the yCrash dashboard as shown in the screenshot below. Open that incident from the yCrash calendar dashboard to view the reports.

Fig: yCrash dashboard, incident list view

Step 2: Start with the RCA Summary Page

Before diving into details, let’s start with the RCA Summary. yCrash analyzes the Node.js diagnostic data and brings the key findings together in simple language with their severity levels.

In the RCA Summary, we will focus on two sections:

  • AI Overview
  • Issues in the application and device

AI Overview

At the top of the RCA summary report page, you’ll see an AI Overview section. It gives you an AI-generated summary of the incident, which would help even a non-technical person understand the root cause of the problem. Within the AI Overview section, below the AI summary, you can also click on the ‘Dive Deeper in AI Mode‘ button to open a chat window to ask any question to the AI about this incident.

Fig: RCA Summary highlighting the AI Overview

As shown in the AI Overview above, an event listener leak, with listeners increasing from 17,942 to 30,711. It also shows TCP sockets increasing from 2,100 to 3,600.

For this incident, the socket increase is the more important clue. Sockets increased by 1,500, while listeners increased by 12,769. That works out to roughly eight listeners per socket, which is expected when outbound HTTP requests remain open.

Issues in application and device

Fig: RCA Summary highlighting the issues in application and device

As shown in the above screenshot, 3 application-level issues and 2 device-level issues are reported. The one that matters for HTTP Agent Exhaustion is:

  • TCP socket leak

The Fatal Event listener leak is a secondary problem and is not the root cause. The ms package warning does not open sockets. The device notes (system CPU above user CPU, about 19% memory) are what you get when the kernel is holding thousands of connections. App Memory on this capture is about 1% and App CPU is about 6%.

Step 3: Confirm outbound sockets on Handle Growth

Click the “details here” link present at the end of the “TCP socket leak” problem on the RCA Summary page. It takes you to the Active Handles & Requests Growth Trend section of the Node.js Internals report.

Fig: Active Handles showing TCP sockets at 3,600 under a 30,711 listener line

In the last sample, the number of TCP sockets has reached 3,600, while Event listeners have grown to 30,711.

Both TCP sockets and event listeners continue to increase, while pipes, TCP servers, and timers remain mostly flat.

A typical `net.Socket` leak usually has roughly two listeners per socket. Here, the ratio is much higher. That is because each `http.get()` keeps request, response, and agent callbacks attached to the connection.

This listener-to-socket ratio is an important clue. It helps distinguish this problem from the Socket Leak example, even though both issues may look similar in the Issues list.

How to Fix HTTP Agent Exhaustion in Node.js

The following are the potential solutions for this issue:

  1. Cap the agent. Set `maxSockets` to something your upstream can actually serve. Infinity is how this capture got to 3,600 sockets.
  2. Put a timeout on the request and on the agent. A hung GET must die so the socket can close.
  3. Do not share one unbounded agent across every outbound host. Use a dedicated agent per upstream if you need isolation.
  4. When Issues lists both a listener leak and a TCP socket leak, read the TCP number and the listener-to-socket ratio before you start removing `EventEmitter.on()` calls.

Conclusion

Diagnosing and identifying the root cause of HTTP Agent Exhaustion can be challenging when the listener row is listed first. In this example, the diagnostic data was captured using the yc-360 script and analyzed using the yCrash server, which helped correlate the Fatal TCP climb with outbound http.get() through one Agent.

The analysis traced the issue to sockets that stayed checked out because the peer never responded. TCP sockets went from 2,100 to 3,600. Listeners followed, about eight for each socket.

Capping `maxSockets` and putting a timeout on hung GETs addresses the underlying problem and helps prevent the issue from recurring.

Mahesh Devda
Mahesh Devda
Articles: 19

Share your Thoughts!