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.