1

I have added a lambda function to my api gateway. It is a get request and it returns an array of data. I am using mongodb for my database

Domain: domain.com/api/list/

Sometime if I request the domain without a slash it works fine, sometimes it does not work and returns 502. If I request it in the normal browser it returns 502 but if i request the same url in the tor browser then it always works fine.

I suspect it might be something related to caching but why would caching result in 502?

module.exports.getAll = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  await database.connect();
  const x = await model.find({});

  callback(null, {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(x)
  })
};

I have set caching for this api gateway to 0 on cloudfront. I have increased the timeout to 10 seconds but cloudwatch says Task timed out after 6.01 seconds

x-amzn-errortype: InternalServerErrorException

x-amzn-requestid: 578f0c43-9798-4949-813c-52259d57375b

x-cache: Error from cloudfront

I have also made a npm package which contains my mongodb schemas and creates the connection to the mongoclient. Something I realised from looking at the cloudwatch is that I get the errors sometimes when 'using existing database connection' is printed out.

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = ``

let isConnected;
module.exports = connectToDatabase = () => {
  if (isConnected) {
    console.log('=> using existing database connection');
    return Promise.resolve();
  }
  console.log('=> using new database connection');
  return mongoose.connect(url).then(db => {
    isConnected = db.connections[0].readyState;
  });
};

I got the connectToDatabase code from here

Siyavash
  • 970
  • 9
  • 23
  • 1
    *"I have set caching for this api gateway to 0 on cloudfront."* Are you quite sure about that? In CloudFront, errors are cached with a timer called Error Caching Minimum TTL that defaults to 5 minutes. https://stackoverflow.com/a/35541525/1695906 – Michael - sqlbot Mar 29 '20 at 02:32
  • @Michael-sqlbot That makes total sense why the error would disappear when I request it from tor browser or when I add a slash to the endpoint. THANK YOU. So it is related to my db connection. I have updated the question, please have a look – Siyavash Mar 29 '20 at 02:38
  • Does this answer your question? [Frequent timeout with app using Serverless Framework (AWS Lambda/Gateway), Express, Mongoose/MongoDB Atlas](https://stackoverflow.com/questions/60588274/frequent-timeout-with-app-using-serverless-framework-aws-lambda-gateway-expre) – noetix Apr 03 '20 at 12:59
  • @noetix It does not solve and as you can see I do set the callbackwaits in my code. It only happens for one specific route in my api. – Siyavash Apr 05 '20 at 00:44

0 Answers0