3

In Serverless, I have the following folder structure

/component_a/function_1/function_1.js (get)
/component_a/function_2/function_2.js (get)

What is the best way from function_1 to call function_2 using the Serverless Framework?

dinnouti
  • 1,517
  • 2
  • 13
  • 20

3 Answers3

2

Do not invoke function_2 from function_1.

Write the two functions to be able to complete their respective tasks independently.

In order to control the flow of execution, you should use AWS Step Functions, which lets you co-ordinate between your various lambda functions.

If you want to persist information, use another storage service (like S3 or DynamoDB) to store information that function_2 can use. Then let Step Functions direct the traffic. But check if this service exists in the region you are deploying your functions.

Here is a quick guide on AWS Step Functions:

http://docs.aws.amazon.com/step-functions/latest/dg/welcome.html

Shazic
  • 152
  • 2
  • 7
2

This depends on whether you are interested on the return value of function_2.

If you need to get the return value of function_2, you have to invoke it directly. You have two options:

  1. Invoke the Function 2 Lambda synchronously. See Lambda.invoke() from AWS-SDK docs.

  2. If you can include Function 2 in your Function 1 package (which serverless does by default), you can probably just import it directly depending on how your code is written.

If Function 1 does not need to know the response or the return value of Function 2, you should use SNS to call it asynchronously. To do this, here's one suggested approach:

  1. Create an SNS topic.
  2. Configure Function 2 to subscribe to the above SNS topic. (Serverless Docs)
  3. Have Function 1, publish a message to the SNS topic in Step 1.
Noel Llevares
  • 11,823
  • 2
  • 41
  • 72
  • 1
    You can make the Lambda.invoke() asynchronous by setting `InvocationType` to `Event` https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property – Syed Waqas Aug 09 '19 at 07:36
1

This is generally frowned upon since it creates a dependency. Directly calling other lambda functions is an option (Can an AWS Lambda function call another) however the point of lambda is for them to run in isolation. It can also be dangerous if you end up with a recursive lambda pattern. The best way is usually to communicate via SQS and SNS if you need quick response time.

Community
  • 1
  • 1