Introduction CloudFront 502 Bad Gateway errors occur when CloudFront cannot get a valid response from the origin server. This could be an ALB returning malformed responses, an SSL certificate mismatch, or the origin closing the connection prematurely.

Symptoms - Users see 502 Bad Gateway from CloudFront distribution - CloudFront access logs show status 502 with x-edge-result-type = error - Origin works when accessed directly but fails through CloudFront - Error is intermittent, correlating with origin load spikes - Specific paths or large responses trigger the error

Common Causes - Origin server returns incomplete HTTP response (missing headers, truncated body) - SSL/TLS certificate validation failure between CloudFront and origin - Origin response header exceeds 10 KB limit (CloudFront maximum) - Origin connection timeout (default 30 seconds for custom origins) - ALB target group health check failures causing intermittent 502s

Step-by-Step Fix 1. **Check CloudFront access logs**: ```bash aws s3 cp s3://my-cloudfront-logs/ /tmp/cf-logs/ --recursive grep "502" /tmp/cf-logs/*.gz | head -20 ```

  1. 1.Verify origin connectivity:
  2. 2.```bash
  3. 3.curl -v -o /dev/null -w "HTTP %{http_code}, Time: %{time_total}s" \
  4. 4.https://my-alb-123456.us-east-1.elb.amazonaws.com/health
  5. 5.`
  6. 6.Check response header size (CloudFront limit is 10 KB total):
  7. 7.```bash
  8. 8.curl -sI https://my-origin.example.com/api/data | wc -c
  9. 9.`
  10. 10.If headers exceed 10 KB, remove unnecessary headers.
  11. 11.Increase origin response timeout:
  12. 12.Update CloudFront distribution Origin Response Timeout to 30 seconds:
  13. 13.```bash
  14. 14.aws cloudfront update-distribution --id E1234567890 --cli-input-json '{
  15. 15."DistributionConfig": {
  16. 16."Origins": {"Items": [{"Id": "my-origin", "DomainName": "my-alb.example.com",
  17. 17."CustomOriginConfig": {"HTTPSPort": 443, "OriginProtocolPolicy": "https-only",
  18. 18."OriginReadTimeout": 30, "OriginKeepaliveTimeout": 5}}], "Quantity": 1}
  19. 19.}
  20. 20.}'
  21. 21.`

Prevention - Set up CloudFront real-time logs to Kinesis for immediate 502 detection - Configure origin health checks with origin groups for failover - Monitor OriginResponseTime CloudWatch metric - Use CloudFront Functions to validate responses before caching - Implement circuit breaker patterns at the origin