Saturday 15 April 2017

In a single threaded language like JavaScript, does it ever make sense to open and close database connection per transaction?

From a perspective of Node.js and server side scripting (web applications), does it ever make sense to open and close database connections per transaction?

Consider MongoDB and MySQL. If all web requests are going to transact with the database in some way, it seems most efficient to maintain a single persistent connection on server start and use it at the time of each request. The connection will close when the server is stopped.

This question is founded on a potentially fallible assumption that queries can be issued against a database cluster. That is to say... a single open connection from any web server in a load balanced farm would scale just fine as long as the database cluster can support the corresponding number of open connections.

As an example, I create database operations object on top of the database connection itself, I have designed a single connection for MongodB in the following manner:

Mongo.connect(MONGO_URL, function(err, db) {

  Mongo.ops = {};

  Mongo.ops.find = function(collection, json, callback) {
    db.collection(collection).find(json).toArray(function(err, docs) {
      if(callback) callback(err, docs);
    });
  };

  Mongo.ops.insert = function(collection, json, callback) {
    db.collection(collection).insert(json, function(err, result) {
      if(callback) callback(err, result);
    });
  };
});

In this example I avoid object modeling wiht Mongoose on purpose, taking advantage of the inherent flexibility of JSON in a NoSQL database. The same principle can be applied to the MySQL Node.js Driver to some extent.



via ThisClark

No comments:

Post a Comment