AWS Lambda to run in background even after sending response to API Gateway AWS Lambda to run in background even after sending response to API Gateway node.js node.js

AWS Lambda to run in background even after sending response to API Gateway


You can achieve this by using AWS Lambda Step functions, connected to API Gateway, having parallel execution of branches with two lambda functions, where one returns a response to API Gateway and other executes asynchronously.


Besides Step Functions, you could just invoke another Lambda function using the SDK built-in to the Lambda environment.

I'm no expert in express or NodeJS but I would also think there should be a way to send the HTTP response back and still continue code execution.


Can't find a link to the documentation of AWS, but normally it is not possible to continue processing after the Lambda function has returned the response. That's just not how the available runtimes (for the different programming languages) are constructed.

Next to invoking separate asynchronous processes (e.g., other Lambda function requests, or putting work on a queue) or using AWS Step functions as mentioned here, there's a third method that I know that works: supply a special custom runtime for the AWS Lambda functions that addresses this need.

Next to the standard runtimes, you can create and specify a custom runtime to be used for your AWS Lambda functions. In the standard runtimes, the response of your handler is being posted to the Lambda execution context, after which no activities are possible in your handler because the handler is being terminated (or at least: paused).

So, the trick to make additional processing possible after sending the response is to move the responsibility of posting the response to the Lambda operating content from the bootstrap script to the Lambda function handler itself... and continue to do your processing in your Lambda function handler after already having sent the response. Using your custom runtime, processing in the Lambda functions will then not be terminated after having sent the response, since it's not how your custom runtime is constructed.

It's not the architecturally-best solution, as it messes with the responsibilities between the Lambda operating context and your Lambda functions handlers... but it makes it possible to do processing in your Lambda function handlers after having sent the response.