DevOpsil
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

  1. 1Check ALB access logs for the 502 entries — look at target_status_code
  2. 2Check target group health: AWS Console → EC2 → Target Groups → Targets tab
  3. 3Check CloudWatch: `TargetResponseTime` and `UnHealthyHostCount` metrics
  4. 4Check target's application logs during the 502 window
  5. 5Verify security groups: ALB SG → Target SG allow health check port

>Fix

  1. 1Ensure targets return valid HTTP responses (proper status code and headers)
  2. 2Increase deregistration delay: `deregistration_delay.timeout_seconds = 60`
  3. 3Increase ALB idle timeout if targets need more processing time
  4. 4Fix security groups to allow ALB health check traffic
  5. 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