Comparing the effect of global scope - AWS Lambda

Comparing the effect of global scope

In this example, the Lambda function looks up a customer ID from a database to process a payment. There are several issues:

perf optimize figure 11
  1. Private data that is only used per invocation should be defined within the handler. Global variables retain their value between invocations in the same execution environment.

  2. Libraries should be defined in the initialization code outside of the handler, so they are loaded once when the execution environment is created. This implementation causes the library to be loaded on every invocation, slowing performance.

  3. The connection logic should also be managed in the initialization handler, and any connection strings containing secrets should not be stored in plaintext.

  4. This type of logic can lead to unintended effects. If the existingCustomer function returns false, the customerId retains the value from the last invocation of the function. As a result, the wrong customer is charged.

The next example uses scoping correctly to resolve these issues:

perf optimize figure 12
  1. Libraries are defined in the initialization section and are loaded once per execution environment. The instance variable is lazily loaded.

  2. The customerId is defined in the handler so the variable is erased when the function exits with no risk of data leakage between functions.

  3. The dbInstance connection is made only on the first invocation, using lazy loading.

  4. The customerId value equals null if the existingCustomer function returns false.