AWS Lambda Task timed out error [Solved]

avatar

Borislav Hadzhiev

Last updated: Jul 28, 2022

banner

Photo from Unsplash

AWS Lambda Task timed out error [Solved] #

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:

  1. Increase the function's timeout. The default value is 3 seconds and 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 adds to the function's execution time.
I've found that setting a lambda function's memory to 1024 Mb ends up saving me money due to the reduced execution time.
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 run on initialization (the first time).

The following 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.

initialize-expensive-tasks-outside-handler
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 and 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 a 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.