Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
VGSources
Blog

How to Fix Connection Timeouts on a Node.js App

A practical Node.js timeout guide: distinguish inbound server timers from outbound ETIMEDOUT failures, inspect version-specific defaults, align proxies and keep-alive settings, and add abortable client deadlines.
Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fix a Node.js connection timeout by first identifying which side timed out. An incoming request is governed by the Node HTTP server’s keepAliveTimeout, headersTimeout, and timeout settings. An ETIMEDOUT error usually comes from an outbound connection to another service, so changing those server settings will not help. Check the exact Node.js version, inspect the active values, align them with your load balancer, and then test DNS, routing, firewall rules, and the client library’s connect behavior.

Start by locating the timeout

“Connection timeout” describes several different failures. The fastest fix depends on whether your app is accepting a connection or creating one.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Symptom Likely direction First place to look
408 Request Timeout in the response, followed by a closed connection Inbound request to your Node server headersTimeout or the server socket timeout
Clients receive a 502 or 504 from a proxy or load balancer Inbound request, with an intermediary closing an idle connection Node keep-alive settings versus the intermediary’s idle timeout
ETIMEDOUT while calling an API, database, queue, or other host Outbound connection from Node Destination reachability, DNS, firewall rules, security groups, and the client’s connect timeout
ECONNRESET after an otherwise successful request Either side closed an established socket Keep-alive and idle-timeout mismatches, proxy behavior, or a remote restart

Capture the complete error, not just the word “timeout.” Record the operation, destination hostname and port, HTTP status if one exists, elapsed time, Node version, and whether the process is a server, a client, or both. A timeout while your route calls another service is an outbound problem even though the route itself is hosted by a Node server.

Check the Node.js version and effective settings

Timeout defaults are version-dependent. Do not copy a value from a guide written for another release line without checking your runtime.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
  1. Print the runtime used by the deployed process:

    node --version
  2. Log the values on the actual server object during startup:

    const http = require('node:http');
    
    const server = http.createServer(requestHandler);
    console.log({
      node: process.version,
      keepAliveTimeout: server.keepAliveTimeout,
      headersTimeout: server.headersTimeout,
      timeout: server.timeout
    });
    server.listen(process.env.PORT || 3000);
  3. Check the process manager, container image, and hosting platform as well. A local shell may use a different Node binary than production.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The HTTPS documentation lists a keepAliveTimeout default of 5,000 milliseconds and a headersTimeout default of 60,000 milliseconds. In Node v10.14.0, the documented headersTimeout default was 40,000 milliseconds. The server.timeout default changed from 120 seconds to 0 (no timeout) in Node v13.0.0. A value of 0 can leave an idle socket open indefinitely, so treat it as a deliberate capacity decision rather than proof that requests cannot time out.

Understand the three inbound server timers

keepAliveTimeout: idle persistent connections

This controls how long an HTTP keep-alive connection may remain idle after a response before Node closes it. Node also adds a buffer when calculating the socket timeout; the buffer is intended to reduce avoidable ECONNRESET errors when a client or intermediary reuses a socket near its expiration.

headersTimeout: time to receive request headers

This limits the period in which the server waits for complete request headers. It protects the process from connections that open but send headers too slowly. If the limit is exceeded, Node sends a 408 response and terminates the connection.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

timeout: socket inactivity

This is the inactivity timeout for an established socket. It is separate from the time required to receive headers and from the idle keep-alive period. When it expires, the connection is considered inactive; your application should still handle the socket or request timeout events according to the behavior you want.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Increasing every timer is not a universal fix. Longer limits can accommodate slow clients, but they also allow more sockets to occupy memory and file descriptors. Set a value because your workload requires it, and monitor open connections after changing it.

Apply a safe server-side configuration

Set the properties immediately after creating the server and before accepting traffic. The following example is suitable for an HTTP server; use require('node:https') or import https from 'node:https' with the same properties for HTTPS.

const http = require('node:http');

function requestHandler(req, res) {
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ ok: true }));
}

const server = http.createServer(requestHandler);

// Example policy: choose values from your proxy and workload, not blindly.
server.keepAliveTimeout = 65_000;
server.headersTimeout = 66_000;
server.timeout = 120_000;

server.on('timeout', (socket) => {
  // Decide whether to destroy the inactive socket or let application code act.
  socket.destroy();
});

server.listen(3000, () => {
  console.log('Listening on 3000', {
    keepAliveTimeout: server.keepAliveTimeout,
    headersTimeout: server.headersTimeout,
    timeout: server.timeout
  });
});

The 65,000/66,000 millisecond pair is an example for an intermediary with a 60-second idle timeout. It is not a universal Node recommendation. The important relationship is that the intermediary should not abandon an idle connection before Node does, and headersTimeout should remain slightly above keepAliveTimeout when you use this pattern. Confirm the actual idle value for your reverse proxy, ingress, or load balancer before selecting numbers.

Keep the assignment order correct

Changing a server after it has already accepted traffic can leave existing sockets with their previous timers. Configure the listener during startup, deploy the change, and recycle old workers if you need every connection to use the new policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Do not confuse request duration with socket inactivity

A long-running handler can still be active while the socket is quiet. If your application streams progress, send data or heartbeats according to the protocol and intermediary requirements. If it performs a long computation without producing output, use an application-level deadline and cancellation rather than simply making all transport timers unlimited.

Align Node with a proxy or load balancer

A proxy can close a connection independently of Node. If its idle timeout is shorter than the time your server keeps a connection available, the proxy may return a 502 or 504, or a reused connection may fail with ECONNRESET. Conversely, if Node closes first, clients may observe a reset while the proxy still considers the backend usable.

  1. Find the configured idle timeout for every hop: CDN, ingress, reverse proxy, service mesh, cloud load balancer, and the Node process.
  2. Choose an intentional order. For ordinary keep-alive traffic, set Node’s keep-alive period longer than the intermediary’s idle period when the intermediary is expected to retire the connection first, or set both according to the intermediary’s documented reuse behavior.
  3. Keep the header-waiting limit above the keep-alive value when using the common buffered configuration.
  4. Roll out to one instance and inspect 502, 504, reset, and socket-count metrics before changing the whole fleet.
  5. Test a connection that remains idle, then sends a new request just before and just after each boundary.

Do not infer a load-balancer timeout from a single failed request. A 504 may represent an upstream response deadline, while a 502 may indicate a reset, protocol error, or unhealthy backend. Read the intermediary’s access and health-check logs alongside Node logs.

Fix outbound ETIMEDOUT failures

An outbound timeout means your process could not complete some client operation. The server timers above do not control the connection attempt to another host.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the destination from the same runtime environment

  • Resolve the hostname inside the same container, VM, or network namespace:
getent hosts api.example.test
nslookup api.example.test
  • Check TCP reachability to the destination port:
nc -vz api.example.test 443
  • For an HTTPS endpoint, make a request with the same proxy and certificate environment:
curl -v --connect-timeout 10 https://api.example.test/health

These commands distinguish a DNS failure, a blocked route, and a service that accepts TCP but does not answer at the application layer. A successful check from your laptop does not prove that the production subnet, security group, egress gateway, or container can reach the host.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Check network policy and address selection

Review outbound firewall rules, cloud security groups, network ACLs, proxy variables, and the destination’s allowlist. If DNS returns both IPv6 and IPv4 addresses, an unreachable IPv6 route can create an apparent timeout before fallback. Test each address family in the production environment and configure the client or network path deliberately rather than assuming the order is harmless.

Give the operation an explicit deadline

Use a deadline that covers the whole operation and abort it when it expires. The following native HTTPS example applies one deadline to DNS, connection establishment, response headers, and body consumption:

const https = require('node:https');

function getJson(url, deadlineMs = 10_000) {
  return new Promise((resolve, reject) => {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), deadlineMs);

    const request = https.get(url, { signal: controller.signal }, (response) => {
      let body = '';
      response.setEncoding('utf8');
      response.on('data', (chunk) => { body += chunk; });
      response.on('end', () => {
        clearTimeout(timer);
        if (response.statusCode < 200 || response.statusCode >= 300) {
          reject(new Error(`Upstream HTTP ${response.statusCode}`));
          return;
        }
        try {
          resolve(JSON.parse(body));
        } catch (error) {
          reject(error);
        }
      });
    });

    request.on('error', (error) => {
      clearTimeout(timer);
      reject(error);
    });
  });
}

Adapt the equivalent cancellation option for your HTTP, database, or queue library. A client request’s timeout event generally signals socket idleness; it does not automatically cancel the request. Abort or destroy the request explicitly, and clear the timer on every success and failure path.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate connect, response, and total deadlines

One large timeout hides which phase is slow. Where your client library supports it, set separate budgets for DNS, TCP/TLS connection, time to first byte, and total response time. If it does not, wrap the operation in an abortable total deadline and record phase timestamps yourself. Do not assume an http.Agent timeout covers connection establishment: the documented behavior applies after the socket connects.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use keep-alive agents deliberately for outbound calls

Connection pooling reduces handshake overhead, but a pooled socket may be closed by the remote service or intermediary while the agent still has it available. Configure the agent according to the remote idle policy, handle socket errors, and retry only operations that are safe to repeat.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
const https = require('node:https');

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

https.get('https://api.example.test/data', { agent }, (res) => {
  res.resume();
}).on('error', (error) => {
  console.error('upstream request failed', {
    code: error.code,
    message: error.message
  });
});

The pool limits shown are workload examples, not universal capacity settings. Size them against upstream rate limits, local file-descriptor limits, and concurrency. A retry with exponential backoff and jitter can help with transient resets, but retries amplify load during a real outage. Never retry a non-idempotent write unless the API provides an idempotency key or equivalent guarantee.

Interpret common timeout symptoms

408 Request Timeout

Node emits a 408 and closes the connection when the header-waiting or socket-inactivity threshold is exceeded. Inspect slow clients, request-header size, proxy buffering, and whether a security scanner is opening connections without completing requests. Raising the timer may mask an attack or resource leak; prefer limits appropriate to the clients you actually support.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ETIMEDOUT

Treat this as an outbound investigation first. Log the hostname, resolved address when available, port, elapsed milliseconds, phase, and error code. Then test reachability from the application environment and inspect egress controls. Changing keepAliveTimeout cannot repair a blocked route.

ECONNRESET

Determine which side reset the socket. Compare Node’s keep-alive policy with the proxy and upstream idle policies, inspect deployment restarts, and check whether a pooled client socket was reused after the peer closed it. A reset immediately after a known idle boundary strongly suggests a timer mismatch; a reset during active transfer points to a different failure.

502 or 504 from an intermediary

Read the intermediary’s reason field and timing fields. Distinguish backend connect failure, upstream response deadline, idle disconnect, and health-check failure. Correlate the request identifier across proxy and Node logs before changing any timeout.

Add diagnostics before changing limits

Every timeout log should answer four questions: which operation was running, which phase exceeded its budget, which peer was involved, and whether cancellation completed. Include a correlation ID, route or job name, Node version, configured timeout policy, elapsed time, and error code. Avoid logging authorization headers, cookies, request bodies, or credentials.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Track active sockets, in-flight outbound requests, timeout counts by destination, response latency percentiles, resets, and event-loop delay. A rising socket count after setting server.timeout to zero is a capacity warning even if user-facing errors disappear.

Version and deployment checklist

  1. Pin and record the Node.js major and minor version used in production.
  2. Print effective server timeout values at startup rather than relying on presumed defaults.
  3. Document every intermediary’s idle, header, connect, and response deadlines.
  4. Test inbound slow headers, idle keep-alive reuse, and long responses in a staging environment.
  5. Test outbound DNS failure, blocked port, refused connection, delayed headers, and a peer that closes an idle socket.
  6. Verify that aborting a timed-out request releases sockets and does not leave work running in the background.
  7. Deploy to a small instance group, watch resets and open-socket metrics, then expand.
  8. Recheck the policy whenever Node, the proxy, the load balancer, or the client library changes.

Practical decision guide

What you observe Action
408 while clients upload slowly Review header and inactivity limits, proxy buffering, and client requirements; raise only the specific limit needed.
502 after an idle period behind a 60-second intermediary Align Node keep-alive and header settings with that 60-second policy, then verify with boundary tests.
ETIMEDOUT before any response exists Test DNS, route, firewall, security group, proxy, and connect handling from the production environment.
Timeout event fires but work continues Abort or destroy the request explicitly and make the operation cancellation-safe.
Errors began after a Node upgrade Compare the new runtime’s documented defaults with the old version and set intentional values explicitly.

The reliable fix is therefore not “increase the Node timeout.” Identify the direction and phase, verify the runtime’s actual defaults, choose limits that match every network hop, and enforce cancellation for outbound work. That approach resolves genuine timeout mismatches without turning slow or unreachable dependencies into permanently occupied sockets.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.