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](/images/lambda/latest/operatorguide/images/perf-optimize-figure-11.png)
-
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.
-
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.
-
The connection logic should also be managed in the initialization handler, and any connection strings containing secrets should not be stored in plaintext.
-
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](/images/lambda/latest/operatorguide/images/perf-optimize-figure-12.png)
-
Libraries are defined in the initialization section and are loaded once per execution environment. The instance variable is lazily loaded.
-
The customerId is defined in the handler so the variable is erased when the function exits with no risk of data leakage between functions.
-
The dbInstance connection is made only on the first invocation, using lazy loading.
-
The customerId value equals null if the existingCustomer function returns false.