Chatwithcloud logo

ChatWithCloud

AWS GenAI Tools

Calling Lambda Functions from Another Lambda Function: A Comprehensive Guide

AWS Lambda is a service that enables you to run your code without provisioning or managing servers. It’s in the serverless category of cloud computing services, taking away the need to worry about infrastructure management.

Occasionally, you'll need to call one Lambda function from another. This interaction could take a synchronous, asynchronous, or AWS SNS form.

Synchronous Invocation

In a synchronous invocation, the calling function waits until the called function completes its execution before proceeding. Here's an example.

import { Lambda } from "aws-sdk"; import { promisify } from "util"; const lambda = new Lambda(); async function callLambdaFunction() { const params = { FunctionName: "myFunction", // the name of the Lambda function you want to call InvocationType: "RequestResponse", // for synchronous invocation Payload: JSON.stringify({ key: "value" }), }; const result = await lambda.invoke(params).promise(); console.log(result); }

Asynchronous Invocation

In an asynchronous invocation, the calling function doesn't wait for the called function to finish executing. The calling function triggers the called function and moves on to the next task.

async function callLambdaFunction() { const params = { FunctionName: "myFunction", // the name of the Lambda function you want to call InvocationType: "Event", // for asynchronous invocation Payload: JSON.stringify({ key: "value" }), }; const result = await lambda.invoke(params).promise(); console.log(result); }

Invocation via AWS SNS

Sometimes, you may want to call another Lambda function via AWS Simple Notification Service (SNS). Here, extra Lambda permissions are needed to allow SNS to invoke your Lambda function.

import { SNS } from "aws-sdk"; const sns = new SNS(); async function callLambdaFunctionViaSNS() { const params = { Message: JSON.stringify({ key: "value" }), TopicArn: "arn:aws:sns:us-west-2:123456789012:MyTopic", }; const result = await sns.publish(params).promise(); console.log(result); }

Limitations and Caveats

Choosing the appropriate invocation method depends on your particular use case. ACKnowledge these considerations before implementing one method over the other to ensure your application maintains performance and availability.

Note: The calling AWS Lambda function requires the 'lambda:InvokeFunction' permission for synchronous and asynchronous invocations. The SNS service also needs ‘sns:Publish’ permission for invoking Lambda function via SNS.