magdan
magdan

Reputation: 11

Node.js MySQL connection not being released properly

I think my connections aren't being released properly. Sometimes I get an error stating that my pool has reached its limit. Also, sometimes accessing the db randomly takes 15+ seconds. Whenever I check how many connections are in use using pool._allConnections.length, it never returns anything above 60. Here is my code:

const mysql = require('mysql');
const config = require('./config.json');

const pool = mysql.createPool({
  connectionLimit : 999,
  host: config.host,
  user: config.user,
  password: config.password,
  database: config.database
});

const db = (() => {

  _query = (query, params, callback) => {
    pool.getConnection((err, connection) => {

      if (err) {
        callback(null, err);
      } else {
        connection.query(query, params, (err, rows) => {
          connection.release();
          if (!err) {
            callback(rows);
          } else {
            callback(null, err);
          }
        });
      }

    });
  };

  return {
    query: _query
  };
})();

module.exports = db;

Upvotes: 1

Views: 1746

Answers (1)

shivshankar
shivshankar

Reputation: 2135

i've faced same issue and https://github.com/mysqljs/mysql/issues/1518 help me. Notice line

Yeah, that was the issue. I was calling mysql.createPool on each query.

Actually you are importing db from query.js (let say your post code) to fire a query. every time you fire a query it create a new pool.to solve this issue you can put createPool code block to app.js and can share it global or can use in query.js via any other code style. Referring official doc https://github.com/mysqljs/mysql#pooling-connections find line

Since the pool.query method is a short-hand for the pool.getConnection -> connection.query -> connection.release() flow, calling pool.end() before all the queries added via pool.query have completed,

later i used this to stop headache of release connection

Upvotes: 1

Related Questions