How does mysql connection pooling works with Node microservices? - mysql

I have two node microservices talking to one common mysql database. Both microservices have this below code to create a connection pool with a connectionlimit of 10 as follows:
// Initializing pool
var pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
port: '3306',
user: 'root',
password: 'root'
});
function addConnection(req, res) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
res.json({ "code": 500, "status": "Error" });
return;
}
connection.query("select * from user", function (err, rows) {
connection.release();
if (!err) {
res.json(rows);
}
});
connection.on('error', function (err) {
res.json({ "code": 500, "status": "Error" });
return;
});
});
}
For mysql database I have the max_connections set to 200(SHOW VARIABLES LIKE 'max_connections'; returns 200).
With the pool connectionLimit set to 10 for each of the microservice, in which cases or scenarios will the number of connections for any of the microservice will go above 10?
i.e. When and how the node services would be able to maintain more connections then expected?
If I have 3 instances running of same microservice then how does the pool connectionLimit works? What would be the limit of connections for each instance of microservice?
In one of the microservice say I have two apis which does database transactions and both connects to the database(getting connection) through two different functions having
same implementation of mysql.createPool({}) as above. What would happen if both apis are called concurrently and the number of requests made for each of them per second is 100 or more?
Will the number of connections made available be 10 or 20(since there are two mysql pools created with a connectionLimit of 10 each)?

Ideally it would not; but it can go above 10; if suppose some connections become stale i.e. they are closed from client end but are still open on Server end.
If you have multiple instances of same micro-service deployed in multiple VM or docker containers; they are like independent services.. and they have no connection among each other.. Hence, each of them will create its own 10 connection.
Firstly if u set connection pool limit as 10; that does NOT mean that during first moment 10 connections would be created.. While creating a pool; you also specify initial connection parameter suppose 5.. so, when service starts only 5 connections would be created.. and more created only when needed.. with UPPER Limit set as defined by parameter max_connections. Coming back to your question; well if you have NOT implemented synchronization etc. properly then yes it is possible that both pools will initialize their INITIAL_CONNECTIONS..

Related

How do we close the database `connection` in sequelize

How do we close the database connection in the below app.post. Do sequelize will automatically taken care of it ?
server.js
const sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, {
host: DB_HOST,
dialect: DB_DIALECT,
pool: DB_POOL,
port: DB_PORT
});
const Availability = availabilitySchema(sequelize, DataTypes);
app.post('/service/availability', async (req, res) => {
try {
const userEmail = req.query.email;
const dailyStatus = req.body.dailystatus;
var playerData = {email:userEmail, dailystatus: dailyStatus};
const playerDailyStatus = await Availability.create(playerData);
res.status(200).json({ success: true });
} catch (e) {
res.status(500).json({ message: e.message });
}
});
As i understand it (and I only started looking at sequelize yesterday - comments if I'm wrong, please) Sequelize pools its connections, so there isn't really anything for you to close; it opens and closes connections as necessary much like any other ORM, and mostly those connections are open and live in a pool, are leased from the pool and do some work, then are returned to the pool. You can configure the pool options (looks like you already have) if you want to limit the number of concurrently open connections to your DB but if you're looking in your DB manager and seeing "omg, my sequelize appp has 5 open connections.. now it has 10.. now 15!" that's just how it is; it opens as many connections as necessary (up to the max) to service the workload and leaves them open because it's a huge waste of time to actually open (TCP connect) and close them constantly (TCP disconnect).
When using an ORM you don't micromanage the connections, you just carry out queries using the modeled objects and let the ORM deal with the low level stuff (opening and closing a connection is a level below crafting the SQL to run, and you hand that off to the ORM too). Even in something you've been used to elsewhere, like C# new SqlConnection("connstr").Open() might not actually be opening a TCP cnnection to the DB and closing it; it's probably just leasing and returning to a pool and the underlying framework manages the actual TCP connections and their state

Too many Connections on Node-MySQL

I get Error Too many connections when there to much items in a loop with INSERT IGNORE INTO.
function insertCases(cases) {
for(var i in cases) {
var thequery = 'INSERT IGNORE INTO `cases` SET keysused='+cases.keysused+'
pool.query(thequery, function(ee, rr) {
if(ee) {
logger.info(ee);
throw ee;
}
});
}
}
When there are now 100+ cases so 100 times INSERT IGNORE INTO than I get too many connections. I don't know how much exactly crash it but with 100 it's working.
What I read is, that query runs the query and also closes the connection after done, so I read, I don't need to close it after than.
If I run 100, waiting short time and run 100 again and so on, it don't get Too many connections error.
It's only when there runs so much time at once.
That's my DB settings
var db_config = {
connectionLimit : 5000,
host: 'localhost',
user: 'userexample',
password: '*******',
database: 'example.com'
};
and that's the function that createPool.
function database_connection() {
pool = mysql.createPool(db_config);
pool.getConnection(function(err, connection) {
if(err) {
logger.error('[ERROR] Connecting to database "' + err.toString() + '"');
setTimeout(function() { database_connection(); }, 2500);
}
else
{
pool.query('SET NAMES utf8');
pool.query('SET CHARACTER SET utf8');
logger.trace('[INFO] Connected to database and set utf8!');
}
});
}
All queries on the node are simply run with pool.query
The database_connection() is called on start of the node
You've set connectionLimit to five thousand! That means the node-mysql subsystem will keep trying to handle multiple query requests by adding new connections until it has five thousand. Your MySQL server has a connection limit of 100, it seems, so your nodejs app blows out when that limit is reached.
Set connectionLimit: 10,
Then you'll use ten pool connections, and when they're all in use your pool.query invocations will wait until one becomes available.
Why not set the limit to 100? Two reasons:
You want to leave some MySQL connections for other client software.
If you hammer the database with many similar queries (in your case INSERT queries) in parallel, it will spend time avoiding contention. With fewer connections in parallel, each query will finish much faster.

chose connection pool based on parameter node mysql restful

We are trying to create backend - RESTFUL api based on mysql DB - in express Nodejs. My boss (self acclaimed mysql guru) insist that we should use more connection pools than 1 - based on the different roles that users are grouped in.
So I need to define/create different connection pools in file B.js - > and make them as global variables so that I could access them later.
In file A.js I have a this route - in which looged in users will be able to call stored procedures with arguments. However, I would like to be able to define from which connection pool the connection will be called - in route itself (based on the session (req.user.role) variable).
So that:
pool1.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query(query1, val, function (err, rows, fields) {
connection.release();
if(!err) {
var results = JSON.stringify(rows[0]);
console.log(results);
console.log(typeof(results));
console.log(rows[0][0]);
console.log(typeof(rows[0]));
res.send(JSON.stringify(results));
}
});
connection.on('error', function(err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
});
};
refers to pool1, but in case with other user -> pool1 should connect to other pool - defined in other files.
I hope I am clear with my issue.
You don't need to use global variables, you can export an object that holds each pool:
// B.js
module.exports = {
regular : mysql.createPool({ ... }),
admin : mysql.createPool({ ... }),
};
// A.js
const pools = require('./B');
...
let pool = pools[req.user.role];
if (! pool) {
throw Error('there is no pool for user role ' + req.user.role);
}
pool.getConnection(...);
So this declares two pools, one for "regular" users and one for "admin" users. It uses the value of req.user.role (which is assumed to contain one of two values: "regular" or "admin", but that's just for the purpose of this example) to pick the pool that should be used.
I'm not sure what the upside is of having more than one pool, unless they connect to two different databases or use different database credentials.
I don't know why you're doing this or your boss want to do this, more connection pools won't make the application more efficient, it just confuse people. Since the MySQL server has its limit of clients. And by the way, if you want to know a user's role, you have to connect the database and fetch the user data in the first place. Why don't you just use the same connection to do other things and that will be fine.
We have more than one UI developer, each develops one role so we don't want that all UI developers can see all store procedures... (That boss)

When to initialize mysql connections in node

I'm trying to figure out what the best time to actually initialize connections for mysql in node is.
Am I supposed to create a pool of connections and then set them to some global so that all my models have access to the pool? Or am I supposed to initialize connections whenever I'm doing queries?(Seems bad).
I'm sure there's some "proper" way to do it, but I'm not really certain what the best way is.
If you are going to pool connections, then don't initialize connections right when they're needed. When not using a pool, you can just store connection information when your application is starting up, and use it when you need it:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret'
});
Then for single use cases:
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
// we are done with the connection
connection.end();
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
If you're pooling, you should just create a connection pool when your application is starting and fetch connections when you need them. You should not make more than one pool.
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'example.org',
user: 'bob',
password: 'secret'
});
Then when you need a connection, you'd do something like this:
pool.getConnection(function(err, connection) {
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// we are done using the connection, return it to the pool
connection.release();
// the connection is in the pool, don't use it here
});
});
After more research, think I've figured out the right way.
1) Create a connection pool on app start
2) Include that file in your models.
3) Get a connection from the pool.
In the interest of keeping your code cleaner, I think you can also just invoke the pool object directly, according to the manual at https://github.com/felixge/node-mysql. This should abstract the logic for getting and releasing connections from the pool.
EG:
var result = yield pool.query("SELECT * FROM users");
(I'm using co-mysql with support for generators, but syntactically it should be the same w/out the callbacks)

Socket.io & Mysql: how many connections?

In an app with socket.io and node-mysql module, what's the best way (most optimized and well designed) to use mysql connections when an event is triggered?
create one connection and pass it to the callback
create a connection every time the callback is called
Let's write some code to better explain
Case 1
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
connection.connect(function cb3(){
connection.query();
});
});
});
Case 2
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function cb3(){
connection.query();
});
});
});
My server listen for several socket events and I'm experiencing a lot of timeout errors! I think it could be related to the use of the connections.
Any suggestions?
I think the best would be to have a connection opened all the time and run just query inside socket.io event. Like this:
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function cb3(){
io.sockets.on('connection', function cb1(){
socket.on('event', function cb2(){
connection.query();
});
});
});
I would look at connection pooling, which is implemented by node-mysql. This has the advantage of being able to use multiple connections to your database, while keeping the total number of connections limited to prevent flooding the database server.
Another possibility could be node-mysql-queues, which can be used to prevent possible issues with multiple queries run through a single connection.