patternjavascriptTip
Lambda Layers for sharing dependencies across functions without increasing deployment package size
Viewed 0 times
lambda layersshared dependenciesnodejs layerlayer versioning/opt250MB limitlayer structure
aws-lambda
Error Messages
Problem
Multiple Lambda functions share the same heavy dependencies (e.g., AWS SDK clients, PDF libraries, custom utilities), causing each function to have a large deployment package and slow updates.
Solution
Extract shared dependencies into a Lambda Layer. Publish the layer and reference it by ARN from each function. The layer contents are mounted at /opt in the execution environment. Limit layers to 5 per function; total unzipped size must be under 250MB.
// Layer structure (published as a zip):
// nodejs/node_modules/@aws-sdk/... (for Node.js runtimes)
// In CDK:
const sharedLayer = new lambda.LayerVersion(this, 'SharedDeps', {
code: lambda.Code.fromAsset('layers/shared'),
compatibleRuntimes: [lambda.Runtime.NODEJS_20_X],
});
new lambda.Function(this, 'MyFn', {
layers: [sharedLayer],
// ...
});Why
Lambda Layers let you share code and data across functions without bundling it into every deployment artifact. They are cached in the execution environment, reducing download time and storage costs.
Gotchas
- Layer path for Node.js must be nodejs/node_modules/ inside the zip — wrong structure means modules not found
- Layers are versioned and immutable — updating a layer creates a new version; functions must be updated to reference the new version ARN
- You can use up to 5 layers per function; combined unzipped size (function + layers) must be under 250MB
- Layers are region-specific — a layer in us-east-1 cannot be used by a function in eu-west-1
- Do not put secrets or environment-specific config in layers — use environment variables or Secrets Manager
Code Snippets
Building and publishing a Node.js Lambda Layer with correct directory structure
# Correct layer directory structure for Node.js
mkdir -p layer/nodejs
cd layer/nodejs
npm install some-heavy-library
cd ..
zip -r ../my-layer.zip nodejs/
# Publish
aws lambda publish-layer-version --layer-name my-shared-layer --zip-file fileb://../my-layer.zip --compatible-runtimes nodejs20.xContext
Managing shared dependencies across multiple Lambda functions in a monorepo or microservices architecture
Revisions (0)
No revisions yet.