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