Refactoring to ServerlessExtract function invocation2 min

Description

Invoking Lambda functions asynchronously from within the function code hides the application topology inside the code. An example might look as follows:

const aws = require('aws-sdk');
const lambda = new aws.Lambda();

exports.handler = async function(event, context) {
    ...
    // Prepare invokation params 
    var params = {
        FunctionName: process.env.FUNCTION_NAME,
        InvocationType: Event,
        Payload: JSON.stringify(event),
    };
    // Invoke the destination function 
    await lambda.invoke(params).promise();
    ...
};

Solution

Use Lambda Destination to send the message asynchronously and configure the Lambda destination in CloudFormation or CDK to make the application topology explicit.

See the CDK implementation of this pattern in Typescript on GitHub.

Considerations

Advantages

  • Extracting the function invocation into a destination makes the application topology explicit and separates compsition from application logic

Applicability

  • Lambda Destinations are triggered only for asynchronous invocations. Therefore, this refactoring cannot be applied to synchronous invocations, e.g. from the console (Test). If your functions returns a synchronous result, this is now replaced by the message to be sent

  • Lambda Destinations are triggered at the end of the function execution whereas the code could send the message at any place

  • Invoking a functinon from AWS SDK allows you to set additional attributes like ClientContext, InvocationType, LogType, Qualifier. You cannot set these attributes from a Lambda destination. Setting InvocationType for example allows for synchronous invocations

  • Lambda Destinations have the option to send the response payload only via responeOnly, not the full record. This allows to easily chain asynchronous Lambda functions without having to deal with data extraction in the runtime code. (LambdaDestinationOptions)

  • Consider building event driven architectures using the other Destination types (SNS, SQS, EventBridge)

Related Refactorings

Related Resources


Created by:

Gregor Hohpe
Gregor HohpeI contemplate and write about architecture strategy, cloud, and IT transformation. In between I - extract order from chaos - dive into the engine room to give the penthouse better IT strategies - fight relentlessly against unnecessary complexity and corporate politics I've been called the ''IT transformation jester'' - unbiased, trusted, influential, and witty.
Sindhu Pillai
Sindhu PillaiAs Regional SA Lead, I focus on enterprise Education Technology customers. In my role, I guide my SA team in the delivery and execution of complex technical solutions to support our customer's business and technical goals.
Bhuvan Annamreddi
Bhuvan AnnamreddiAssociate Solutions Architect, AWS