Fix 502 bad gateway on API Gateway
Quick Answer: The "502 Bad Gateway" error on API Gateway indicates that the upstream integration (e.g., Lambda function, HTTP endpoint) returned an invalid response or timed out. The most likely cause is an unhandled exception or malformed JSON from the backend. First, check the API Gateway CloudWatch logs for the specific API execution. Look for "Execution failed due to an internal error" or "Lambda.FunctionError" messages to pinpoint the exact failure point and expected result is a detailed error trace.
What Causes This Error
- Backend integration (e.g., Lambda, EC2, ECS) returned an invalid or malformed response (e.g., non-JSON, incorrect headers, status code outside 200-299 range for proxy integrations).
- Integration backend timed out before responding to API Gateway, often due to long-running operations exceeding the backend's configured timeout or API Gateway's integration timeout.
- Network connectivity issues between API Gateway and the private integration endpoint (e.g., VPC Link misconfiguration, Security Group/NACL blocking traffic, incorrect DNS resolution).
- Backend service (e.g., Lambda function, HTTP server) crashed, became unavailable, or returned an unhandled exception, resulting in an empty or malformed response.
- API Gateway's integration request or response mapping templates are misconfigured, leading to an inability to parse the backend's output or generate a valid request to the backend.
Step-by-Step Fixes
Fix 1: Analyze CloudWatch Logs for Integration Errors
Navigate to the API Gateway console, select your API, and go to 'Stages'.,Select the relevant stage, then click on the 'Logs/Tracing' tab. Ensure CloudWatch Logs are enabled for 'INFO' or 'ERROR' level.,Click the 'CloudWatch Logs' link. In CloudWatch Logs Insights, query for logs related to your API and the 502 error, filtering by 'logStream' and 'message' for phrases like 'Execution failed' or 'Lambda.FunctionError'.,Examine the detailed log entries for the specific request ID that failed to identify the exact error message or stack trace from your backend integration.
Fix 2: Verify Backend Response Format and Status Codes
For Lambda integrations, ensure your Lambda function returns a valid JSON object with the correct structure for proxy integrations (e.g., `{statusCode: 200, headers: {}, body: "{}"}`).,For HTTP/VPC Link integrations, confirm the backend server is returning a standard HTTP response with a valid status code (2xx for success) and well-formed headers/body.,Temporarily modify your backend code to log the *exact* response it generates before sending it, then compare this against API Gateway's expected format.,If using integration response mapping, ensure the 'Content-Type' header is correctly set and the mapping template (`application/json`) accurately transforms the backend's response.
Fix 3: Adjust Integration and Backend Timeouts
In the API Gateway console, navigate to your API, select the specific method, and click 'Integration Request'.,Locate the 'Integration timeout' setting. Increase this value (up to 29 seconds for most integrations) if your backend requires more processing time.,For Lambda integrations, go to the Lambda function's configuration and increase its 'Timeout' setting (up to 15 minutes). Ensure the Lambda timeout is greater than the API Gateway integration timeout.,For HTTP/VPC Link integrations, verify that your backend server's internal processing timeout and any load balancer idle timeouts are sufficient to handle the request duration.
Fix 4: Inspect VPC Link and Network Configuration
If using a VPC Link, ensure its status is 'AVAILABLE' in the API Gateway console under 'VPC Links'.,Verify that the target Network Load Balancer (NLB) associated with the VPC Link is healthy and its target groups have registered instances/IPs.,Check the Security Groups attached to your backend instances/containers and the NLB. Ensure inbound rules allow traffic from the API Gateway service IP ranges or the NLB's security group on the correct port.,Confirm that the network ACLs (NACLs) for the subnets where your backend and NLB reside permit the necessary inbound and outbound traffic on the required ports.
Advanced Fixes
Advanced Fix 1: Implement API Gateway Custom Error Responses
In the API Gateway console, select your API, then navigate to 'Gateway Responses'.,Locate the 'DEFAULT_5XX' response type. You can customize its status code, headers, and body mapping templates.,Define a specific mapping template (e.g., `application/json`) for the response body to return a structured error message to the client instead of a generic 502, using variables like `$context.error.message`.
Advanced Fix 2: Use AWS X-Ray for Distributed Tracing
Enable X-Ray tracing for your API Gateway stage and for your backend Lambda functions or other integrated services.,When a 502 occurs, use the X-Ray console to view the end-to-end trace for the failed request.,Analyze the trace map and timeline to identify which service segment failed, its exact error message, and the latency at each hop, providing a clear picture of the root cause.
FAQs
Q: What's the difference between a 502 and a 504 error on API Gateway?
A: A 502 Bad Gateway means API Gateway received an invalid response from the backend integration (e.g., malformed JSON, unhandled exception, non-2xx status for proxy). A 504 Gateway Timeout means API Gateway *did not receive any response* from the backend within the configured integration timeout period, indicating the backend took too long or was unreachable.
Q: Why am I getting a 502 even if my Lambda function returns a 200 OK?
A: Even with a 200 OK, a 502 can occur if the Lambda function's response body is not valid JSON, or if the overall response structure for a proxy integration is incorrect (e.g., missing `statusCode`, `headers`, or `body` fields). API Gateway expects a specific JSON format for proxy integrations to correctly map the backend response to the client.
Q: Does enabling detailed CloudWatch logging impact performance or cost?
A: Enabling detailed 'INFO' or 'DEBUG' level logging for API Gateway stages will increase the volume of logs sent to CloudWatch, which can incur additional costs based on data ingestion and storage. While the performance impact on API Gateway itself is minimal, it's recommended to use 'ERROR' level for production or only enable detailed logging temporarily for troubleshooting.
Q: Can a WAF or custom domain configuration cause a 502 error?
A: While less common, a misconfigured WAF (Web Application Firewall) rule could potentially block legitimate requests before they reach the backend, leading to a 502 if API Gateway interprets it as an invalid response. Similarly, an incorrect custom domain base path mapping or SSL certificate issue might prevent requests from reaching the API Gateway endpoint correctly, though this often manifests as a 4xx error or connection error rather than a 502.