devansvd
devansvd

Reputation: 1019

Aws Lambda call to external api after callback

I have a lambda function that sends http call to a API(Let's say 'A'). After getting response from 'A' Immediately return the stuff's to the caller i.e., (callback(null, success)) within 10secs. Then save the Data fetched from API 'A' to My External API(Let's Say 'B').

I tried like below but Lambda waits until event loop is empty(It is waiting for the response from second http call).

I doesn't want to set the eventLoopWaitEmpty to false since it freezes the eventloop and Execute next time when invoked.

request.get({url: endpointUrlA}, 
  function (errorA, responseA, bodyA) {

     callback(null, "success");

    request.post({url: endpointUrlB,  
          body: bodyA,
          json: true}, function(errorB, responseB, bodyB){

         //Doesn't want to wait for this response
    });

/* Also tried the callback(null, "success"); here too

});

Anybody have any thoughts on How can I implement this? Thanks!

PS - Btw I read the Previous similar questions doesn't seems to clear with those.

Upvotes: 2

Views: 988

Answers (1)

mcfinnigan
mcfinnigan

Reputation: 11638

This seems like a good candidate for breaking up this lambda into two lambdas with some support code.

  1. First lambda recieves request to 'A' and places a message onto SQS. It then returns to the caller the success status.
  2. A separate process monitors the SQS queue and invokes a second Lambda on it when a message becomes available.

This has several benefits.

Firstly, you no longer have a long-running lambda waiting for a second system that may be down to return. Secondly, you're doing things asynchronously in the background.

Take a look at this blog post for an overview of how this could work in practice.

Upvotes: 4

Related Questions