diff --git a/.env.example b/.env.example index fa7d9e7bd3..b3ea205335 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,10 @@ SERVER_TYPE=http SERVER_PORT=8080 # Server URL - Set your application url SERVER_URL=http://localhost:8080 +# How long (ms) idle keep-alive connections stay open. Keep it above the idle timeout of +# your clients and reverse proxy (Go net/http: 90 s; most proxies: 60 s) to avoid ECONNRESET +# on reused connections. Must be a positive integer; invalid values fall back to the default. +SERVER_KEEPALIVE_TIMEOUT=95000 SSL_CONF_PRIVKEY=/path/to/cert.key SSL_CONF_FULLCHAIN=/path/to/cert.crt diff --git a/src/config/env.config.ts b/src/config/env.config.ts index 1b17a83b53..abc19ed328 100644 --- a/src/config/env.config.ts +++ b/src/config/env.config.ts @@ -10,6 +10,7 @@ export type HttpServer = { URL: string; DISABLE_DOCS: boolean; DISABLE_MANAGER: boolean; + KEEPALIVE_TIMEOUT: number; }; export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE'; @@ -470,6 +471,10 @@ export class ConfigService { } private envProcess(): Env { + // Must exceed the idle timeout of pooled clients (Go net/http: 90 s) so the client closes idle sockets first. + // Only positive integers are accepted; 0 would disable the timeout and negatives break headersTimeout. + const keepAliveTimeout = Number.parseInt(process.env?.SERVER_KEEPALIVE_TIMEOUT); + return { SERVER: { NAME: process.env?.SERVER_NAME || 'evolution', @@ -478,6 +483,7 @@ export class ConfigService { URL: process.env.SERVER_URL, DISABLE_DOCS: process.env?.SERVER_DISABLE_DOCS === 'true', DISABLE_MANAGER: process.env?.SERVER_DISABLE_MANAGER === 'true', + KEEPALIVE_TIMEOUT: Number.isInteger(keepAliveTimeout) && keepAliveTimeout > 0 ? keepAliveTimeout : 95000, }, CORS: { ORIGIN: process.env.CORS_ORIGIN?.split(',') || ['*'], diff --git a/src/main.ts b/src/main.ts index f9884ba34b..e3c7f69a7c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -171,6 +171,13 @@ async function bootstrap() { server = ServerUP[httpServer.TYPE]; } + // Node closes idle keep-alive sockets after 5 s (+1 s buffer). Clients that pool connections and ignore the + // `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 (Go: 90 s, load balancers/proxies: 60 s) so the client closes them. + server.keepAliveTimeout = httpServer.KEEPALIVE_TIMEOUT; + server.headersTimeout = httpServer.KEEPALIVE_TIMEOUT + 1000; + eventManager.init(server); const sentryConfig = configService.get('SENTRY');