Skill 118 · Debugging Lambda Timeouts
Subchapter 118.1
references/lambda-timeout-debugging.mdMarkdown16 KBView on GitHub
This SOP systematically investigates Lambda function timeout failures by analyzing function configuration, CloudWatch logs, metrics, dependencies, and code patterns. It identifies common causes of timeouts such as insufficient timeout settings, external service delays, database connection issues, memory constraints, and inefficient code patterns, then provides specific recommendations for resolution.
Prompt the user in a single message to provide all required parameters at once. Clearly list the required parameters and their descriptions, and include any optional parameters with their default values. Do not proceed until you have received and confirmed all required parameters. If any required parameter is missing or unclear, you MUST explicitly request the missing information before moving forward.
Only proceed to the steps below if you have all required information.
Check for required tools and warn the user if any are missing.
Constraints:
Retrieve the Lambda function configuration to understand current timeout and memory settings.
Constraints:
call_aws tool with the command: aws lambda get-function-configuration --function-name ${function_name} --region ${region}Examine Lambda metrics to understand timeout patterns and performance trends.
Constraints:
call_aws tool with the command: aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name Duration --dimensions Name=FunctionName,Value=${function_name} --start-time ${start_time} --end-time ${end_time} --period 3600 --statistics Average Maximum --region ${region}aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name Errors --dimensions Name=FunctionName,Value=${function_name} --start-time ${start_time} --end-time ${end_time} --period 3600 --statistics Sum --region ${region}Verify the log group exists and determine the available time range for analysis.
Constraints:
call_aws tool with the command: aws logs describe-log-groups --log-group-name-prefix /aws/lambda/${function_name} --region ${region}aws logs describe-log-streams --log-group-name /aws/lambda/${function_name} --order-by LastEventTime --descending --max-items 10 --region ${region}Search CloudWatch logs for timeout-related errors and performance patterns.
Constraints:
lastEventTimestamp from the log streams as the reference point for time calculationslastEventTimestamp from the log streams response (step 4)call_aws tool with the command: aws logs start-query --log-group-name /aws/lambda/${function_name} --start-time ${start_timestamp} --end-time ${end_timestamp} --query-string 'fields @timestamp, @message | filter @message like /(?i)(timeout|task timed out|duration)/ | sort @timestamp desc | limit 50' --region ${region}aws logs start-query --log-group-name /aws/lambda/${function_name} --start-time ${start_timestamp} --end-time ${end_timestamp} --query-string 'fields @timestamp, @message | filter @message like /(?i)(error|exception|fail)/ | sort @timestamp desc | limit 50' --region ${region}aws logs start-query --log-group-name /aws/lambda/${function_name} --start-time ${start_timestamp} --end-time ${end_timestamp} --query-string 'fields @timestamp, @message | filter @message like /(?i)(start|end|duration|memory)/ | sort @timestamp desc | limit 50' --region ${region}aws logs start-query --log-group-name /aws/lambda/${function_name} --start-time ${start_timestamp} --end-time ${end_timestamp} --query-string 'filter @type = "REPORT" | stats avg(@maxMemoryUsed) as avgMemory, max(@maxMemoryUsed) as peakMemory by bin(1h)' --region ${region}Poll for completion and retrieve results from all CloudWatch Logs queries.
Constraints:
aws logs get-query-results --query-id ${query_id} --region ${region}If lambda_code parameter is provided, analyze the code for potential timeout issues.
Constraints:
Identify external dependencies that could cause timeouts.
Constraints:
call_aws tool with the command: aws lambda get-function-configuration --function-name ${function_name} --region ${region}Investigate related AWS services that might be causing delays.
Constraints:
Examine cold start behavior and its impact on timeouts.
Constraints:
call_aws tool with the command: aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name InitDuration --dimensions Name=FunctionName,Value=${function_name} --start-time ${start_time} --end-time ${end_time} --period 3600 --statistics Average Maximum --region ${region}Create specific, actionable recommendations based on the analysis.
Constraints:
Combine all findings into a comprehensive debugging report.
Constraints:
function_name: my-api-handler
region: us-east-1
time_window_hours: 48
lambda_code: |
import requests
import json
def lambda_handler(event, context):
# This could cause timeouts - no timeout set
response = requests.get('https://api.example.com/data')
return {
'statusCode': 200,
'body': json.dumps(response.json())
}# Lambda Timeout Debugging Report
**Function:** my-api-handler
**Region:** us-east-1
**Analysis Period:** Last 48 hours
## Executive Summary
- 23 timeout errors detected in the last 48 hours
- Average function duration: 8.2 seconds (approaching 10-second timeout)
- Root cause: External API calls with no timeout configuration
## Function Configuration
- Current timeout: 10 seconds
- Memory allocation: 512 MB
- Runtime: Python 3.9
- VPC configuration: Yes (may add latency)
## Key Findings
1. **External API Delays**: Function makes unoptimized calls to external APIs
2. **No Timeout Configuration**: External calls have no timeout settings
3. **Memory Pressure**: Average memory usage at 89% of allocation
4. **Cold Start Impact**: 15% of timeouts occur during cold starts
5. **Code Issues**: HTTP requests without timeout configuration in the function code
## Recommendations
1. **Immediate (High Impact)**:
- Increase timeout to 30 seconds
- Add timeout configuration to external API calls: `requests.get(url, timeout=10)`
- Increase memory to 1024 MB
2. **Short-term (Medium Impact)**:
- Implement connection pooling for external APIs
- Add retry logic with exponential backoff
- Configure provisioned concurrency for critical functions
3. **Long-term (Architectural)**:
- Consider async processing for long-running operations
- Implement circuit breaker pattern for external dependencies
- Add comprehensive monitoring and alerting
4. **Code Improvements**:
- Add timeout parameter to all HTTP requests
- Implement proper error handling for network timeouts
- Consider using async/await for I/O operationsIf the Lambda function doesn’t exist, verify the function name and region. Use aws lambda list-functions --region ${region} to see available functions.
If CloudWatch logs are empty or don’t exist, the function may not have been invoked recently or logging may be disabled. Check the function’s log group configuration.
If you encounter access denied errors, verify that your AWS credentials have the necessary permissions for Lambda, CloudWatch, and related services.
If CloudWatch Logs Insights queries timeout, reduce the time window or check if the log group contains a large volume of data. Consider running analysis during off-peak hours.
If the function is in a VPC and experiencing timeouts, check NAT gateway configuration, security group rules, and subnet routing to ensure proper internet access for external API calls.
If you encounter MalformedQueryException errors indicating the time range exceeds log retention or is before log group creation:
aws logs describe-log-groupsIf you encounter ResourceNotFoundException errors for log streams:
aws logs describe-log-streamsWhen calculating timestamps for log analysis:
lastEventTimestamp from log streams to determine the most recent activity