Hendrik Jan van Randen
Hendrik Jan van Randen

Reputation: 348

Limit jar size in AWS Lambda functions with many code reuse permutations

We have many Lambda functions written in Java, which reuse code in many permutations: Lambda functions A and B use a common piece of code, Lambda functions B and C use another common piece of code, etc.

If we put all this reused code in each Lambda, or in a Layer that's used by all Lambdas, each cold start of a Lambda loads a lot of code that's not used by that Lambda, causing a significant delay in the cold start.

It is quite a puzzle to manually move all code to Layers or dependencies that are only used in the Lambdas that need them, because of the many permutations, which also change over time as our code evolves.

Is there a mechanism that (at build time) for each Lambda generates a jar without all the unused code (thus by pruning all the code that's not used by this Lambda)? Or is there another solution for this problem?

Upvotes: 0

Views: 95

Answers (1)

Jesse Barnum
Jesse Barnum

Reputation: 6816

My approach to this is usually to write fewer Lambda functions. Consider that each individual Lambda function has a cold-start delay, so that if function A is called, then a few seconds later B is called, then A is called repeatedly for the next 20 minutes, B will go "cold" and a call to it 20 minutes later will have a cold-start delay.

Combining both things into a single Lambda function that internally dispatches based on some parameter solves several problems:

  • Your concerns about code size bloat are solved, because there are fewer (maybe just 1) functions
  • As long as either A, B, or C are called on some regular basis, there will be no cold-start delay for any of the other functions.
  • The AWS Lambda console doesn't make it easy to manage large numbers of functions (e.g. there is no folder hierarchy or way of grouping related functions), so having fewer functions make it easier to get around the console.

Upvotes: 1

Related Questions