AWSCritical
Fix: AWS ALB Returning 502 Bad Gateway
ALB returning 502 errors to clients
!Symptoms
- ALB returning 502 errors to clients
- CloudWatch showing elevated HTTP 502 count on the ALB
- Backend health checks passing but requests failing
- Intermittent 502s during deployments or scaling events
?Root Causes
- Target responding with invalid HTTP response or closing connection prematurely
- Target deregistering while in-flight requests are still processing
- Target taking too long to respond (exceeding idle timeout)
- Security group on targets not allowing health check traffic from ALB
- Target application crashing or running out of connections
#Diagnosis Steps
- 1Check ALB access logs for the 502 entries — look at target_status_code
- 2Check target group health: AWS Console → EC2 → Target Groups → Targets tab
- 3Check CloudWatch: `TargetResponseTime` and `UnHealthyHostCount` metrics
- 4Check target's application logs during the 502 window
- 5Verify security groups: ALB SG → Target SG allow health check port
>Fix
- 1Ensure targets return valid HTTP responses (proper status code and headers)
- 2Increase deregistration delay: `deregistration_delay.timeout_seconds = 60`
- 3Increase ALB idle timeout if targets need more processing time
- 4Fix security groups to allow ALB health check traffic
- 5Fix application connection handling — ensure graceful shutdown
*Prevention
- Set ALB idle timeout lower than application keep-alive timeout
- Enable access logging on ALB for debugging
- Use connection draining (deregistration delay) during deployments
- Monitor `HTTPCode_ELB_502_Count` and alert on spikes
- Implement graceful shutdown in application (handle SIGTERM, drain connections)
Related Error Messages
502 Bad Gatewayupstream connect error or disconnectConnection reset by peerTargetDeregistrationInProgress