Error Medic

How to Fix AWS Lambda Timeout Errors (Task timed out after 3.00 seconds)

Fix AWS Lambda 'Task timed out after 3.00 seconds' and 504 Gateway Timeout errors. Learn the root causes, default limits, and how to increase the max timeout.

Last updated:
Last verified:
1,252 words
Key Takeaways
  • The default AWS Lambda timeout is 3 seconds, which frequently causes 'Task timed out after 3.00 seconds' errors.
  • The absolute maximum AWS Lambda execution timeout limit is 900 seconds (15 minutes).
  • API Gateway has a hard timeout of 29 seconds, so increasing Lambda timeouts beyond this won't prevent 504 Gateway Timeouts.
  • Network latency (e.g., Python requests timeout, socket timeout) or cold starts are common culprits for execution delays.
Approaches to Fixing Lambda Timeouts
MethodWhen to UseTime to ImplementRisk/Drawbacks
Increase Timeout SettingWhen the function genuinely needs more time for computation or expected API latency.1 minHigher AWS costs if the function hangs; masks underlying performance issues.
Optimize Cold StartsWhen timeouts only happen on the first invocation after idle periods.1-2 hoursProvisioned concurrency adds fixed costs.
Implement Timeout HandlingTo gracefully handle external API delays (e.g., Python requests socket timeout).30 minsRequires code changes and error handling logic.
Decouple via SQS/EventBridgeWhen operations take > 29s and are behind an API Gateway.DaysArchitectural change; requires asynchronous client handling.

Understanding the Error

When working with serverless architectures, one of the most common and frustrating errors developers encounter is the AWS Lambda timeout. By default, an AWS Lambda function has a default timeout of 3 seconds. If your code execution exceeds this configured time, the AWS runtime forcibly terminates the execution environment and logs an error message exactly like:

Task timed out after 3.00 seconds or occasionally Task timed out after 3.01 seconds (due to slight billing/execution measurement rounding).

If your Lambda function is invoked synchronously via Amazon API Gateway, a timeout in the Lambda function (or the Lambda function running longer than 29 seconds) will result in an AWS Lambda 504 Gateway Timeout returned to the client.

Diagnosing the Root Cause

Before you simply increase the AWS Lambda timeout limit, it's crucial to understand why the function is timing out. Simply raising the limit can lead to inflated AWS bills and mask severe architectural flaws.

1. External Network Calls and Socket Timeouts A frequent cause of the aws lambda endpoint request timed out error is hanging network connections. For example, if you are using Python, an aws lambda python requests timeout usually occurs because the external API you are calling is slow, and you haven't set a timeout on the requests.get() call. The socket hangs, and the Lambda function hits its execution limit.

2. The Cold Start Penalty The aws lambda cold start timeout happens when a function is invoked after being idle. AWS must provision a container, load your code, and initialize the runtime. For Java or .NET, or functions attached to a VPC without optimized ENIs, this initialization can easily take 5-10 seconds, immediately crashing into the default 3-second limit.

3. API Gateway Hard Limits Many developers ask: "I changed my AWS Lambda timeout to 5 minutes, why am I still getting an AWS Lambda API Gateway timeout?" While the maximum timeout for an AWS Lambda function is measured in seconds and caps at 900 (15 minutes), API Gateway has a hard, unchangeable integration timeout of 29 seconds. If your Lambda function takes 35 seconds to process, Lambda will succeed, but API Gateway will return a 504 to the user after 29 seconds.

Step 1: How to Change and Increase the Timeout

If you have determined that your function legitimately requires more time (e.g., processing a large S3 file), you need to increase the timeout.

Via AWS Console:

  1. Go to the AWS Lambda Console.
  2. Select your function.
  3. Navigate to the Configuration tab, then General configuration.
  4. Click Edit.
  5. Adjust the Timeout setting (max 15 min / 900 sec).
  6. Click Save.

Via Infrastructure as Code (Terraform): If you are managing your infrastructure via Terraform, you can set the terraform aws lambda timeout property in your aws_lambda_function resource:

resource "aws_lambda_function" "my_processor" {
  function_name = "data_processor"
  role          = aws_iam_role.iam_for_lambda.arn
  handler       = "index.handler"
  runtime       = "nodejs18.x"
  timeout       = 30 # Timeout in seconds
}

Step 2: Implementing Proper Timeout Handling in Code

Instead of letting the AWS environment abruptly kill your function, you should handle timeouts gracefully. This is especially important for aws lambda timeout handling python or Node.js.

The AWS Lambda context object provides a method to check how much time is remaining before the execution environment is terminated.

For Python:

import time
import requests

def lambda_handler(event, context):
    # Set a timeout on external requests to prevent hanging sockets
    try:
        # Ensure the request times out BEFORE the Lambda function does
        response = requests.get('https://api.example.com/data', timeout=2.0)
    except requests.exceptions.Timeout:
        return {"statusCode": 408, "body": "External API timed out"}
        
    # Check remaining time
    time_left = context.get_remaining_time_in_millis()
    if time_left < 500: # Less than 500ms left
        print("Warning: Approaching AWS Lambda max timeout")
        return {"statusCode": 206, "body": "Partial completion"}
        
    return {"statusCode": 200, "body": "Success"}

Step 3: Architecting for Long-Running Tasks

If your task consistently hits the aws lambda function max timeout of 15 minutes, Lambda is the wrong compute choice. You should migrate the workload to AWS Fargate (ECS) or AWS Batch.

If your task takes 2 minutes and is triggered by a user via API Gateway, you will hit the 29-second API Gateway limit. To solve this, implement the Asynchronous Request-Reply pattern:

  1. API Gateway triggers a Lambda function.
  2. The Lambda function pushes a message to an SQS queue or EventBridge and immediately returns a 202 Accepted to the client along with a job_id.
  3. A separate worker Lambda function pulls from SQS and processes the 2-minute task, saving the result to DynamoDB.
  4. The client polls a status endpoint using the job_id to retrieve the final result.

Frequently Asked Questions

bash
# Use the AWS CLI to increase the timeout to 60 seconds
aws lambda update-function-configuration \
    --function-name my-processing-function \
    --timeout 60

# Check CloudWatch logs for timeout occurrences
aws logs filter-log-events \
    --log-group-name /aws/lambda/my-processing-function \
    --filter-pattern "Task timed out after" \
    --limit 10
E

Error Medic Editorial

Our SRE and DevOps experts have spent thousands of hours debugging cloud architectures. We write practical, code-first guides to help engineers resolve production incidents faster.

Sources

Related Articles in AWS Lambda

Explore More Cloud Infrastructure Guides