简体   繁体   中英

Lambda Node.js Mysql RDS Timeout

My lambda function written in Node.js times out when connecting to RDS.

Weird thing is, this timeout happens only for the first request.

All subsequent requests work with the DB without the timeout.

Any idea why?

Just FYI not using any VPCs.

var mysql = require('mysql');

var pool = mysql.createPool({
  host     : 'ahost',
  user     : 'auser',
  password : 'apassword',
  database : 'adb',
  port : 3306
});


exports.handler = async (event, context) => {
    let request = JSON.parse(event.body);
    let question = request.question;
    let answered = question.answered;
    let sId = request.sid;
    let questionnaireId = request.questionnaireId;
    let hutk = request.hutk;
    let questionId = question.question.id;

    pool.getConnection((error, connection) => {
        if (error) throw error;
        let values = [];
        if(Array.isArray(answered)){
            let i = 0;
            while(i < answered.length){
                let td = [
                    questionnaireId,
                    sId,
                    questionId,
                    answered[i],
                    hutk
                ];
                values.push(td);
                i++;
            }
        } else {
            let td = [
                questionnaireId,
                sId,
                questionId,
                answered,
                hutk
            ];
            values.push(td);
        }

        let delsql = "DELETE FROM answers WHERE sId= ? AND `key` = ?";
        connection.query(delsql, [sId, questionId], function(err, result){
            if(err) throw err;
        });

        let sql = "INSERT INTO answers (qId, sId, `key`, value, hutk) VALUES ?";
        connection.query(sql, [values], function(err, result){
            if(err) throw err;
            console.log("Successfull Insert")
            connection.release();
        });

    });

    // TODO implement
    const response = {
        statusCode: 200,
        headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': true
                },
        body: JSON.stringify({message : 'success'}),
    };

    return response;
};

You might be running into and issue where you're releasing your pool connection while (or prior to) one of your two queries is being run.

You don't need to explicitly call getConnection once you've created the pool. More importantly if you have code where queries might execute in parallel (as you do here) you have to be very judicious in managing the connection and only releasing it once you're certain all the queries that will use it have completed.

Read more here: ( https://github.com/mysqljs/mysql#pooling-connections )

Consider trying the following:

var mysql = require('mysql');

var pool = mysql.createPool({
  host: 'ahost',
  user: 'auser',
  password: 'apassword',
  database: 'adb',
  port: 3306
});

pool.on('connection', function (connection) {
  console.log('Pool id %d connected', connection.threadId);
});

pool.on('enqueue', function () {
  console.log('Waiting for available connection slot');
});

exports.handler = async (event, context) => {
  let request = JSON.parse(event.body);
  let question = request.question;
  let answered = question.answered;
  let sId = request.sid;
  let questionnaireId = request.questionnaireId;
  let hutk = request.hutk;
  let questionId = question.question.id;

  let values = [];
  if (Array.isArray(answered)) {
    let i = 0;
    while (i < answered.length) {
      let td = [
        questionnaireId,
        sId,
        questionId,
        answered[i],
        hutk
      ];
      values.push(td);
      i++;
    }
  }
  else {
    let td = [
      questionnaireId,
      sId,
      questionId,
      answered,
      hutk
    ];
    values.push(td);
  }

  let delete_query = "DELETE FROM answers WHERE sId= ? AND `key` = ?";
  pool.query(delete_query, [sId, questionId], function(err, result) {
    if (err) throw err;
  });

  let insert_query = "INSERT INTO answers (qId, sId, `key`, value, hutk) VALUES ?";
  pool.query(insert_query, [values], function(err, result) {
    if (err) throw err;
    console.log("Successfull Insert")
  });

  // TODO implement
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true
    },
    body: JSON.stringify({
      message: 'success'
    }),
  };

  return response;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM