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

Share:

administrator

I am a full stack software engineer and a blogger. Primarily, I work on Python, Java and React.js. I am an autodidact with a strong passion for new technologies. I love to build new things from the ground up. I have about 7 years of dynamic experience gained by working in early stage startups to mid-sized organizations in an Agile environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

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