Optimizing Your Code - Serverless Architectures with AWS Lambda

Optimizing Your Code

Much of the performance of your Lambda function is dictated by what logic you need your Lambda function to execute and what its dependencies are. We won’t cover what all those optimizations could be, because they vary from application to application. But there are some general best practices to optimize your code for Lambda. These are related to taking advantage of container reuse (as describes in the previous overview) and minimizing the initial cost of a cold start.

Here are a few examples of how you can improve the performance of your function code when a warm container is invoked:

  • After initial execution, store and reference any externalized configuration or dependencies that your code retrieves locally.

  • Limit the reinitialization of variables/objects on every invocation (use global/static variables, singletons, etc.).

  • Keep alive and reuse connections (HTTP, database, etc.) that were established during a previous invocation.

Finally, you should do the following to limit the amount of time that a cold start takes for your Lambda function:

  1. Always use the default network environment unless connectivity to a resource within a VPC via private IP is required. This is because there are additional cold start scenarios related to the VPC configuration of a Lambda function (related to creating ENIs within your VPC).

  2. Choose an interpreted language over a compiled language.

  3. Trim your function code package to only its runtime necessities. This reduces the amount of time that it takes for your code package to be downloaded from Amazon S3 ahead of invocation.