Error Encyclopedia

Socket Hang Up Error

Fix 'socket hang up' errors in Node.js HTTP clients. Learn why connections are terminated prematurely and how to handle them.

What Does This Error Mean?

The 'socket hang up' error means an HTTP connection was terminated by the server before the request completed. This usually happens when the server closes the connection or the underlying TCP connection is reset (ECONNRESET).

Common Causes

1

Server crashed or was killed while processing the request

2

Server-side timeout closing idle connections

3

Nginx or load balancer timeout configured too low

4

Client request body is too large for the server

5

HTTP/2 or keep-alive connection was forcefully closed

6

Network proxy or firewall resetting the connection

How to Fix It

Add retry logic with exponential backoff

Retry failed requests with increasing delays between attempts.

async function fetchWithRetry(url, options, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch(url, options)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      return res
    } catch (err) {
      if (i === retries - 1) throw err
      const delay = Math.pow(2, i) * 1000
      console.log(`Retry ${i + 1}/${retries} after ${delay}ms`)
      await new Promise(r => setTimeout(r, delay))
    }
  }
}

Increase timeout settings

Ensure timeout values are appropriate for the server's expected response time.

// Node.js HTTP agent keep-alive
const http = require("http")
const agent = new http.Agent({ keepAlive: true })

// Fetch with timeout
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30000)
fetch(url, { signal: controller.signal, agent })

Check server logs for crashes

A socket hang up during request processing often means the server crashed.

# Check Node.js error logs
pm2 logs
journalctl -u myapp

# Check for out-of-memory errors
dmesg | grep -i "killed process"

Use connection pooling

Reuse connections with keep-alive to avoid establishing new connections for each request.

const keepAliveAgent = new https.Agent({ keepAlive: true })
// Reuse the same agent across requests
fetch(url1, { agent: keepAliveAgent })
fetch(url2, { agent: keepAliveAgent })

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: