Question

Difficulty: MediumServerless Development with AWS Lambda

A developer has implemented an AWS Lambda function in Node.js that processes orders and sends a response back to Amazon API Gateway. Inside the handler, the function sends tracking metrics to a third-party analytics API by initiating an asynchronous HTTP request without using an 'await' statement (a background promise). However, the developer notices that the Lambda function continues running and eventually times out, even though the main order processing logic completes and the callback is invoked. Which configuration change should the developer make to ensure the function returns the response immediately without waiting for the background tracking metrics request to complete?

  1. Set the callbackWaitsForEmptyEventLoop property of the context object to false in the Lambda handler.Answer
  2. B
    Increase the Lambda function's timeout configuration to allow enough time for the background metrics API call to complete before returning the response.
  3. C
    Change the API Gateway integration type to Lambda custom integration and configure an integration response mapping template to return the response early.
  4. D
    Deploy the Lambda function inside a private VPC subnet with a NAT Gateway to optimize outbound network traffic to the third-party API.

Answer

Set the callbackWaitsForEmptyEventLoop property of the context object to false in the Lambda handler.
The correct answer is to set the callbackWaitsForEmptyEventLoop property of the context object to false. By default, the Lambda runtime for Node.js will not return the response until the Node.js event loop is completely empty. If an asynchronous background operation (such as a metrics API call without an await statement) is still pending when the handler finishes its main execution, Lambda will wait for that operation to complete or for the function to time out. Setting callbackWaitsForEmptyEventLoop to false overrides this behavior and returns the response immediately to the caller, while allowing background tasks to be frozen until the next invocation.

Step-by-Step Solution

1
Identify the cause of the Lambda function's prolonged execution.
The un-awaited asynchronous tracking metrics call creates a pending event/promise in the Node.js event loop.
By default, AWS Lambda waits for the Node.js event loop to be completely empty before freezing the execution environment and returning the response.
2
Modify the execution context behavior.
Assign context.callbackWaitsForEmptyEventLoop = false; inside the handler.
This configuration overrides the default behavior, instructing the runtime to immediately send the response back to API Gateway once the callback is called or the main handler promise resolves.

Key Concept

AWS Lambda Node.js event loop execution behavior
Rate this question