Reduce Lambda Function size during deployment

Hi, I know this question has been asked many times on SO or Github issues. But, I did not find any good answer apart from using optimizer plugin.

So, here is my complete question is:
My entire zipped codebase is around 100kB(w/o node_modules). When serverless tries to bundle it up, the size reaches 12.4mB, which is huge. So, is there any way to load only the code, and let lambda service run yarn install?

I am skeptical that AWS lambda even provides anything like running pre-deployment hooks/scripts that run online. Or is there a workaround to making such thing happen? This would substantially reduce the zip size and should make deployment pretty quick.

It might make deployments quick but it would make cold starts really slow while packages are downloaded.

You could look at using exclude/include in your serverless.yml but that probably won’t help much.

Something like webpack and tree shaking might help (I haven’t used this).

I find the best option is to be careful with your package selection. Pay attention to the packages you’re using and which packages they depend on. It’s really easy to include one package and discover that it pulls in 10-20 dependencies. Could you have written your own function instead using the package?

1 Like

Since I am quite new to Serverless framework, so, I do not understand how exactly cold starts would affect this, reading up on that ->

“Webpack w/ tree shaking, and package selection”. Thanks for all those ideas. Will try them out and post here what works best for me. Since, I am using GraphQL, package size really matters to me not just for faster deployment, but, also for Lamda size limit.

PS: A small improvement can be made by uploading the codebase to a faster upstream which will then install dependencies and do sls deploy.

Hey @dpkshrma. It looks like I originally quoted the wrong sentence. If you found a way to get Lambda to download packages it would slow down cold starts.

Start by focusing on the packages you’re using. Are you including any you don’t really need? If you only need it for one or two things could you write the code yourself? Could you change packages for a smaller one or one with less dependencies?

Do you have development dependencies or source folders that you’re packaging?

Importantly, don’t optimize for deployment time. Optimize for execution. You mention your Lambda size, is this currently an issue? AWS reports resource usage so check with that.

It is stated as a drawback in the serverless blog here in Graph pattern. I looked up the max size that a lambda function can have, and it was 50MB(ref. Lamda function size limit)

And yes, you’re correct, I’ve got quite a few devDependencies(mostly babel, stupid of me to keep them in there after build :stuck_out_tongue:). If I exclude them alone, size would fall by a good number. Thanks again.

1 Like