Building Lambda Layer using uv

You may have encountered this error (or a related one) when bundling Python dependencies into a Lambda layer and using it in a Lambda function:

[ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'pydantic_core._pydantic_core'
Traceback (most recent call last):

The issue occurs because the dependency was built for the wrong platform (macOS or Windows), making it incompatible with AWS Lambda's Linux runtime.

There are several ways to build the dependencies for the target platform, such as using a Dockerfile (requires Docker) or leveraging an EC2 instance specifically to create the Lambda layer.

However, in this guide, we’ll use uv to package the dependencies for the targeted platform.

Step 0:

Ensure uv is installed on your system.

Step 1:

Initialize a pyproject.toml and lock file (if not already created) in your project directory:

uv init .

Step 2:

Add the dependencies required for your Lambda function (if they’re not already listed in pyproject.toml or the lock file):

uv add pydantic
uv add boto3

Step 3:

Export the dependencies to a requirements.txt file:

uv export --format=requirements.txt > requirements.txt

Step 4:

Install the dependencies into a local python/ directory, targeting the correct platform for AWS Lambda (x86_64-manylinux2014 if the Lambda architecture is x86_64). This ensures binary compatibility. Without it, you may encounter runtime errors due to missing or incompatible binaries.

uv pip install -r requirements.txt --python-platform x86_64-manylinux2014 --target ./python

Step 5:

Zip the python/ folder and create a new Lambda layer using the archive utility. If uploading manually, keep it under 50 MB; otherwise, upload to S3 and ensure the architecture matches your Lambda function.

Step 6:

Test the Lambda function and it should work fine now.