Soru

Zorluk: OrtaServerless Development with AWS Lambda

A developer is writing an AWS Lambda function in Node.js to calculate order discounts. The developer declares a helper array, `appliedDiscounts`, outside of the handler function to store the discount codes applied during execution. During testing, the developer notices that subsequent invocations of the function return incorrect discounts because they contain discount codes from previous invocations. Which of the following actions should the developer take to resolve this issue?

  1. A
    Configure Provisioned Concurrency on the Lambda function to guarantee that each invocation runs in a newly created execution environment.
  2. B
    Set the `context.callbackWaitsForEmptyEventLoop` property to `false` to force the recycling of the execution environment after each invocation.
  3. Move the initialization of the helper array inside the handler function.Cevap
  4. D
    Increase the visibility timeout of the incoming event source to automatically flush the global execution state between invocations.

Cevap

Move the initialization of the helper array inside the handler function.
Moving the initialization of the helper array inside the handler function ensures that the array is declared and reset to empty on every execution. Since AWS Lambda frequently reuses execution contexts to optimize performance, variables declared globally (outside the handler) persist across invocations. For mutable data structures like arrays, this persistence leads to state leakage and incorrect calculations on subsequent invocations.

Adım Adım Çözüm

1
Analyze the scope of the helper array variable.
The array is declared outside the handler function (globally).
Variables declared globally persist as long as the Lambda execution context is reused by subsequent invocations.
2
Identify the cause of incorrect discount calculations.
Subsequent executions append data to the same global array without resetting it.
Since the array is mutable and not cleared, state leaks from one execution to the next.
3
Determine the solution to reset the state for each request.
Move the array declaration and initialization inside the handler function.
Variables declared inside the handler are scoped to that specific execution and are fresh for every invocation.

Anahtar Kavram

AWS Lambda Execution Context Reuse and Variable Scoping
Tahmini Süre:1m 0s
Bu soruyu puanla