Skip to content

fix(server): keep idle keep-alive sockets open longer than client/proxy idle timeouts - #2813

Open
barbaro-br wants to merge 2 commits into
evolution-foundation:developfrom
barbaro-br:fix/server-keepalive-timeout
Open

barbaro-br wants to merge 2 commits into
evolution-foundation:developfrom
barbaro-br:fix/server-keepalive-timeout

Conversation

@barbaro-br

@barbaro-br barbaro-br commented Dec 2, 2026 •

Copy link
Copy Markdown

📋 Description

Node's HTTP server closes idle keep-alive sockets after 5 s (server.keepAliveTimeout; on Node 24 there is also a 1 s keepAliveTimeoutBuffer, so ~6 s in practice). Evolution never changes it.

Clients that pool connections but don't honor the Keep-Alive: timeout=5 header (Go net/http, Python urllib3/requests, Java, most reverse proxies) keep idle sockets for 60–90 s. A bulk sender that pauses a few seconds between messages will sometimes reuse a socket at the exact moment Evolution closes it. The request is written, the socket is reset, and the call fails with ECONNRESET / socket hang up. For a POST /message/sendMedia the client can't safely retry, because it can't tell whether the message was sent.

We hit this in production (v2.3.8, Node 24.22, client in Go, both in the same Docker network): read: connection reset by peer on one sendMedia in a ~3000-message day.

This PR:

  • adds SERVER_KEEPALIVE_TIMEOUT (ms, default 95000, above Go net/http's 90 s idle timeout and the common 60 s proxy/load balancer idle timeout) and sets server.keepAliveTimeout from it. Only positive integers are accepted; anything else falls back to the default;
  • sets server.headersTimeout 1 s above it (Node requires headersTimeout > keepAliveTimeout);
  • documents the variable in .env.example.

With the server keeping idle sockets longer than the client, the client closes them first, so the race goes away. The cost is idle sockets staying open up to 95 s instead of ~6 s. They hold no request state, and headersTimeout/requestTimeout still bound slow or incomplete requests. For comparison, nginx keeps idle client connections for 75 s by default.

🔗 Related Issue

No existing issue that I could find. Happy to open one if you prefer.

🧪 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧹 Code cleanup
  • 🔒 Security fix

🧪 Testing

Reproduction with a plain Node 24 server (same defaults as Evolution), a Go client with the default http.Client, and a TCP relay adding 30 ms one-way latency (as between containers/hosts). The client sends 40 POSTs, each after a pause of 5.95–6.04 s on a pooled connection:

server result
Node default (keepAliveTimeout 5 s + 1 s buffer) 22 / 40 connection reset by peer, 18 ok
keepAliveTimeout = 65000 40 / 40 ok
Reproduction scripts

server.mjs

import http from 'node:http';
const KEEPALIVE = process.argv[3] ? Number(process.argv[3]) : undefined;
const server = http.createServer((req, res) => { req.resume(); req.on('end', () => res.end('{"ok":true}')); });
if (KEEPALIVE !== undefined) { server.keepAliveTimeout = KEEPALIVE; server.headersTimeout = KEEPALIVE + 1000; }
server.listen(Number(process.argv[2]), () => console.log(`listening keepAliveTimeout=${server.keepAliveTimeout}`));

relay/main.go (adds latency)

// TCP relay that adds one-way latency (default 30 ms) to every chunk and to connection close,
// simulating a client and the API on different hosts/containers.
package main

import (
	"net"
	"os"
	"time"
)

const delay = 30 * time.Millisecond

func pipe(dst, src *net.TCPConn) {
	buf := make([]byte, 64<<10)
	for {
		n, err := src.Read(buf)
		if n > 0 {
			b := append([]byte(nil), buf[:n]...)
			time.Sleep(delay)
			if _, werr := dst.Write(b); werr != nil {
				dst.SetLinger(0); dst.Close(); src.SetLinger(0); src.Close()
				return
			}
		}
		if err != nil {
			time.Sleep(delay)
			dst.SetLinger(0) // propagate the close as a reset, like a dead peer
			dst.Close()
			return
		}
	}
}

func main() {
	ln, _ := net.Listen("tcp", os.Args[1])
	for {
		c, err := ln.Accept()
		if err != nil {
			return
		}
		go func(c *net.TCPConn) {
			u, err := net.Dial("tcp", os.Args[2])
			if err != nil {
				c.Close()
				return
			}
			go pipe(u.(*net.TCPConn), c)
			pipe(c, u.(*net.TCPConn))
		}(c.(*net.TCPConn))
	}
}

goclient/main.go

// Go client with default pooling (like most API consumers), pausing ~5 s between POSTs.
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	url := os.Args[1]
	cli := &http.Client{} // default Transport: IdleConnTimeout 90 s, ignores the Keep-Alive header
	res := map[string]int{}
	post := func() string {
		r, err := cli.Post(url, "application/json", bytes.NewReader([]byte(`{"media":"`+strings.Repeat("x", 1000)+`"}`)))
		if err != nil {
			return err.Error()[strings.LastIndex(err.Error(), ": ")+2:]
		}
		io.Copy(io.Discard, r.Body)
		r.Body.Close()
		return "ok"
	}
	for i := 0; i < 40; i++ {
		post()
		time.Sleep(5950*time.Millisecond + time.Duration(i%10)*10*time.Millisecond) // 5.95–6.04 s
		res[post()]++
	}
	fmt.Println(res)
}
node server.mjs 18081 &            # Node default
node server.mjs 18082 65000 &      # this PR
./relay 127.0.0.1:19081 127.0.0.1:18081 &
./relay 127.0.0.1:19082 127.0.0.1:18082 &
./goclient http://127.0.0.1:19081/message/sendMedia/x   # map[connection reset by peer:22 ok:18]
./goclient http://127.0.0.1:19082/message/sendMedia/x   # map[ok:40]
  • npx tsc --noEmit: 0 errors (after prisma generate for postgresql).

  • npx eslint src/main.ts src/config/env.config.ts: clean.

  • Manual testing completed

  • Functionality verified in development environment

  • No breaking changes introduced

  • Tested with different connection types (if applicable)

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios
  • Any dependent changes have been merged and published

📝 Additional Notes

If you'd rather not change the default, I can keep Node's 5 s as the default and leave SERVER_KEEPALIVE_TIMEOUT as opt-in. I picked 95 s so the server outlives the idle timeout of the default Go client (90 s) and of common proxies and load balancers (60 s, e.g. AWS ALB), so the client side always closes idle sockets first.

Updated after the Sourcery review: the default went from 65 s to 95 s (Go's 90 s idle timeout), and the value is now validated.

Summary by Sourcery

Keep idle HTTP connections open longer than typical client and proxy idle timeouts to prevent resets during connection reuse.

Bug Fixes:

  • Reduce connection resets when pooled clients reuse idle keep-alive sockets by keeping server connections open longer.

Enhancements:

  • Add configurable SERVER_KEEPALIVE_TIMEOUT in milliseconds, defaulting to 95,000; invalid or non-positive values use the default.
  • Set the server headers timeout to one second longer than its keep-alive timeout.

Documentation:

  • Document SERVER_KEEPALIVE_TIMEOUT in .env.example.

…xy idle timeouts

Node closes idle keep-alive sockets after 5 s (+1 s keepAliveTimeoutBuffer on Node 24).
Clients that pool connections and do not honor the Keep-Alive: timeout header
(Go net/http, Python urllib3, Java, most reverse proxies) can reuse a socket at the
moment the server closes it, and the POST fails with ECONNRESET / socket hang up
without ever reaching the API.

Set server.keepAliveTimeout from SERVER_KEEPALIVE_TIMEOUT (default 65000 ms, above
the usual 60 s client/proxy idle timeout) and headersTimeout 1 s above it, so the
client side is the one that closes idle sockets.
@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Configuration

Add a validated SERVER_KEEPALIVE_TIMEOUT setting with a 95-second default, then apply it to the HTTP server and set headersTimeout one second higher.

  • src/config/env.config.ts L13, L474-477, L486
  • src/main.ts L174-180

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/main.ts" line_range="178" />
<code_context>
+  // `Keep-Alive: timeout` header (Go, Python, Java, most reverse proxies) can reuse a socket right as it closes
+  // and get ECONNRESET / "socket hang up" on a POST that never reached the API. Keep idle sockets open longer
+  // than typical client and proxy idle timeouts (60 s) so the client is the one that closes them.
+  server.keepAliveTimeout = httpServer.KEEPALIVE_TIMEOUT;
+  server.headersTimeout = httpServer.KEEPALIVE_TIMEOUT + 1000;
+
</code_context>
<issue_to_address>
**Idle sockets amplify connection exhaustion**

When an unauthenticated remote client opens many HTTP/1.1 keep-alive connections and leaves them idle, `server.keepAliveTimeout` retains each completed HTTP/1.1 connection for 65 seconds, so enough idle sockets consume process file descriptors and memory and deny service to other clients.

Limit concurrent connections or otherwise enforce per-client connection limits when using the longer default timeout.

Also at `src/config/env.config.ts:482`.
</issue_to_address>

### Comment 2
<location path="src/config/env.config.ts" line_range="482" />
<code_context>
         URL: process.env.SERVER_URL,
         DISABLE_DOCS: process.env?.SERVER_DISABLE_DOCS === 'true',
         DISABLE_MANAGER: process.env?.SERVER_DISABLE_MANAGER === 'true',
+        KEEPALIVE_TIMEOUT: Number.parseInt(process.env?.SERVER_KEEPALIVE_TIMEOUT) || 65000,
       },
       CORS: {
</code_context>
<issue_to_address>
**Go clients get reset POSTs**

When a pooled Go client reuses a connection around the server's 65-second idle close, before its default transport's 90-second idle timeout, `KEEPALIVE_TIMEOUT` configures `server.keepAliveTimeout` shorter than the Go transport's idle timeout, so Node closes the socket before the client retires it and a reused POST fails with ECONNRESET or "socket hang up".

Configure the server keep-alive timeout to exceed the Go client's idle timeout so the client closes the connection first.

Also at `src/main.ts:178`.
</issue_to_address>

### Comment 3
<location path="src/config/env.config.ts" line_range="482" />
<code_context>
         URL: process.env.SERVER_URL,
         DISABLE_DOCS: process.env?.SERVER_DISABLE_DOCS === 'true',
         DISABLE_MANAGER: process.env?.SERVER_DISABLE_MANAGER === 'true',
+        KEEPALIVE_TIMEOUT: Number.parseInt(process.env?.SERVER_KEEPALIVE_TIMEOUT) || 65000,
       },
       CORS: {
</code_context>
<issue_to_address>
**Malformed timeout breaks requests**

When `SERVER_KEEPALIVE_TIMEOUT` is set to a negative integer, `Number.parseInt` accepts negative values, and `main.ts` derives `headersTimeout` by adding only 1,000 ms; for a negative setting this leaves some otherwise valid requests with less than a one-second header deadline, so Node rejects slow requests before they reach the API.

Validate the parsed timeout as a positive, supported value and fall back to the default or fail startup when it is invalid.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and keeping idle sockets open for 65 seconds can retain substantially more connections and consume server resources; if that causes a production outage, reverting the timeout cannot undo the outage that already occurred. The new setting can be reverted to restore the prior socket behavior.

Blocking findings: src/main.ts:178, src/config/env.config.ts:482, src/config/env.config.ts:482


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/main.ts Resolved
Comment thread src/config/env.config.ts Resolved
Comment thread src/config/env.config.ts Resolved
…_TIMEOUT

- 95 s exceeds Go net/http's default IdleConnTimeout (90 s), so pooled Go clients
  retire idle sockets before the server closes them (65 s did not).
- Accept only positive integers; 0 (no timeout), negatives and garbage fall back
  to the default instead of producing a broken headersTimeout.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant