Take advantage of the Lambda execution environment

Serverless Tip #13: Take advantage of the Lambda execution environment

Each Lambda execution environment goes through the following phases:

  • ๐ˆ๐ง๐ข๐ญ: Downloads code & layers โžœ Initializes extensions and runtime โžœ Runs function initialization code.
  • ๐ˆ๐ง๐ฏ๐จ๐ค๐ž: Invokes the function handler โžœ Wait until completion โžœ Prepares for future invocations.
  • ๐’๐ก๐ฎ๐ญ๐๐จ๐ฐ๐ง: No invocations for a while โžœ Shuts down and removes the environment.

In the init phase, the function initialization code is the code outside the handler. Each Lambda environment will only execute this code once. The init phase is also known as a โ€œcold start.โ€

Future invocations reuse the environment, avoiding the costly init phase. Such invocations are known as โ€œwarm starts.โ€

You can initialize reusable constructs outside your handler function. This way, you only pay the price once, and future invocations can reuse the constructs and enjoy shorter execution times.

Example constructs to reuse:

  • SDK Clients
  • Loggers
  • Database Connections

Sometimes, caching objects in the execution environment can have unintended side effects.

For example, if you add request-specific fields such as user IDs to a logger, they will stick around for future invocations. If you are caching request-specific context, reset the state at the start of each invocation.