Home > Net >  How to share code between several Lambda functions?
How to share code between several Lambda functions?

Time:12-08

I have microservice that contains multiple Lambda functions.

How can I share the same code between those functions?

Lets imagine I have the following structure:

handler
|
|______ a-handler.js
|
|______ b-handler.js
|
repository
|
|______ users-repository.js

I know that AWS recommended to use Lambda Layers for that, but can I simply import the relevant code to the Lambda function?

Like that:

users-repository.js:

export getUser(...){...}; 
export createUser(...){...}; 

a-handler.js:

import {getUser} from '../repository/users-repository.js';
/.../

b-handler.js:

import {createUser} from '../repository/users-repository.js';
/.../

The build process anyway will do Tree Shaking and remove the unused code from the Lambda function, so basically it will use and build only the relevant code.

So what are the benefits of Lambda Layers?

Thanks!

CodePudding user response:

There’s no mandate to use layers to share code. The reasons I’ll end up with a layer over an include are:

  1. Separately versioned items the ops team should be able to update separate from build process
  2. Shared item is so large that including it causes bundle sizes to be unreasonably large
  3. Shared code without deployment system (Pulumi, Terraform, etc…)

Includes has more or less the opposite set of use scenarios:

  1. Dependency that will not change or be versioned separate from lambda
  2. Small dependency not worth the added complexity of a layer
  • Related