πŸ”§ Error Fixes
Β· 2 min read

AWS Lambda: Timeout β€” How to Fix It


Task timed out after X seconds means your Lambda function didn’t finish within its configured timeout (default 3 seconds, max 15 minutes).

Why this happens

Lambda enforces a hard timeout on every invocation. The default is only 3 seconds, which is too short for most real-world workloads involving database queries, API calls, or file processing. When the function doesn’t return before the deadline, Lambda kills the process and logs the timeout error. This is especially common during cold starts or when downstream services are slow or unreachable.

What causes this error

  1. Timeout too short β€” default is 3 seconds, which is too short for most real work
  2. Slow downstream service β€” database, API, or S3 call taking too long
  3. Cold start β€” first invocation takes longer due to initialization
  4. Infinite loop or deadlock β€” code never completes

Fix 1: Increase the timeout

In serverless.yml, CloudFormation, or the AWS Console:

functions:
  myFunction:
    timeout: 30  # seconds (max 900 for 15 min)

Fix 2: Optimize cold starts

  • Use smaller deployment packages
  • Use provisioned concurrency for critical functions
  • Avoid heavy imports at the top level β€” lazy-load instead

Fix 3: Add timeouts to downstream calls

// Don't let an external API hang your Lambda
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });

Fix 4: Check for connection issues

Lambda functions in a VPC need a NAT Gateway to reach the internet. Without it, external API calls hang until timeout.

Alternative solutions

For tasks that exceed the 15-minute Lambda limit, consider using AWS Step Functions to orchestrate multiple shorter Lambda invocations. You can also offload heavy processing to AWS Fargate or ECS where there’s no execution time limit.

Prevention

  • Always set context.callbackWaitsForEmptyEventLoop = false in Node.js Lambdas to prevent open database connections from keeping the function alive.
  • Add explicit timeouts to every external HTTP call and database query so a single slow dependency can’t consume your entire Lambda timeout.

Related: Vercel Serverless Timeout Β· Cloudflare 524 Timeout