0

Trigger AWS Lambda Asynchronously from API Gateway

AWS API Gateway

AWS Lambda & API Gateway are the perfect partners when it comes to serverless architecture.

The default invocation type of AWS Lambda from API Gateway is synchronous. That means the lambda keeps the connection open until the function returns a response or times out. And that is usually required by most of the REST APIs. The API returns a response along with optional data as soon as the request processing is complete.

But what if the API is doing batch operations for a longer than usual time or is spawning a process? The lambda will time out with an error in response. Now to deal with this, we need to invoke the aws lambda function asynchronously.

There are two ways to invoke AWS Lambda asynchronously:

1. Via Another Lambda Function

In this solution, there will be a helper lambda function between API Gateway and your main Lambda function. Its job will only be to invoke the main lambda function in async mode and return the response.

The helper lambda uses boto3 API to launch the main lambda. You can set the Invocation Type to Event to launch it asynchronously. I have added the helper lambda below:

def lambda_handler(event, context):
    try:
        boto3.client('lambda').invoke(
            FunctionName='main-lambda',
            InvocationType='Event',
            Payload=json.dumps(event)
        )
    except Exception as e:
        return {
        "isBase64Encoded": False,
        "statusCode": 400,
        "headers": {},
        "body": json.dumps({'error': str(e)})
        }

    response = {
        "isBase64Encoded": False,
        "statusCode": 200,
        "headers": {},
        "body": ""
    }
    return response

2. Via API Gateway

Go to API Gateway, select your deployed gateway and then go to your Lambda function.

Deselect the following option if selected.

AWS Lambda

Now scroll down and go to HTTP Headers section and add the following header:

Name: X-Amz-Invocation-Type

Mapped from: ‘Event’

Note, mapped from value is with quotes.

AWS LAmbda

Now the request coming to this lambda will invoke this Lambda asynchronously.

Also Read: AWS Lambda To Launch AWS EMR Cluster

Abhishek Balani

A full stack developer, sometimes designer, passionate coder, tireless knowledge seeker, curious learner. I have a strong passion for new technologies, very autodidact and love to build new things from the ground up. Having 5+ years of dynamic experience accumulated from working in early stage startups to mid-sized organizations in Agile environment. Skilled in Python and related frameworks, React.js, Databases, Hadoop, Elastic Search and various AWS Services like Boto3, API Gateway, Lamda, EC2, EMR, CloudWatch.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.