Search code examples
amazon-web-servicesaws-lambdaserverlessaws-alb

Serve Binary responses via ALB and Lambda Integration


AWS just announced a new feature Invoking Lambda functions using Application Loadbalancers. This is great news as we don't have to configure all those mappings for API gateway just to get a simple response from my lambda function.

We have an image resizing service running on lambda via API gateway. I am wondering if we can replace API gateway with ALB. The way it works now we have to send a base64 encoded image to api gateway which in return converts it to a binary and send back to our clients.

If we were to replace API gateway with ALB how would we be serving images/binary responses what will be the needed changes we have to do to our existing infrastructure.


Solution

  • Receive Events From the Load Balancer is the Use Case:

    Now Application load balancer supports Lambda invocation for requests over both HTTP and HTTPS. If the content type is one of the following types, the load balancer sends the body to the Lambda function as is and sets isBase64Encoded to false: text/*, application/json, application/javascript, and application/xml. For all other types, the load balancer Base64 encodes the body and sets isBase64Encoded to true

    The following is an example event.

    {
        "requestContext": {
         "elb": {
         "targetGroupArn":
         "arn:awscn:elasticloadbalancing:region:123456789012:targetgroup/my-target- group/6d0ecf831eec9f09" // ALB reference
              }
              },
    "httpMethod": "GET",
    "path": "/",
    "queryStringParameters": {parameters},
    "headers": {
    "accept": "text/html,application/xhtml+xml",
    "accept-language": "en-US,en;q=0.8",
    "content-type": "text/plain",
    "cookie": "cookies",
    "host": "lambda-846800462-us-east-2.elb.amazonaws.com", //this is where Lambda CNAME is declared
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)",
    "x-amzn-trace-id": "Root=1-5bdb40ca-556d8b0c50dc66f0511bf520",
    "x-forwarded-for": "72.21.198.66",
    "x-forwarded-port": "443",
    "x-forwarded-proto": "https"
          },
    "isBase64Encoded": false,
    "body": "request_body"
     }
    

    following Official AWS Guide which will describe your use case