Async AWS Lambda not executed if caller returns too early

1.2k views Asked by At

I'm trying to call an async lambda function from within another lambda function, and I'm finding that it doesn't get executed if the calling function exits too quickly.

In other words, the following doesn't ever work. LambdaFunction2 never gets called.

function lambdaFunction1(event, context) {
  callLambdaFunction2();
  context.done(null);
}

But adding a small delay before LambdaFunction1 exits does tend to work so far:

function lambdaFunction1(event, context) {
  callLambdaFunction2();
  setTimeout(
    function() {
     context.done(null);
    }, 500
  );
}

What concerns me is that waiting 500ms is a rather arbitrary magic number. Has anyone encountered a similar problem and found a more principled fix?

1

There are 1 answers

0
h-kippo On

callLambdaFunction2() probably does not complete before context.done(null) causes handler to exit.

To fix this you would need to call context.done as a callback. For example:

lambda.invoke({
    FunctionName: "functionName",
    InvocationType: 'Event',
    Payload: JSON.stringify(event)
}, function(err, data) {
    if (err) return context.done(err, null);
    return context.done(null, data);
});

If this is not the solution, can you show how you have implemented callLambdaFunction2?