Invoke lambda instances from lambda and wait for the longest to comple

I have a lambda and I want to invoke multiple lambdas instance and wait for the longest to complete.

I already checked online and found very interesting threads but none of them helped me achieve what I want.

Here’s the code:

Lambda as promise

invokeVideoRenderer = (params) => {
    const param = {
      FunctionName: 'myFunction',
      InvocationType: 'Event',
      Payload: JSON.stringify({ body: params })
    };

    return new Promise(async (resolve, reject) => {
      this.lambda.invoke(param, (error, data) => {
        if (error) {
          reject(error);
        }
        resolve(data); <--- it always returns { StatusCode: 202, Payload: '' }
      });
    });
  };

the loop where I invoke the different lambdas

const promises = [...Array(totalNumberOfLambdaToInvoke).keys()].map(
    async (part: number) => {

      
      const body = {
        // body
      };

      const request = await invokeVideoRenderer(body);
      return request;
    }
  );

  const results = await Promise.all(promises); <--- here I want to wait for the longest to complete

The lambda I am invoking:

const myFunction = async (event, context, callback) => {
  try {
    //...code
    callback(null, {
      status: 200,
      body: JSON.stringify({
        status: "SUCCESS",
      }),
    });
    return;
  } catch (error) {
    callback(null, {
      status: 500,
      body: JSON.stringify({
        status: "FAILED",
        errorMessage: error,
      }),
    });
    return;
  }
};

What am I doing wrong?

Answer

An InvocationType of Event tells Lambda to invoke the child Lambda asynchronously. Hence the Lambda service responds with 202 (Accepted) response immediately. Meanwhile the child Lambda function executes.

If you want it to execute synchronously, then don’t provide an InvocationType of Event. Either remove it entirely to get the default, or explicitly set it to RequestResponse (which is the default).

Note: it’s typically not ideal to invoke Lambda functions synchronously if you can avoid it, because you are paying for both Lambdas concurrently.

Leave a Reply

Your email address will not be published. Required fields are marked *