Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Same backend, two different outcomes
Your health checks pass, but some real requests still get a 502. The health check reaches app:8080 and gets a 200 OK. A client's GET /orders goes through the ALB, and that's where it fails, on the reused connection between the ALB and the backend. The app itself isn't broken.
Fresh connection vs reused connection
The difference is which connection the request travels on. The health check opens a brand-new connection to app:8080, so it gets 200 OK. But the ALB reuses pooled keep-alive connections for real traffic, and the app may already have closed one. That request gets reset and refused.
The race on one pooled connection
The ALB sends GET /orders to app:8080 and gets a 200, with the connection kept open for reuse. After five idle seconds, the app closes it. The ALB doesn't know yet, so it sends the next GET /orders on that same connection. The app answers with a TCP reset, and the client sees a 502 Bad Gateway.
The 55-second danger window
Follow the timeline. After the last response at zero seconds, Node closes the idle connection at five seconds. The ALB keeps it for sixty. Any reuse between five and sixty seconds can fail, about a fifty-five second window. That's why the 502s look random, and cluster after traffic lulls.
The backend hung up first
A 502 happens when the backend hangs up before the load balancer does. After five seconds of silence, app:8080 closes the connection. The ALB still thinks it's open for sixty, so it talks into a dead line. The app never logs an error, because it never saw the request.
Fix: backend waits longer than ALB
The fix is to flip the order. Raise app:8080's keep-alive from five seconds to sixty-five, just above the ALB's sixty-second idle timeout. Now the ALB hangs up first, so a reused connection for GET /orders is still open. In Node, also set headersTimeout higher than keepAliveTimeout.
If 502s persist, check these
If 502s persist, timeouts aren't the only suspect. Deploys that kill targets without connection draining cause the same reset. Check the load balancer logs for 502s with no target status, then see whether those 502s line up with quiet gaps.
- Deploys: targets killed without connection draining
- LB logs: 502 with no target status
- Match 502 times to idle gaps
502s happen when the backend hangs up before the load balancer does.
A 502 happens when the backend hangs up before the load balancer does. So keep the backend's keep-alive timeout longer than the load balancer's idle timeout, and the same goes for any upstream behind a proxy. That way the proxy never reuses a dead connection.
