[AWS Lambda] Optimizing node_modules in zip files

Hey folks

I was recently working through setting up some lambda infrastructure, and one thing that caught me off guard was the bloat that came from my node_modules.

I can present how I solved it but I would love to hear how ya’ll are solving this problem.

Before we start, here is a reference of size limitation when using AWS Lambda:

Type size
Lambda (unzipped) 250 mb
Lambda (zipped) 50 mb
Container 10 gb

Here is my process of reducing the bloat (using a zip file):

  1. Start an install with production settings (pnpm --prod --ignore-scripts --prefer-offline )
  2. Create a dependency zip file (zip -r main.zip node_modules)
  3. Run the dev install (pnpm install)
  4. Run build (into a dist/index.js file - using esbuild with target: node so node_modules is not included in bundle)
  5. Append the built scripts into the zip file (zip -ur main.zip dist)

This works for me to reduce the bloat on the node_modules.

The only weird thing is I have to run install twice (production and dev) in my build (which isn’t that big of a deal).

I am just curious to know how everyone else is doing it ?

Edit: Include more details about build

Edit 2:

Summarizing the top suggestion here for others:

  1. Using a layer - zip the node_modules into a layer
    - Keep in mind that the size counts towards overall lambda limit and must stay under it (listed in the table above)
  2. Bundling all the required dependencies - using webpack, rollup, esbuild to bundle your code + deps into one bundle and just use that
  3. Run install using production flag (npm, pnpm, yarn)
  4. keep aws-sdk as devDependecies or mark it as “external” in your bundler

Other notes:

  1. Using Lambda layers does make local development a bit more challenging (with testing etc) so depends on your setup
  2. I/O hit with external dependency versus bundling (maybe someone from AWS can chime in ?)
  3. Bundling versus lambda layer (federated dependencies) - If you have multiple lambdas with shared dependencies then layering might work better ?

Overall a great discussion. It’s interesting to hear how everyone is solving this problem! Thanks for adding your inputs!

“Install twice”

Been there, never really dug into it.

I use some sort of module bundler e.g webpack. This will create a single index.js file that gets uploaded with only the necessary code. I’d also recommend adding a source map, so the stack traces are actually useful.

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/webpack.html

This is the best way, I do this with all my lambda with esbuild, you can reduce more space by excluding aws sdk from the bundle as it’s provided by default in lambda

+1 on excluding the aws sdk

What /u/Alfred17686 said regarding the use of a bundler is indeed the best approach.

The simple approach using --production installation

Many years ago, I started off doing something similar to what you had. I would have my typescript code compile output to a separate build folder and then I’d cp the package.json into there and run npm install --prefix ./build --production.

In my npm scripts, that looked something like:

“prebuild”: “rm -rf build && npm run test”,
“build”: “mkdir -p build && cp package*.json build/ && tsc --pretty”,
“postbuild”: “npm install --prefix ./build --production”,

Then I’d just have my SAM template point to the build folders and run my deploy script which looked something like:

#!/bin/bash
set -e
set -x
# Build the lambda function
cd ./myLambda
npm run build
cd -
# Check to make sure stack definition is valid
sam validate
# Package template and upload code to S3
sam package --template-file template.yaml --s3-bucket $YOUR_SAM_BUCKET_NAME --output-template-file packaged-template.yml
# Trigger CloudFormation change set deployment
sam deploy --template-file packaged-template.yml --stack-name $YOUR_STACK_NAME --capabilities CAPABILITY_IAM

SAM took care of the zipping and uploading of your code artifact. One important thing to remember with this approach is to make aws-sdk a devDependency if you’re looking to use the 2.x variant. This is because the Node 14 and below runtimes (which are all that exist today) include it on disk already.

The better approach: Bundling

We can do better than the approach above using code bundling. It has many advantages:

  • The cold start can load a single file and skip a lot of the IO overhead of chain-requiring a ton of files on initialization. You can still have your setup broken up into multiple chunks if one big blob is too much, but it’s much more performance friendly either way.
  • Code bundlers will remove the extraneous stuff that’s often published in NPM packages (readmes, changelogs, test code, multiple dist variants for different runtimes, etc). This alone reduces size by a TON.
  • Code bundlers can perform tree shaking to remove dead code that isn’t used.
  • Code bundlers can minify the JS code to reduce size further.
  • Code bundlers will only load libraries that are actually used in the defined entry point.

The downsides are that you may have some libraries that do very dynamic requires or fs.readFile calls that would require configuration to make sure those assets are still available.

I created a small project to showcase the impact that running a bundle optimizer with tree shaking has for a node project. The project had axios, lodash, and date-fns as main dependencies and a ton of dev dependencies like typescript, eslint, prettier, etc. A minimal webpack config was used.

Using just --production dep reduction

Size of node_modules with both regular and dev deps installed: 149MB
Size of node_modules with --production: 27MB
Size of own codebase: 4KB
Size of build artifacts before zipping: 27MB
Size of build artifacts after zipping: 3.9MB

# Using webpack bundler
Size of build artifact bundled without minification: 256KB
Size of build artifacts bundled/minified: 68KB
Size of build artifacts bundled/minified/zipped: 24KB

Size of source map: 324KB
Size of source map gzipped: 92KB

The deployed zip size goes from 3.9MB to 24KB in this simple example. Note that it’s important to mark the aws-sdk as an external dep so bundlers avoid repackaging it.

However, I’d recommend not using webpack specifically these days. If you’re using the AWS CDK’s NodeJS lambda constructs, they actually already default to bundling using ESBuild out of the box with zero config needed. I’d also consider looking into Vite as an alternative if you’re concerned about how stable/production-ready ESBuild is.

A quick note regarding source maps: You can upload to a service like Sentry and leverage their Lambda extension so you don’t mess with performance of the actual runtime for synchronously invoked lambdas. For async ones, you may be better off with the simpler approach of adding a import 'source-map-support/register' at the top of your entry point.

TL;DR: Bundling is the way to go. ESBuild/Vite are my recommendations, but Webpack works too.

Great tips.

Don’t forget an alternative is layers. Put just the node_modules in a separate layer and have just your code in the lambda. Works like a charm and you get to be able to edit / debug your lambda inside the console editor. Lifesaving sometimes.

I use yarn with prod build mode. For multiple lambdas with shared dependencies, I put the node-modules in a layer.

This seems to work and I have only hit issues where there was a mistake - like bundling unnecessary peer dependencies, or including dev libs, etc…

Layers are great. The only caveat with them is that they have to exist prior to deploying your Lambda code. You can’t deploy a Lambda and its Layer dependency in the same step. I had to have a Cloudformation stack devoted to Layers.

The bundling approach is interesting but I never tried it because the way I see it, you almost never have one Lambda in a project. Many of those Lambdas will share dependencies and common code, which is literally what Lambda layers are made for.

So what you’d do for example is have a layers/NodeLayer folder and under it you’d have your common library and a special nodejs which is home for your production node_modules.

Your build installs production to that path, you could copy your package files to it in case it didn’t work without it.

You’d reference your common from /opt/common or /opt/lib or /opt/banana, however you named it, and the nodejs is already in your lambda path, so you don’t have to worry about its packages.

This keeps your Lambdas’ cloud code intact in case you want to debug things live, while reducing its size. The only downside is local dev if you’re using that. Layers are a paid feature in LocalStack and I don’t know much about it in SAM. And for unit testing you’d have to find a way to symlink your common library to /opt/* or use Docker volumes and run your tests in a container

In cdk it works perfectly in different stacks.

Ah cool glad that’s an option now.

Unless you’re using sdk v3

One quick tip. If you’re using version 2.x of aws-sdkdon’t include it in your upload.The environment comes with it anyway.

Not sure I completely understand. You can have an AWS::Lambda::LayerVersion in the same stack as an AWS::Lambda::Function that uses the layer. What errors do you get?

For nodejs/javascript functions you really should be using esbuild https://github.com/evanw/esbuild

Its faster and easier to setup that webpack and drastically reduces the size of the archive. For Serverless framework users there is https://github.com/floydspace/serverless-esbuild and if you use SAM CLI, you already get this for free since they now use esbuild in the build process

Use -9 for max compression:

zip -9r main.zip node_modules

You can find duplicate package versions in node_modules with npm dedupe dry-run. From there either run without dry-run or modify your package-lock.json by hand. With a good test suite you can pretty confidently purge dupicates even if they otherwise would not satisfy a package’s requirements.

The newer versions of the cdk support layers in the the Function API. Meaning you can build your layer version in the same stack without making more complicated handling in your code.

Can confirm the cdk nodejs constructs are awesome. One downside with it is if you have a lot of functions with its own handlers, it’s gonna build all those separately sequencial which takes time everytime you synthesise/deploy.