Soru

Zorluk: KolayServerless Development with AWS Lambda

A developer is writing an AWS Lambda function that retrieves data from a database. To optimize performance and reduce latency, the developer wants to reuse the database connection client across multiple function executions. In which part of the code should the database connection client be initialized to achieve this goal?

  1. Outside the main handler function in the global initialization codeCevap
  2. B
    Inside the main handler function so that it is re-initialized on every invocation
  3. C
    Inside the handler function by hardcoding the database access credentials directly in the SDK client setup
  4. D
    In a private VPC subnet without a NAT Gateway to ensure secure caching of the connection pool

Cevap

The database connection client should be initialized outside the main handler function in the global initialization code.
Initializing the database connection client outside the main handler function in the global initialization code executes the initialization once during the initialization (INIT) phase. Warm invocations reuse the same execution environment, which caches the client and reduces connection latency and resource load.

Adım Adım Çözüm

1
Analyze the AWS Lambda execution environment lifecycle.
The execution environment goes through an initialization phase (INIT phase) that runs global code, followed by the invocation phase (INVOKE phase) that runs the handler code.
Understanding the lifecycle allows a developer to identify where static configurations should reside for caching.
2
Determine the resource initialization scope.
Declaring the database connection client in the global scope (outside the handler) executes it during the INIT phase once, and subsequent warm invocations within the same execution context reuse this initialized client.
Declaring resources inside the handler forces initialization on every invocation, causing unnecessary overhead and database connection exhaustion.

Anahtar Kavram

Execution Context Reuse in AWS Lambda
Tahmini Süre:45s
Bu soruyu puanla