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.