2
votes

I'm researching on Serverless applications using AWS Lambda and NodeJS.

I was looking into using Webpack to bundle all my NodeJS backend code into a single JavaScript file, and to use features like tree shaking.

For the way I understand Node works, imports (or requires) are resolved in runtime.

I'm afraid that bundling everything in a single file will affect my app's performance by always loading the entire JS file, instead of only loading the JS files as they are resolved during the code's execution. For a small application, the impact my be small, but as my app grows, the bundle will too.

I could create multiple bundles, one for each of my Lambda functions, but my question is: Is my concern valid?

In a mere NodeJS context, will bundling everything in a single file affect my performance, even by a small amount?

Note: AWS Lambda does support ES5 so using Webpack just to transpile is not a factor in here.

1

1 Answers

3
votes

I think on the contrary it can improve the performance during the "warm up" of a Lambda.

Indeed when a Lambda is invoked for the first time or infrequently invoked, a container will be initialized and that is when require() will load the node modules. As require() is asynchronous and can search for files in many places, having many files to load may slow down this invocation.

Note that once the "warm up" is done, the modules will already be loaded for next invocations and using a single file will not be an advantage anymore.

You can have some problems trying to use Webpack with some node modules that are not supposed to be executed in a browser (like ORMs for example) because they can contain some dynamic require() (using a variable as the parameter of require()).


To summarize, calling require() on a very big file should not be a big concern compared to calling require() on a lot of small files. But using Webpack can add complexity and if your lambda does not need to "warm up" very often, there is no difference.