A developer is writing an AWS Lambda function that retrieves data from an Amazon RDS database. To optimize the function's performance and minimize connection overhead, the developer wants to reuse the database connection across multiple function invocations. How should the developer structure the function code to achieve this?
- ACreate and close the database connection inside the Lambda handler function on every invocation.
- BInitialize the database connection inside the handler function using hardcoded access credentials.
- Initialize the database connection client outside of the Lambda handler function.Answer
- DReturn the database connection object in the response payload formatted for an API Gateway proxy integration.
Answer
Initialize the database connection client outside of the Lambda handler function.
Initializing the database connection client outside of the Lambda handler function allows the connection to be kept alive in the execution context's memory. When subsequent invocations occur (warm starts), Lambda reuses the existing container and execution context, making the existing database connection immediately available and avoiding connection overhead.
Step-by-Step Solution
Key Concept
AWS Lambda Execution Context Reuse
Estimated Time:45s