Mastering AWS Lambda Layers: A Step-by-Step Guide to Managing Dependencies

AWS Lambda Layers let you centrally manage common dependencies like libraries, custom runtimes, or configuration files. Instead of bundling these into every function deployment, you attach a layer to multiple functions—reducing package size, speeding up deployments, and simplifying updates. This tutorial walks you through creating and using layers effectively.

Each layer is a ZIP archive containing your dependencies in a specific folder structure (e.g., python/ for Python, nodejs/node_modules/ for Node.js). When attached to a Lambda function, the layer’s content is extracted into the /opt directory, making it available at runtime. The key advantage: update a single layer and every function using it gets the new version automatically.

Article illustration

Creating a Layer

Use the AWS CLI, Console, or infrastructure-as-code tools. For a Python example with the requests library:

  • Create a folder: mkdir python && cd python
  • Install dependencies: pip install requests -t .
  • Zip the folder: cd .. && zip -r my-layer.zip python
  • Publish the layer: aws lambda publish-layer-version --layer-name my-layer --zip-file fileb://my-layer.zip --compatible-runtimes python3.9

Customizing Layer Content

Ensure the folder name matches your runtime: python/, nodejs/node_modules/, java8/lib/, or bin/ for binaries. Multiple folders can be included in one ZIP.

Attaching a Layer to a Function

During function creation or update, specify the layer ARN. Using the Console, scroll to “Layers” in the function configuration and click “Add a layer”. Or with the AWS CLI:

aws lambda update-function-configuration --function-name my-function --layers arn:aws:lambda:us-east-1:123456789012:layer:my-layer:1

You can attach up to five layers per function.

Versioning and Best Practices

Each publish creates an immutable version. Use publish-layer-version for updates and reference the version number in your function. For production, pin layer versions to avoid unexpected changes. Consider using a shared layer for common utilities and separate layers for runtime-specific dependencies.

Mastering Lambda layers keeps your serverless code lean, reusable, and easier to maintain. Start by packaging one library today and see the difference.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *