I'm developing an express
-based application that makes some queries to different (different by user!) SQL Server 2008 and 2014 databases. It's different because each user belongs to a different company and each company has its own SQL Server. My app uses an own SQL Server to manage companies and their SQL Server connection string (my app has access to their database servers). I'm using the mssql
module.
I've not found a best practice regarding "should I use one SQL Server connection per user session or one connection for each user request".
Coming from a .NET world we had a rule: "one query/function - one connection".
First, the app has to query the own app database to get the SQL Server connection string for the database of the user's company. The user then can retrieve some data from their company's SQL Server (in my app) - like getAccounts()
. Each of these functions (each function - not each request in that function!) opens a new connection and closes it after query completion:
let connection = new mssql.Connection(conStr, (err) => {
request.query(queryString, (err, result) => {
if (err)
throw new Error('...');
resolve(result)
connection.close();
});
})
As far as I understand, it should make no (negative) difference if 100 users open and close connections per request (assuming just one request per user at the same time) or if 100 user have 100 opened connections (one per user) for the whole session. At first glance it seems that my approach is less resource hungry since connections are only opened when they are needed (i.e., a few seconds per request).
Am I missing something? What if 200 users access my app at the same time - will I get in trouble somehow?
Thanks in advance!
[EDIT]
As far as I understand,
let connection = new mssql.Connection(...)
will create a new connection pool which will open a new connection when I use something like
connection.connect()
and close all active connections with:
connection.close()
So I'm guessing that best practice in my scenario would be to create one connection pool (new mssql.Connection(..)
) per active user, save it in some kind of session store and then reuse it throughout the lifetime of the session.
Is this a good approach?
I just want to avoid one thing: a user gets an error because a connection can't be created.