Skip to content

Random ALB 502s Are a Keep-Alive Race

Published:

We had this exact issue in production. An AWS Application Load Balancer returned a 502 every now and then, on quiet endpoints, at quiet hours, nowhere near a deploy. The app logs had nothing for those requests because they never reached our code.

This post by Daniel Valev, Those Random ALB 502s Aren’t Your Deploys. They’re a Keep-Alive Race, explains the cause.

What’s happening

The ALB keeps a pool of open TCP connections to each target and reuses them across requests. Both sides have an idle timer on those connections:

So the backend closes an idle connection first. If the ALB sends a request on that connection just as the backend’s timer fires, the request and the backend’s FIN cross on the wire. The request lands on a closed socket, the kernel replies with a RST, and the ALB returns a 502.

The window is tiny, so it looks random. Busy endpoints never sit idle long enough to hit it. Endpoints polled every few seconds, like a dashboard status check, hit it the most.

The rule: on a pooled connection, the side that sends the next request has to be the one that gives up first. Behind an ALB, that’s the ALB, so the backend’s timeout must be longer.

How to confirm it

SELECT time, target_ip, request_url
FROM alb_logs
WHERE elb_status_code = 502 AND target_status_code = '-'
ORDER BY time DESC
LIMIT 50;
aws elbv2 describe-load-balancer-attributes \
  --load-balancer-arn "$ALB_ARN" \
  --query "Attributes[?Key=='idle_timeout.timeout_seconds'].Value" \
  --output text

The fix

Set the backend’s keep-alive timeout above the ALB idle timeout. The article suggests 15s of margin, so 75s for the default 60s.

Python with uvicorn:

uvicorn app:app --host 0.0.0.0 --port 8000 --timeout-keep-alive 75

Or, if you start uvicorn from code:

import uvicorn

uvicorn.run(
    "app:app",
    host="0.0.0.0",
    port=8000,
    timeout_keep_alive=75,  # must be longer than the ALB idle timeout
)

If you run uvicorn workers under gunicorn, gunicorn’s --keep-alive is what counts, not uvicorn’s flag:

gunicorn app:app -k uvicorn_worker.UvicornWorker --keep-alive 75

Other servers:

Keep the ALB timeout and the app’s keep-alive in the same IaC module, or pass one into the other as an env var. If someone raises the ALB timeout to 120s later, the app has to move in the same change, or the 502s come back.

Don’t fix it by lowering the ALB idle timeout instead. Slow requests then fail with 504s.

Is Dictator Telegram's Grokbot Moment?