0

I have following setup,

db.js

const mysql = require("mysql");
const config = require("../core/config/config.json");

const db = mysql.createPool({
    host: config.mysql.host,
    port: config.mysql.port,
    user: config.mysql.user,
    password: config.mysql.password
});

db.getConnection((err, connection) => {
    if (err) {
        console.error(err);
        return;
    }
    connection.ping();
    connection.release();
    console.log("Database connected !");
});


module.exports = db;

Then I have many query files as shown below,

query1.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

query2.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

query3.js

const mysql = require("../db");

mysql.query("select * from table", [param], (error, results) => {
            if (error) {
                return cb(error);
            }
            return cb(null, results);
});

and so on...

And I get

ER_CON_COUNT_ERROR: Too many connections error in node-mysql

When I deploy this code to AWS-lambda function. (Locally, it works fine).

What should I do it avoid above error with above setup ?

What am I doing wrong ?

micronyks
  • 54,797
  • 15
  • 112
  • 146
  • When do you encounter this error? I mean, immediately after the execution of the process or after a certain period? And is it part of a server? – Mostafa Fakhraei Jan 03 '23 at 16:35
  • After a certain period it happens but once it happens, it happens everytime. I have deployed my backend on aws-lamda function. Someone I want to close the connection after each query execution. – micronyks Jan 03 '23 at 16:37
  • Try to use connection directly (.createConnection) instead of using connection pool. Or only create connect(`db.getConnection` or `db.connect()`) in the lambda handler. – hoangdv Jan 04 '23 at 01:22
  • Did you release db connection after query ended? – Donggi Kim Jan 04 '23 at 13:42
  • Forget the older comment. I found that `pool.query()` do the releasing. How about MySQL server's `max_connections` setting? https://stackoverflow.com/questions/14331032/mysql-error-1040-too-many-connection – Donggi Kim Jan 04 '23 at 13:55
  • By the way, there's [RDS Proxy](https://aws.amazon.com/ko/blogs/compute/using-amazon-rds-proxy-with-aws-lambda/) for database connection pooling with Lambda – Donggi Kim Jan 04 '23 at 14:03

0 Answers0