# 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:

bash
aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime,Timeout,MemorySize]' --output table

Get detailed information about a specific function:

bash
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:

bash
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 text

If you see timeouts or memory issues, check the function's metrics:

bash
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 table

Check for memory usage patterns:

bash
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 table

Test the function directly with a test event:

bash
aws lambda invoke \
  --function-name my-function \
  --payload '{"key": "value"}' \
  --cli-binary-format raw-in-base64-out \
  response.json && cat response.json

Check the execution role's permissions:

bash
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:

bash
aws lambda update-function-configuration \
  --function-name my-function \
  --timeout 60

Maximum 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:

bash
REPORT RequestId: 12345678-1234-1234-1234-123456789012	Duration: 123.45 ms	Billed Duration: 124 ms	Memory Size: 128 MB	Max Memory Used: 125 MB

If "Max Memory Used" is close to "Memory Size", increase memory:

bash
aws lambda update-function-configuration \
  --function-name my-function \
  --memory-size 512

In 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:

bash
aws iam get-role-policy \
  --role-name lambda-execution-role \
  --policy-name my-policy

Or for managed policies:

bash
aws iam list-attached-role-policies \
  --role-name lambda-execution-role

Add the required permissions. For example, to add S3 access:

bash
aws iam attach-role-policy \
  --role-name lambda-execution-role \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

For a more targeted inline policy:

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::my-bucket/*"
    }
  ]
}

Apply it:

bash
aws iam put-role-policy \
  --role-name lambda-execution-role \
  --policy-name S3AccessPolicy \
  --policy-document file://policy.json

Runtime Errors

Python exceptions show up clearly in logs:

bash
aws logs tail /aws/lambda/my-function --since 1h --format short

For Node.js, check for unhandled promise rejections:

javascript
exports.handler = async (event) => {
  try {
    const result = await someAsyncOperation();
    return result;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
};

Add proper error handling:

python
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:

bash
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. 1.Increase memory - More memory = faster initialization
  2. 2.Use Provisioned Concurrency for critical functions:
bash
aws lambda put-provisioned-concurrency-config \
  --function-name my-function \
  --provisioned-concurrent-executions 5
  1. 1.Minimize dependencies - Smaller deployment packages initialize faster
  2. 2.Use Lambda SnapStart (Java functions):
bash
aws lambda update-function-configuration \
  --function-name my-java-function \
  --snap-start ApplyOn=PublishedVersions

Environment Variable Issues

Missing or invalid environment variables cause failures:

bash
aws lambda get-function-configuration \
  --function-name my-function \
  --query 'Environment.Variables' \
  --output json

Update environment variables:

bash
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:

bash
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/abcd1234

Verification 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:

bash
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 table

Set up an alarm for errors:

bash
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