How to fix Error: ETIMEDOUT (Operation timed out) in Node.js

Node.jsINTERMEDIATEMEDIUMUpdated Dec 9, 2025ยท 185 views

ETIMEDOUT occurs when a network operation in Node.js does not complete within the specified or default time limit. This typically happens during HTTP requests, database connections, or socket operations when the remote server fails to respond in time.

Quick fix

Fixes ETIMEDOUT

const http = require('http');

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/data',
  timeout: 10000 // 10 seconds
};

const req = http.get(options, (res) => {
  // Handle response
});

req.on('timeout', () => {
  req.destroy();
  console.error('Request timed out');
});

req.on('error', (err) => {
  if (err.code === 'ETIMEDOUT') {
    console.error('Connection timed out');
  }
});
  1. Configure explicit timeout values
  2. Enable HTTP Keep-Alive for connection reuse
  3. Implement retry logic with exponential backoff
  4. Check firewall and network configuration
node.js โ€” error
const http = require('http');
const options = {
hostname: 'api.example.com',
port: 80,
path: '/data',
timeout: 10000 // 10 seconds
};
const req = http.get(options, (res) => {
// Handle response
});
req.on('timeout', () => {
req.destroy();
console.error('Request timed out');
});
req.on('error', (err) => {
if (err.code === 'ETIMEDOUT') {
console.error('Connection timed out');
}
});
Error: ETIMEDOUT (Operation timed out)

What this error means

ETIMEDOUT is a timeout error that signals a network operation failed because the connected party did not properly respond within the allocated time period. This error is emitted by Node.js when attempting to establish or maintain a connection that exceeds the timeout threshold. The error typically occurs in the network layer when Node.js is unable to complete a TCP connection, send data, or receive a response from a remote server. Unlike connection refused errors, ETIMEDOUT means the connection attempt was made but no response was received before the timeout expired. This is one of the most common networking errors in Node.js applications, especially those making HTTP requests to external APIs, connecting to databases, or performing other I/O operations over unreliable networks.

Typical symptoms

  • HTTP requests hang and eventually fail with ETIMEDOUT
  • Application logs show "Error: connect ETIMEDOUT" followed by an IP address
  • API calls to external services fail intermittently or consistently
  • Database connection attempts time out during application startup
  • Axios or fetch requests throw ETIMEDOUT or ECONNABORTED errors
  • AWS Lambda functions fail with timeout errors when calling external APIs
  • Socket connections fail to establish within the expected timeframe

Common causes

  1. Remote server is overloaded and cannot respond within the timeout period
  2. Network connectivity issues between client and server (latency, packet loss)
  3. Firewall or proxy blocking outbound connections
  4. DNS resolution delays preventing timely connection establishment
  5. Default timeout settings too aggressive for slow networks or distant servers
  6. Server-side keepAliveTimeout lower than client timeout causing premature disconnections
  7. Too many concurrent requests exhausting available sockets
  8. Cloud environment networking restrictions (security groups, NACLs)
  9. Service is down or unreachable but not actively refusing connections
  10. IPv4/IPv6 routing issues causing connection delays

How to fix "Error: ETIMEDOUT (Operation timed out)"

1Configure explicit timeout values

Set appropriate timeout values based on your expected response times. Different HTTP libraries handle timeouts differently:

Native http/https module:

javascript
const http = require('http');

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/data',
  timeout: 10000 // 10 seconds
};

const req = http.get(options, (res) => {
  // Handle response
});

req.on('timeout', () => {
  req.destroy();
  console.error('Request timed out');
});

req.on('error', (err) => {
  if (err.code === 'ETIMEDOUT') {
    console.error('Connection timed out');
  }
});

Axios:

javascript
const axios = require('axios');

const response = await axios.get('https://api.example.com/data', {
  timeout: 10000 // 10 seconds
});

Fetch API (Node.js 18+):

javascript
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);

try {
  const response = await fetch('https://api.example.com/data', {
    signal: controller.signal
  });
  clearTimeout(timeoutId);
} catch (err) {
  if (err.name === 'AbortError') {
    console.error('Request timed out');
  }
}

Start with conservative timeouts (30-60 seconds) and adjust based on your monitoring data.

2Enable HTTP Keep-Alive for connection reuse

Keep-Alive allows Node.js to reuse TCP connections, reducing the overhead of establishing new connections and avoiding timeout issues:

javascript
const http = require('http');
const https = require('https');

// Create agents with Keep-Alive enabled
const httpAgent = new http.Agent({
  keepAlive: true,
  keepAliveMsecs: 30000, // Keep connection alive for 30 seconds
  maxSockets: 50,
  maxFreeSockets: 10,
  timeout: 60000
});

const httpsAgent = new https.Agent({
  keepAlive: true,
  keepAliveMsecs: 30000,
  maxSockets: 50,
  maxFreeSockets: 10,
  timeout: 60000
});

// Use with axios
const axios = require('axios');
axios.defaults.httpAgent = httpAgent;
axios.defaults.httpsAgent = httpsAgent;

// Or with fetch
const response = await fetch('https://api.example.com/data', {
  agent: httpsAgent
});

This is especially important in serverless environments like AWS Lambda where connection pooling significantly improves performance.

3Implement retry logic with exponential backoff

Handle transient network failures gracefully by retrying failed requests:

Using axios-retry:

javascript
const axios = require('axios');
const axiosRetry = require('axios-retry');

axiosRetry(axios, {
  retries: 3,
  retryDelay: axiosRetry.exponentialDelay,
  retryCondition: (error) => {
    return error.code === 'ETIMEDOUT' ||
           error.code === 'ECONNABORTED' ||
           axiosRetry.isNetworkOrIdempotentRequestError(error);
  }
});

const response = await axios.get('https://api.example.com/data', {
  timeout: 10000
});

Custom retry implementation:

javascript
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      return response;
    } catch (err) {
      const isLastAttempt = i === maxRetries - 1;
      if (isLastAttempt || err.name !== 'AbortError') {
        throw err;
      }

      // Exponential backoff: 1s, 2s, 4s
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
4Check firewall and network configuration

Verify that outbound connections are not being blocked:

Test connectivity:

bash
# Test if you can reach the target host
ping api.example.com

# Check if the port is accessible
telnet api.example.com 443

# Or use curl to test the endpoint
curl -v --max-time 10 https://api.example.com/data

# Check your DNS resolution
nslookup api.example.com
dig api.example.com

Common firewall/network fixes:
- Check cloud security groups (AWS, Azure, GCP) allow outbound HTTPS/HTTP
- Verify corporate proxy settings if behind a corporate network
- Review VPC routing tables and network ACLs
- Ensure no rate limiting at the network level
- Configure proxy in Node.js if required:

javascript
const axios = require('axios');

axios.get('https://api.example.com/data', {
  proxy: {
    protocol: 'http',
    host: 'proxy.company.com',
    port: 8080
  },
  timeout: 10000
});
5Update DNS configuration

DNS resolution delays can cause timeouts. Switch to reliable DNS servers:

On Linux/macOS, edit /etc/resolv.conf:

bash
# Add Google DNS
nameserver 8.8.8.8
nameserver 8.8.4.4

# Or Cloudflare DNS
nameserver 1.1.1.1
nameserver 1.0.0.1

On Windows (PowerShell as Administrator):

powershell
# Set DNS to Google
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("8.8.8.8","8.8.4.4")

# Or Cloudflare
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("1.1.1.1","1.0.0.1")

Configure DNS timeout in Node.js:

javascript
const dns = require('dns');
dns.setDefaultResultOrder('ipv4first');

// For custom DNS resolution
const resolver = new dns.Resolver();
resolver.setServers(['8.8.8.8', '8.8.4.4']);
6Monitor and manage socket usage

Excessive concurrent connections can exhaust available sockets and cause timeouts:

Check current socket usage:

bash
# On Linux/macOS
lsof -i -P -n | grep node

# Count active connections
netstat -an | grep ESTABLISHED | wc -l

# Check system limits
ulimit -n

Increase system limits if needed:

bash
# Temporary increase (Linux/macOS)
ulimit -n 65536

# Permanent increase - edit /etc/security/limits.conf
* soft nofile 65536
* hard nofile 65536

Configure connection pooling in your application:

javascript
const http = require('http');

const agent = new http.Agent({
  maxSockets: 50,        // Max concurrent connections
  maxFreeSockets: 10,    // Keep some connections in pool
  timeout: 60000,
  keepAlive: true
});

// Monitor socket usage
setInterval(() => {
  console.log('Sockets in use:', Object.keys(agent.sockets).length);
  console.log('Free sockets:', Object.keys(agent.freeSockets).length);
}, 10000);

Advanced notes

Server Keep-Alive Configuration:
When using Node.js as both client and server, ensure the server's keepAliveTimeout is greater than the client's timeout. The default Node.js HTTP server timeout is 5 seconds, which can cause race conditions:

javascript
const server = http.createServer((req, res) => {
  // Your handler
});

server.keepAliveTimeout = 65000; // 65 seconds
server.headersTimeout = 66000;   // Slightly higher than keepAliveTimeout

IPv6 vs IPv4 Issues:
Some environments have broken IPv6 connectivity, causing Node.js to attempt IPv6 connections that timeout before falling back to IPv4. Force IPv4 resolution:

javascript
const dns = require('dns');
dns.setDefaultResultOrder('ipv4first');

AWS Lambda Considerations:
Lambda functions experience frequent ETIMEDOUT errors due to cold starts and connection limits. Always use Keep-Alive agents and consider warming strategies:

javascript
// Reuse agents across invocations (outside handler)
const httpsAgent = new https.Agent({
  keepAlive: true,
  maxSockets: 50
});

exports.handler = async (event) => {
  const response = await axios.get(url, { httpsAgent });
  return response.data;
};

Debugging Timeout Sources:
Use Node.js diagnostics to identify which operations are timing out:

javascript
const { performance } = require('perf_hooks');

async function timedFetch(url) {
  const start = performance.now();
  try {
    const response = await fetch(url);
    console.log(`Request took ${performance.now() - start}ms`);
    return response;
  } catch (err) {
    console.log(`Failed after ${performance.now() - start}ms`, err.code);
    throw err;
  }
}

Progressive Timeout Strategy:
For critical operations, implement progressive timeouts with fallback strategies:

javascript
async function fetchWithFallback(primaryUrl, fallbackUrl) {
  try {
    return await fetch(primaryUrl, { timeout: 5000 });
  } catch (err) {
    if (err.code === 'ETIMEDOUT') {
      console.log('Primary timed out, trying fallback');
      return await fetch(fallbackUrl, { timeout: 10000 });
    }
    throw err;
  }
}

Frequently asked questions

What does "ETIMEDOUT" mean?
ETIMEDOUT is a timeout error that signals a network operation failed because the connected party did not properly respond within the allocated time period. js when attempting to establish or maintain a connection that exceeds the timeout threshold. js is unable to complete a TCP connection, send data, or receive a response from a remote server.
How do I fix "ETIMEDOUT"?
ETIMEDOUT occurs when a network operation in Node.js does not complete within the specified or default time limit. This typically happens during HTTP requests, database connections, or socket operations when the remote server fails to respond in time.
What causes "ETIMEDOUT"?
Remote server is overloaded and cannot respond within the timeout period Network connectivity issues between client and server (latency, packet loss) Firewall or proxy blocking outbound connections
Is the "ETIMEDOUT" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading