Solve - AWS Lambda Task timed out


Borislav Hadzhiev

Wed Sep 29 20213 min read


Photo by Jimmy Conover

Solving - AWS Lambda Task timed out #

The "Task timed out after X seconds" error occurs because a lambda function's execution has exceeded its configured timeout.

To view a lambda function's timeout:

  1. Open the AWS lambda console
  2. Click on the function's name
  3. Click on the Configuration tab and select General configuration

general lambda configuration

To solve the "Task timed out after X seconds" error in AWS lambda, you have to:

  1. Increase the function's timeout. The default value is 3 seconds , the maximum is 15 minutes.
  2. Increase the function's memory. By default it's set to 128 Mb which is way too low and ads onto the function's execution time, which increases cost.
I've found that setting a lambda function's memory to 1024 Mb ends up saving me money most of the time, due to the reduced execution time of the function.
Increasing the function's memory also increases its CPU.
  1. Initialize your AWS SDKs and other time consuming tasks outside of the lambda function's handler.
The handler runs every time the function is invoked, whereas the code outside the handler is only ran on initialization (the first time).

This example initializes the AWS SNS SDK outside of a lambda function's handler. The example is in Node.js, however the technique applies to any programming language:

const AWS = require("aws-sdk"); // 👇️ Initialize expensive code here // this only runs once let sns = new AWS.SNS({region: 'us-east-1'}); exports.handler = async event => { if (!sns) { // 👇️ should not run, but just to be safe sns = new AWS.SNS({region: 'us-east-1'}); } // your code here 👇️ }
  1. Read your function's CloudWatch logs, make sure there aren't any permissions your function is lacking. You can view your function's logs by clicking on the Monitor tab and then View logs in CloudWatch

view logs in cloudwatch

  1. Have the correct setup in place if your Lambda function is in a VPC and trying to access the internet.

If your lambda function is in a VPC and trying to access the internet it might time out if you don't have the correct setup, namely:

  • the function has to have permissions to create and manage elastic network interfaces (virtual network cards)
  • the function has to be placed in a private subnet with a route table rule pointing to a NAT gateway or NAT instance. The NAT Gateway has to be provisioned in a public subnet and has to have a public IP address in order to access the internet through the VPC's Internet Gateway.
  • the function's security group has to allow the necessary outbound access

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.