I’ve been working on deploying a few AWS Lambda functions using the Serverless Framework and have a couple of questions regarding the organization of my deployment packages. I understand that it’s possible to package each Lambda function into a separate JAR file, which makes sense for functions that are largely independent. However, I also understand that related Lambda functions can be grouped together into a single JAR file to improve deployment efficiency and manageability.
So, my first question is: when deploying AWS Lambda functions using the Serverless Framework, is it a common or best practice to create a separate JAR file for each Lambda function, or should I be grouping related functions together into a single JAR file? Additionally, if I choose to package multiple Lambda functions into a single JAR file, I’m curious to know what happens when one of the functions is invoked. Specifically, when I call one function, do all other functions defined in the JAR also get loaded, or does AWS Lambda only load the function that’s actually being invoked? Any advice or experience you could share on these matters would be greatly appreciated. Thanks in advance!
If you deploy one JAR, the entire JAR is being loaded into the runtime. This is not much of an issue if it's rather small or has only a few dependencies. However, it can become an issue once the JAR becomes larger because that not only increases startup time, but also its memory footprint.
As an example: It is highly recommended to resolve resource-intensive dependencies (e.g. establishing a database connection) outside the handler function so that it can be reused between Lambda function invocations. If some of your function calls don't require these resource, they will still be impacted, at least in terms of memory and CPU requirement.
Like everything, it essentially comes down to a trade-off between manageability and performance. For very small functions that all use the same resources, I might package them into one JAR. If they have different dependencies, I'd definitely break them each into their own.
For a deep dive into this topic, check out this great article by AWS Serverless Hero Yan Cui: AWS Lambda — should you have few monolithic functions or many single-purposed functions?