A developer is writing an AWS Lambda function that retrieves database configurations from an external database on every invocation. The database queries are slow, causing high latency and occasionally leading to function timeouts. Which approach should the developer use to optimize the function's performance by caching the configurations across invocations?
- Initialize the database connection and retrieve the configurations outside the Lambda handler function, storing them in global or static variables to reuse them across subsequent warm start invocations.Answer
- BDeclare the database connection and configuration variables inside the Lambda handler function, and increase the Lambda function timeout to 15 minutes to allow enough time for queries.
- CStore the database configurations in AWS Systems Manager Parameter Store, and configure Parameter Store to automatically rotate the database credentials every 30 days.
- DStore the configurations in an Amazon SQS queue, and set the queue's visibility timeout to be shorter than the Lambda function's timeout so that the configuration message is immediately recycled.
Answer
Initialize the database connection and retrieve the configurations outside the Lambda handler function, storing them in global or static variables to reuse them across subsequent warm start invocations.
Declaring database connections and configuration variables in the global scope (outside the Lambda handler function) utilizes execution context reuse. During warm starts, Lambda reuses the existing container environment, allowing the application to bypass redundant initialization and query overhead by reading from the globally persisted variables.
Step-by-Step Solution
Key Concept
AWS Lambda Execution Context Reuse