Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my AWS Lambda function keep timing out?

I have an AWS Lambda function running on node.js 8.10. This function connects to a Redis server using the ioredis library, gets a value at a key, and then returns the value. I can see in the logs that the connection is successful, and that the value is successfully retrieved. However, the response is never returned and if I look in the logs I can see the the lambda always times out.

Why does this keep happening? Is there some reason that the lambda keeps running instead of returning the value from Redis?

This is the code in my lambda function:

const Redis = require('ioredis');
const redis = new Redis(6379, 'http://redis.example.com');

exports.handler = async (event, context) => {
  const value = await redis.get('mykey');
  console.log('value', value);  // this shows up in Cloudwatch logs
  return value;
};
like image 677
geresader Avatar asked Apr 28 '19 21:04

geresader


2 Answers

The short answer: Just set event.callbackWaitsForEmptyEventLoop = false.

exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false;
  ...
};

Why does this matter?

The default behavior of a NodeJS runtime in AWS Lambda is to wait for the javascript event loop to be empty before ending the execution of the lambda and returning a value. You can read more about how AWS Lambda and the node.js event loop works here.

So what is happening with your lambda function currently is that the connection to Redis is keeping the event loop open, thus preventing your function from ever ending the execution successfully.

like image 91
Daniel Cottone Avatar answered Sep 20 '22 20:09

Daniel Cottone


Or you can close the Redis connection.

like image 35
Harsh Srivastava Avatar answered Sep 21 '22 20:09

Harsh Srivastava