Random 502 errors behind a load balancer: the keep-alive timeout mismatch

Rare, unpredictable 502s with a healthy backend often come from keep-alive timeouts: the app closes idle connections before the proxy does. How to confirm and fix it.

· 6 min read · By the Spot Downtime team

The pattern is maddening. Your application is healthy, CPU is low, health checks pass, yet a small fraction of requests (one in a few thousand, perhaps) come back as 502 Bad Gateway. Retrying works. Nothing in the application log matches. The cause is often a mismatch between idle connection timeouts, and it is easy to fix once you know where to look.

What happens

Proxies and load balancers reuse TCP connections to your backend (keep-alive) so they do not pay for a new handshake on every request. Each side has an idle timeout: how long it keeps an unused connection open.

If the backend closes an idle connection a moment before the proxy decides to reuse it, the proxy writes a request into a connection that the backend has already closed (or is closing). The backend answers with a reset or nothing, and the proxy returns 502 to the client. It is a race, which is why it is rare and random.

The rule that avoids the race: the backend's keep-alive timeout must be longer than the proxy's idle timeout, so the proxy always closes first.

Typical culprits and the numbers to compare

  • AWS Application Load Balancer. The ALB idle timeout defaults to 60 seconds. If your app closes idle connections sooner, you get sporadic 502s. Set the app above 60 s (for example 65 s).
  • Node.js. server.keepAliveTimeout defaults to 5 seconds, far below a 60 s load balancer timeout. This is the most common source of the problem.
  • Gunicorn. The --keep-alive setting defaults to 2 seconds.
  • nginx upstream keepalive. When nginx proxies to an application using keepalive connections, the application's own idle timeout must exceed nginx's keepalive_timeout for the upstream block (default 60 s in recent versions).

Confirm it

Signs that point to this and not to a real failure:

  • The 502s are a tiny percentage and spread evenly over time, not clustered at deploys or traffic peaks.
  • Your load balancer logs show a 502 with no or a very short target response time, and the application never logged the request.
  • On ALB, the access log shows elb_status_code 502 with target_status_code empty (-), meaning the target never returned a status.
  • Lowering the load balancer idle timeout below the app timeout makes the errors disappear.

The fix: make the backend outlast the proxy

Node.js

js
const server = app.listen(3000);

// must exceed the load balancer idle timeout (ALB default: 60 s)
server.keepAliveTimeout = 65 * 1000;
// headersTimeout must be larger than keepAliveTimeout
server.headersTimeout = 66 * 1000;

Gunicorn

bash
gunicorn app:app --keep-alive 75

Note that Gunicorn's sync workers do not use keep-alive at all. If you run behind a load balancer, use an async or threaded worker class (gthread, gevent) or put nginx in front.

nginx in front of an application

nginx
upstream app {
    server 127.0.0.1:3000;
    keepalive 32;
    keepalive_timeout 30s;   # nginx closes idle upstream connections first
}

server {
    location / {
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

Here the application must keep idle connections for longer than 30 seconds. The proxy_http_version 1.1 and empty Connection header are required for upstream keep-alive to work at all.

Tuning the proxy side instead

If you cannot change the application, lower the proxy's idle timeout (or its upstream keepalive_timeout) below the application's. That also closes the gap. Another option is disabling upstream keep-alive, at the cost of a new connection per request.

Retries as a safety net

Some proxies retry on a connection that fails before any bytes are written. nginx does this with proxy_next_upstream error for idempotent requests. Do not rely on it as the fix, and be careful enabling retries for POST requests, which could be executed twice.

Noticing low-rate failures

An error rate of 0.05% will not trip a simple “site is down” alert and a single check per minute may never see it. It still hurts real users and API clients. Frequent checks help, and so does alerting on repeated failures in a window rather than only on a hard outage. An API monitor that records status codes over time makes a slow drip of 502s visible. Related background on the errors themselves is in 502, 503 and 504 explained and the AWS ALB version.

Quick checklist

List every idle timeout in the path: load balancer, proxy, application server. Make each hop further from the client longer than the one before it. Backend above proxy is the rule that prevents this race.

Get new guides by email

Practical posts on monitoring, outages, error fixes and on-call, when they're published. No spam.

Unsubscribe from any email with one click. See our privacy policy.

Keep reading