# Fix AWS Lambda Function Error
Lambda functions fail for many reasons: timeouts, out-of-memory errors, permission issues, runtime exceptions, and more. The error messages in the AWS console are often cryptic, leaving you to dig through CloudWatch Logs to figure out what went wrong.
This guide walks through the most common Lambda errors and how to diagnose them systematically.
Diagnosis Commands
Start by checking the function's recent invocations and errors:
aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime,Timeout,MemorySize]' --output tableGet detailed information about a specific function:
aws lambda get-function-configuration \
--function-name my-function \
--query '{Name:FunctionName,Runtime:Runtime,Timeout:Timeout,MemorySize:MemorySize,Role:Role,Handler:Handler,LastModified:LastModified}'Check recent errors through CloudWatch:
aws logs filter-log-events \
--log-group-name /aws/lambda/my-function \
--start-time $(date -u -d '1 hour ago' +%s)000 \
--filter-pattern "ERROR\|Exception\|Traceback" \
--query 'events[*].message' \
--output textIf you see timeouts or memory issues, check the function's metrics:
aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name Duration \
--dimensions Name=FunctionName,Value=my-function \
--start-time $(date -u -d '24 hours ago' +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 3600 \
--statistics Average,Maximum \
--output tableCheck for memory usage patterns:
aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name MemoryUtilization \
--dimensions Name=FunctionName,Value=my-function \
--start-time $(date -u -d '24 hours ago' +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 3600 \
--statistics Maximum \
--output tableTest the function directly with a test event:
aws lambda invoke \
--function-name my-function \
--payload '{"key": "value"}' \
--cli-binary-format raw-in-base64-out \
response.json && cat response.jsonCheck the execution role's permissions:
aws iam list-attached-role-policies \
--role-name $(aws lambda get-function-configuration --function-name my-function --query 'Role' --output text | cut -d'/' -f2)Common Causes and Solutions
Timeout Errors
The error message typically looks like: Task timed out after 30.00 seconds
Lambda has a default timeout of 3 seconds, which is often too short. Increase the timeout:
aws lambda update-function-configuration \
--function-name my-function \
--timeout 60Maximum timeout is 15 minutes (900 seconds). If you need longer, consider using Step Functions or ECS/Fargate.
Before increasing timeout, identify *why* the function is slow. Add logging around slow operations:
```python import logging import time logger = logging.getLogger() logger.setLevel(logging.INFO)
def lambda_handler(event, context): logger.info("Starting function execution")
start = time.time() # Your slow operation here result = slow_operation() logger.info(f"Slow operation took {time.time() - start:.2f} seconds")
return result ```
Common causes of timeouts: - Database queries without connection pooling - HTTP requests without timeouts - Large file processing - Circular dependencies in code
Set timeouts on external calls:
```python import requests from botocore.config import Config
# For HTTP requests response = requests.get(url, timeout=10)
# For boto3 clients config = Config(connect_timeout=5, read_timeout=10) s3 = boto3.client('s3', config=config) ```
Out of Memory Errors
The error message might show: Runtime.ExitError or simply fail without clear message.
Check memory usage in CloudWatch logs. Lambda reports memory used after each invocation:
REPORT RequestId: 12345678-1234-1234-1234-123456789012 Duration: 123.45 ms Billed Duration: 124 ms Memory Size: 128 MB Max Memory Used: 125 MBIf "Max Memory Used" is close to "Memory Size", increase memory:
aws lambda update-function-configuration \
--function-name my-function \
--memory-size 512In Lambda, more memory also means more CPU power. A function with 256 MB gets twice the CPU as one with 128 MB. Sometimes increasing memory actually *reduces* duration and cost.
Permission Errors
Common error: AccessDeniedException or User: arn:aws:sts::... is not authorized to perform: ...
Check what permissions the execution role has:
aws iam get-role-policy \
--role-name lambda-execution-role \
--policy-name my-policyOr for managed policies:
aws iam list-attached-role-policies \
--role-name lambda-execution-roleAdd the required permissions. For example, to add S3 access:
aws iam attach-role-policy \
--role-name lambda-execution-role \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccessFor a more targeted inline policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
}
]
}Apply it:
aws iam put-role-policy \
--role-name lambda-execution-role \
--policy-name S3AccessPolicy \
--policy-document file://policy.jsonRuntime Errors
Python exceptions show up clearly in logs:
aws logs tail /aws/lambda/my-function --since 1h --format shortFor Node.js, check for unhandled promise rejections:
exports.handler = async (event) => {
try {
const result = await someAsyncOperation();
return result;
} catch (error) {
console.error('Error:', error);
throw error;
}
};Add proper error handling:
def lambda_handler(event, context):
try:
# Main logic
result = process_event(event)
return {
'statusCode': 200,
'body': json.dumps(result)
}
except ValueError as e:
return {
'statusCode': 400,
'body': json.dumps({'error': str(e)})
}
except Exception as e:
logger.exception("Unexpected error")
return {
'statusCode': 500,
'body': json.dumps({'error': 'Internal server error'})
}Cold Start Issues
Cold starts happen when Lambda creates a new container for your function. They're noticeable as delays of several seconds before execution begins.
Check if cold starts are the issue:
aws logs filter-log-events \
--log-group-name /aws/lambda/my-function \
--start-time $(date -u -d '1 hour ago' +%s)000 \
--query 'events[*].message' \
--output text | grep -i "INIT_START"Cold start indicators in logs:
- INIT_START message
- First invocation after function update
- First invocation after period of inactivity
Solutions for cold starts:
- 1.Increase memory - More memory = faster initialization
- 2.Use Provisioned Concurrency for critical functions:
aws lambda put-provisioned-concurrency-config \
--function-name my-function \
--provisioned-concurrent-executions 5- 1.Minimize dependencies - Smaller deployment packages initialize faster
- 2.Use Lambda SnapStart (Java functions):
aws lambda update-function-configuration \
--function-name my-java-function \
--snap-start ApplyOn=PublishedVersionsEnvironment Variable Issues
Missing or invalid environment variables cause failures:
aws lambda get-function-configuration \
--function-name my-function \
--query 'Environment.Variables' \
--output jsonUpdate environment variables:
aws lambda update-function-configuration \
--function-name my-function \
--environment Variables={DB_HOST=mydb.example.com,DB_PORT=5432}For sensitive values, use Lambda environment variable encryption or AWS Secrets Manager:
aws lambda update-function-configuration \
--function-name my-function \
--environment Variables={DB_PASSWORD=secret} \
--kms-key-arn arn:aws:kms:us-east-1:123456789012:key/abcd1234Verification Steps
After making changes, test the function:
```bash # Invoke with test payload aws lambda invoke \ --function-name my-function \ --payload '{"test": "data"}' \ --cli-binary-format raw-in-base64-out \ response.json
# Check response cat response.json
# Check recent logs for errors aws logs tail /aws/lambda/my-function --since 10m ```
Monitor the function's error rate:
aws cloudwatch get-metric-statistics \
--namespace AWS/Lambda \
--metric-name Errors \
--dimensions Name=FunctionName,Value=my-function \
--start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ) \
--end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
--period 300 \
--statistics Sum \
--output tableSet up an alarm for errors:
aws cloudwatch put-metric-alarm \
--alarm-name lambda-errors-my-function \
--alarm-description "Lambda function errors" \
--namespace AWS/Lambda \
--metric-name Errors \
--dimensions Name=FunctionName,Value=my-function \
--statistic Sum \
--period 60 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--evaluation-periods 1 \
--alarm-actions arn:aws:sns:us-east-1:123456789012:my-alerts