Is it possible for Lambda to continue processing after returning a response like the status code is 202
then Lambda will have to call a request before ending the Lambda?
Regarding background processes or callbacks initiated before the function returns a response, from the Lambda docs:
Background processes or callbacks initiated by your Lambda function that did not complete when the function ended resume if AWS Lambda chooses to reuse the execution context. You should make sure any background processes or callbacks in your code are complete before the code exits.
When you write your Lambda function code, do not assume that AWS Lambda automatically reuses the execution context for subsequent function invocations. Other factors may dictate a need for AWS Lambda to create a new execution context, which can lead to unexpected results, such as database connection failures.
Additionally for Node.js Lambda functions using non-async handlers:
For non-async handlers, function execution continues until the event loop is empty or the function times out. The response isn't sent to the invoker until all event loop tasks are finished. If the function times out, an error is returned instead. You can configure the runtime to send the response immediately by setting
context.callbackWaitsForEmptyEventLoop
to false.
You can use two lambdas. The first lambda (lambda 1) will do an async invocation of the lambda that holds your code (lambda 2). Once you invoke it, you can cleanly exit "lambda 1" without waiting for "lambda 2" to return a response.
Using only AWS Lambda, it is not possible.
You may want to look into AWS Step Functions in order to solve your problem.
It can be done if you implement your own bootstrap
as part of a Custom Runtime. Unlike the provided AWS Lambda runtimes you may already be familiar with, a Custom Runtime controls its own event loop.
Here's the relevant excerpt from the Documentation:
Processing Tasks
[...]
Cleanup – Release unused resources, send data to other services, or perform additional tasks before getting the next event.
You can use Step Functions to achieve this. There are following approaches that can be used as per your requirements:
Trigger Step Function via API Gateway. API Gateway will instantly return the response and then Step Function will take over and trigger the Lambda function and it will ensure that Lambda executes till the end.
You can trigger Lambda 1 and Lambda 1 will trigger the Step Function, then Step Function will trigger the Lambda 2. I am assuming Lambda 2 will be used to heavy processing.
There are several ways to do that. This recent AWS blog page describes several options to achieve that goal.
© 2022 - 2025 — McMap. All rights reserved.