Troubleshooting 502 Bad Gateway Errors in AWS API Gateway and Lambda
Quickly diagnose and fix 502 Bad Gateway errors in AWS API Gateway connected to Lambda. Learn root causes like timeout, payload format, and permissions.
- Lambda function timeout exceeding API Gateway integration timeout (max 29s)
- Malformed Lambda proxy response (missing statusCode, headers, or body)
- Execution role permissions preventing API Gateway from invoking Lambda
- Response payload exceeding the 10MB API Gateway limit
| Method | When to Use | Time | Risk |
|---|---|---|---|
| CloudWatch Logs Analysis | Initial diagnosis of 502 errors | 5 mins | Low |
| Update Lambda Response Format | Malformed proxy integration responses | 10 mins | Low |
| Increase Lambda Timeout | Function taking too long to process (under 29s) | 5 mins | Low |
| Fix IAM Execution Roles | API Gateway lacks permissions to invoke Lambda | 10 mins | Medium |
Understanding the 502 Bad Gateway Error
A 502 Bad Gateway error in AWS API Gateway, particularly when integrated with AWS Lambda (Lambda Proxy Integration), indicates that API Gateway received an invalid or unexpected response from the backend Lambda function. Unlike a 500 Internal Server Error (which usually means the Lambda function threw an unhandled exception), a 502 error often points to an integration issue, a timeout, or a malformed response structure.
When API Gateway invokes your Lambda function, it expects the response to strictly adhere to a specific JSON format. If your function returns a plain string, an object without a statusCode, or times out, API Gateway cannot map the response to an HTTP response, resulting in a 502 Bad Gateway.
Step 1: Diagnose the Root Cause
The first step in troubleshooting a 502 error is enabling and checking CloudWatch Logs for your API Gateway execution.
- Enable Execution Logging: In the API Gateway console, go to your Stage settings and enable "Log full requests/responses data".
- Check CloudWatch Logs: Navigate to CloudWatch > Log groups and find the log group for your API Gateway (e.g.,
API-Gateway-Execution-Logs_{rest-api-id}/{stage-name}).
Look for specific error messages in the logs:
Execution failed due to configuration error: Malformed Lambda proxy responseEndpoint request timed outInvalid permissions on Lambda function
Step 2: Fix Common Issues
Issue 1: Malformed Lambda Proxy Response
If you are using Lambda Proxy Integration, your Lambda function MUST return a JSON object with at least a statusCode and optionally headers and body. The body must be a string (stringify your JSON objects).
Incorrect Response (Causes 502):
exports.handler = async (event) => {
return { message: "Hello World" }; // Missing statusCode, body is an object
};
Correct Response:
exports.handler = async (event) => {
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "Hello World" })
};
};
Issue 2: API Gateway Integration Timeout
API Gateway has a hard limit for integration timeouts of 29 seconds. If your Lambda function takes longer than 29 seconds to execute, API Gateway will drop the connection and return a 502 Bad Gateway, even if the Lambda function eventually completes successfully.
- Fix: Optimize your Lambda function's code to execute faster. Make sure the Lambda timeout is not set lower than what your code needs (up to 29s).
- Workaround: If the task inherently takes longer than 29 seconds, you must decouple the process. Have the API Gateway invoke a Lambda that puts a message on an SQS queue or starts an EventBridge rule, and immediately returns a 202 Accepted. A secondary worker Lambda can process the long-running task asynchronously.
Issue 3: Missing Resource-Based Permissions
API Gateway needs explicit permission to invoke your Lambda function. This is managed via Resource-based policies on the Lambda function.
Usually, the AWS Console adds this automatically when you link them. However, if you are using Infrastructure as Code (Terraform, CloudFormation, SAM, Serverless Framework) and forget to define the AWS::Lambda::Permission, you'll get a 502.
- Fix: Use the AWS CLI to add the permission, or update your IaC templates.
Issue 4: Payload Size Exceeded
API Gateway has a maximum payload size of 10 MB. If your Lambda function attempts to return a payload larger than this, API Gateway will throw a 502 error.
- Fix: Paginate your data, compress the response payload, or return a pre-signed S3 URL for the client to download the large payload directly from S3.
Frequently Asked Questions
# AWS CLI command to grant API Gateway permission to invoke your Lambda function
aws lambda add-permission \
--function-name YourLambdaFunctionName \
--statement-id apigateway-test-2 \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/path"Error Medic Editorial
Error Medic Editorial is a team of senior DevOps and SRE professionals dedicated to providing accurate, actionable troubleshooting guides for modern cloud infrastructure.