Question

Difficulty: MediumServerless Development with AWS Lambda

A developer is implementing an AWS Lambda function in Node.js to process events. The developer wants to log the count of processed items for each individual invocation. The function code is structured as follows:

javascript
let totalItems = 0;

exports.handler = async (event) => {
totalItems += event.items.length;
console.log(`Processed ${totalItems} items.`);
return { statusCode: 200 };
};

During testing, the developer observes that when the function is invoked repeatedly in short succession, the logged count accumulates across requests rather than reflecting only the items processed in the current invocation.

Which of the following modifications should the developer make to ensure the function correctly logs only the items processed in the current invocation?

  1. A
    Configure the Lambda function's reserved concurrency to 1 to force the execution context to tear down and recreate after each invocation.
  2. Declare the totalItems variable inside the handler function so that it is re-initialized on each invocation.Answer
  3. C
    Associate the Lambda function with a private VPC subnet without a NAT Gateway to prevent execution contexts from sharing global variables.
  4. D
    Increase the visibility timeout of the trigger Amazon SQS queue to exceed the function execution time, forcing the Lambda service to clear the execution context.

Answer

Declare the totalItems variable inside the handler function so that it is re-initialized on each invocation.
Declaring the variable inside the handler function ensures that its scope is limited to a single invocation. AWS Lambda reuses execution contexts to optimize performance on subsequent requests. Variables declared outside the handler (globally) persist across warm start invocations, leading to state leakage and cumulative counts, whereas local variables inside the handler are re-initialized on every execution.

Step-by-Step Solution

1
Analyze the variable scope and lifecycle of variables declared outside the handler function in AWS Lambda.
Identify that variables declared outside the handler (globally) are preserved in memory across subsequent execution context reuse (warm starts).
AWS Lambda reuses the container/execution context to minimize cold start latency, which keeps global state alive.
2
Determine the correct place to declare variables that must be isolated and reset per execution.
Move the variable declaration inside the handler block.
Local variable declarations inside the handler function run on every invocation, ensuring they start at 0 each time.

Key Concept

AWS Lambda Execution Context Reuse and Variable Scoping
Estimated Time:1m 30s
Rate this question