Ethan
Ethan

Reputation: 1676

Await causing aws Lambda to timeout

I have some async code in my AWS Lambda function and no matter what async code is running it never resolves. It just causes the Lambda to timeout.

export const handler: Handler = async (event) => {
   console.log("stops after this");
   const test = new Promise(() => setTimeout(() => void 1000));

   await test;

   // Never runs 
   console.log("test");
}

Here is my the code in my stack for the lambda. It is linked to API gateway:

const api = new cdk.aws_apigatewayv2.HttpApi(this, "devpad-api");

        const projectLambda = new lambda.Function(this, "ProjectLambda", {
            runtime: lambda.Runtime.NODEJS_20_X,
            handler: "index.handler",
            code: lambda.Code.fromAsset("./lambdas/project/out/"),
            timeout: cdk.Duration.seconds(10),
            environment: {
                MONGODB_CONNECTION_STRING: process.env.MONGODB_CONNECTION_STRING || "",
                CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY || "",
            },
        });

Why is this happening?

Upvotes: 0

Views: 39

Answers (1)

swawge
swawge

Reputation: 73

The issue in your Lambda function is with the Promise creation and resolution. The current Promise never resolves because the setTimeout is not properly handled.

Your CDK stack setup looks correct, but you might want to consider, 1 - increase memory ( if needed ) 2 - Add property logging configuration 3 - Configure correct API integration

export const handler: Handler = async (event) => {
   console.log("starts here");
   
   // Method 1: Using a properly constructed Promise
   const test = new Promise((resolve) => {
       setTimeout(() => {
           resolve(true);
       }, 1000);
   });

   // OR Method 2: Using util.promisify
   // const { promisify } = require('util');
   // const sleep = promisify(setTimeout);
   // await sleep(1000);

   await test;
   console.log("test");

   return {
       statusCode: 200,
       body: JSON.stringify({ message: "Success" })
   };
}

Upvotes: 1

Related Questions