Node Cold Starts
Reducing Node Cold Starts
Nothing has chased more people away from Lambdas and back to containers than cold start performance so I wanted to document a couple of things I found that helped so I don’t have to rediscover them in the future
The largest impact by far will most likely be the size of the zip file used to set up your environment, so that is what we will focus on
NodeJSFunction
instead of lambda.Function
Using NodeJSFunction instead of lambda.Function gives, beyond free transpiling, pointing to the handler’s ts file adds a lot of free tree shaking, referencing only the packages that are needed for that lambda with some exceptions (it doesn’t seem to treeshake cdk packages for instance)
devDependencies
Often when using CDK, its super easy to be lazy and use one package.json for both your lambda and it’s CDK. This actually works surprisingly well as long as you properly use devDependencies. Making sure to move any CDK, types, esbuild etc to devDependencies allows you to minimize your toil here while keeping the lambda’s zip package small
externalModules
AWS uses custom nodejs images which already have the AWS SDK and a few other items installed, anywhere you reference them in your package.json, adding them or `@aws-sdk/*’ to your externalModules under bundling will not package them in the lamda’s zip file and will use the ones already in the image. You are better served adding you specific @aws-sdk modules rather than using * though as there is a cost to linking them
minify
Setting minify to true on your lambda may save additional size, but may make your stack traces a bit less helpful. I would test this on and off and evaluate
tsconfig
Being careful in your tsconfig with include and exclude folders can have a large impact on your lambda size
esbuild
Just adding esbuild so it is used instead of docker, without adding any extra config, will greatly reduce cold start times
While using this combination with lambdas I have authored, typically reduced cold starts from ~1 second to ~200ms.
One quick way to get accurate cold start information from your handlers is to add your incoming context to your logger on the first line, if you are using the aws logger powertools