8

I have a lambda function which return base64 string, when I invoke lambda from code it works, but when I call lambda behind ALB and base64 string is large size, ALB gives me error 502 Bad Gateway. Note:for small size string ALB also works.

// Lambda function handler

'use strict';


module.exports.handler = async (event, context) => {
  // ALB expects following response format
  // see: https://docs.aws.amazon.com/lambda/latest/dg/services-alb.html
  const response = {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
    },
    isBase64Encoded: true,
    statusCode: 200,
    statusDescription: '200 OK',
  };
// ALB gives error 502 when buffer size is large
  const answer = 'This is my audio buffer'.toString('base64');
  response.body = answer
  return response;
  };
Dharam
  • 469
  • 2
  • 9
  • 23

3 Answers3

9

Check that you are not exceeding the limits. As per the AWS docs, when using Lambda as an ALB target the maximum response size is 1MB; if the response is more than 1MB you will get an error.

You can see this link for more information on using Lambda as a target for your ALB: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html

hephalump
  • 5,860
  • 1
  • 22
  • 23
1

This could be due to couple of reasons as mentioned in the AWS ALB docs -

  • response body exceeds 1 MB
  • Lambda function that did not respond before its configured timeout was reached

There is nothing much that can be done if the payload size limit is reached. 1 MB is the limit if lambda is configured as a target for ALB.

If the reason is due to lambda timeout, then this can be extended in the lambda configuration. The default is 3 seconds and it can be extended upto 15 minutes. There is nothing much one can do if the 15 minutes limit is reached. docs

Nithin Kumar Biliya
  • 2,763
  • 3
  • 34
  • 54
  • 1
    Any idea when it's none of these things? I can see that my lambda runs successfully, but I always get a 502 Bad Gateway response? – user1751825 Feb 14 '21 at 22:11
  • @user1751825 Did you find out why this might have happened? Facing the same problem. – rsp Oct 13 '21 at 10:01
  • 1
    @bob Yes I fixed my issue by adding a 3rd "callback" param to the exports.handler, then instead of just returning response object, I do callback(null, response); – user1751825 Oct 13 '21 at 10:45
  • @bob I've added an answer which might help. – user1751825 Oct 13 '21 at 10:51
1

Just in case it's helpful to someone. I was able to resolve a similar issue by changing the code to be like this...

// Lambda function handler

'use strict';

//note the 3rd 'callback' parameter
module.exports.handler = (event, context, callback) => {

  // Construct the response object like normal

  callback(null, response);
};
user1751825
  • 4,029
  • 1
  • 28
  • 58