Error: read ECONNRESET
Error: socket hang up
ConnectionResetError: [Errno 104] Connection reset by peer
The other side (server, database, API) forcefully closed the connection while your app was still reading or writing.
Fix 1: Server Crashed or Restarted
The most common cause. The server you’re connecting to went down mid-request.
// ✅ Add retry logic
async function fetchWithRetry(url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetch(url);
} catch (err) {
if (i === retries - 1) throw err;
await new Promise(r => setTimeout(r, 1000 * (i + 1)));
}
}
}
Fix 2: Keep-Alive Timeout Mismatch
Your client keeps the connection open longer than the server allows.
// Node.js — set keep-alive timeout lower than server's
const agent = new http.Agent({
keepAlive: true,
keepAliveMsecs: 30000, // Must be less than server timeout
});
Fix 3: Request Too Large
The server closed the connection because the payload was too big.
# Nginx: increase max body size
client_max_body_size 50M;
# Node.js Express
app.use(express.json({ limit: '50mb' }));
Fix 4: SSL/TLS Handshake Failed
// ❌ Self-signed cert in development
// Quick fix (NOT for production):
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
// ✅ Proper fix: add the CA certificate
const https = require('https');
const agent = new https.Agent({
ca: fs.readFileSync('ca-cert.pem'),
});
Fix 5: Database Connection Dropped
// ❌ Using a stale database connection
// ✅ Use a connection pool with health checks
const pool = new Pool({
max: 20,
idleTimeoutMillis: 30000,
});
// Handle connection errors
pool.on('error', (err) => {
console.error('Unexpected pool error', err);
});
Fix 6: Handle the Error Gracefully
// Node.js — prevent crash on ECONNRESET
process.on('uncaughtException', (err) => {
if (err.code === 'ECONNRESET') {
console.log('Connection reset — retrying...');
return;
}
throw err;
});