Optimizing function initialization

Each time a new Lambda execution environment is created (in other words, at each cold start), the function’s static initialization code is run. This is part of what is known as the “init” phase in the execution environment’s lifecycle, as shown in Figure 6-7. The init phase is run once per environment on start-up and is not run again if an invocation uses a warm execution environment.

Figure 6-7. Lambda execution environment lifecycle (source: adapted from an image on the Amazon Lamba Execution Environment web page)

You can think of the init phase as running the code outside of your handler and the invoke phase as running the code inside your handler:

// init phase

import { DynamoDBClient } from “@aws-sdk/client-dynamodb”;

const dynamoDBClient = new DynamoDBClient();

export const handler = async () => {

  • invoke phase

};

You should keep the init code of your functions to an absolute minimum to optimize cold start times as far as possible. That said, there are tasks that are more efficient to perform during the init phase than the invoke phase. Typically these are tasks that produce objects that can be reused over multiple function invocations in the same execution environment. This could include importing dependencies, opening database connections, initializing AWS clients, or instrumenting AWS SDK calls for X-Ray tracing, for example.

Optimizing compute performance

The compute performance of your functions can be optimized by making use of the AWS Graviton2 processor. Functions that use the Graviton2 processor will typically perform better and cost less. They will also consume up to 60% less energy compared to the alternative x86-based processors. For more on sustainability, see Chapter 10.

Leave a Reply

Your email address will not be published. Required fields are marked *