Warm tip: This article is reproduced from serverfault.com, please click

Not closing connection on MySql nodejs cause timeout lambda AWS

发布于 2020-11-29 23:34:04

I have a code on AWS lambda that makes querys to AWS RDS MySQL DB.

It runs this class each time a insert to DB is needed:

const mysql = require('mysql');
const config = require('../config.js');
const con = mysql.createConnection(config);

async function insert_score_db(user,message_id,date_created,sprint){
    //con.connect(function(err) {
      //if (err) throw err;
       console.log("Connected!");
        var sql = "INSERT INTO  user_records (user_name,message_id, date_created,sprint) VALUES ('"+user+"', "+ message_id + ", '"+date_created+"',"+ sprint+");";
        
        con.query(sql, function (err, result) {
        if (err) throw err;
          console.log(result);

      });
      //con.end();
      //con.destroy();
    //});
}

module.exports={
    insert_score_db
};

Im not using **con.connect(function(err){** because any query call established the connection implicitly, as the docs say.

I also commented **con.end()** because this function is being ran by a nested async loop and it cause the following enqueue Hanshake:

ERROR   Uncaught Exception  {"errorType":"Error","errorMessage":"Cannot enqueue Handshake after invoking quit.","code":"PROTOCOL_ENQUEUE_AFTER_QUIT","fatal":false,"stack":["Error: Cannot enqueue Handshake after invoking quit.","    at Protocol._validateEnqueue

I got rid of the **con.end()** and all the code runs correctly but the function ends with : Task timed out after 210.10 seconds. My guess is that DB connection never closes to lambda execution is unable to finish.

What might a potential solution for running DB querys with nested async loops?

Questioner
Christopher Martinez
Viewed
0
schtever 2020-11-30 10:49:13

Put the con.end() and con.destroy() inside the callback function for con.query().