Closing mongoose connection and multiple connections showing up - node.js

I'm using mongoose to maintain a connection with the database for my node.js app.
What I am doing is essentially open a connection the the database when the app starts and close the connection when it terminates. It's working fine and I have absolutely no issues querying and manipulating data, so no issues there.
I have a fair idea about how it works and how connections are pooled. However, I noticed that when the app is running, I randomly get an extra connection to my database - Multiple connections to DB
I'm using nodemon to track any file changes in my project but since the app closes every time nodemon cause it to restart, the connection should be destroyed because the app is closing, right?
Is it advised to close connections anywhere while the app is up and running and open it again as and when required? I haven't done that anywhere because from what I've read, it takes more time to open and close connections for every query. Could this be because I'm not disconnecting anywhere except for when the app closes?

Related

First connection to Mongo Atlas takes a long time

I'm using Mongo Atlas with Prisma. Whenever I launch my project, it takes about 3 minutes for database to connect, and in this period of time, I can't see anything in Mongo Atlas' connection tab. I've tried Prisma's logger, no error prints at all. Interestingly, it connects but it just takes time.
It eventually connects, but this issue with connection time makes using hot reload quite hard. I've tried allowing incoming Node apps in Advanced Firewall Settings, and my firewall is disabled. Actually I couldn't find a lot of people experiencing this, so I couldn't try much to be honest. And to note, when somebody else tries to launch exact same code, their database starts working instantly.

I am getting connection reset error when trying execute two queries at the same time in arangodb?

I am using arangojs v6.14.1 and arangodb version 3.6.4.. I also have the nodejs express app which is intended to serve client requests.
I am experiencing an issue while executing concurrent requests. The database connection hangup when I concurrently process client requests:
What the app will do when it receives a request?
Open a database connection -
db = new Database(dbConfig.url);
db.useDatabase(dbConfig.name);
db.useBasicAuth(dbConfig.username, dbConfig.password);
There are multiple middleware functions that need to access to perform various functions and accessibility checks. And for each middleware I tried to
open a new database connection ->
perform the action ->
close the connection ->
return the result to next middleware.
This works fine with single request at a time. But if I tried to call two APIs at same time, I am getting CONNECTIONRESET error. And also throwing socket hangup error.
I tried to commend out the close connection method and it started working fine for a while. But when I increased the number of connections, it again showing the same error as "CONNECTIONRESET".
I have searched the documentation of arangojs regarding the connection manipulation. But I haven't found any information regarding the same.
Any help would be deeply appreciated.
This might be too late for you, but I had a similar issue. After talking with ArangoDB support, it turned out to be an issue with sockets.
Looking at the output from netstat -aplnt I was seeing a lot of CLOSE_WAIT and TIME_WAIT messages, indicating that there were A LOT of connections that were not being closed properly.
The solution was to enable persistent connections (see arangojs config for keep-alive and maxSockets) and then re-using a single connection whenever possible. This was more than just a settings change, requiring some code modifications as well.

Should I close my mongoose node.js connection after saving into database?

I have the following code in my app.js which runs on server start (npm start)
mongo.mongoConnect('connection_string', 'users').then((x) => {
console.log('Database connection successful');
app.listen(5000, () => console.log('Server started on port 5000'));
})
.catch(err => {
console.error(err.stack);
process.exit(1);
});
process.on('SIGINT', mongo.mongoDisconnect).on('SIGTERM', mongo.mongoDisconnect);
As you can see I open up SIGINT and SIGTERM for closing my connections upon process.exit
I've been reading a lot about how to deal with database connections in mongo and know that I should just invoke it once and have it across my application.
Does that mean that even after save() method when saving data to mongo followed by POST request, I should not be closing my connection? If I close it, how am I going to invoke it again since the connections happens on app start?
I'm asking it since in PHP I had the practice to always open and close my connection after querying MySql database.
Likewise, does it mean that the connection will close only on server shutdown in other words it will always be present since I do not want to shut down my node.js backend instance?
It is formally correct to open a connection, run a query, and then close the connection, but it is not a good practice, because opening a connection is an "expensive" operation and connections can be reused, which is much more efficient. The main restriction on an open connection is that it can only be used by 1 thread at a time. (More accurately, once a request is sent on a connection, no other requests can be sent on that connection until the response to that request is received.)
If your application is short lived or inherently single threaded, as may be the case when running as a "serverless" function, it may be acceptable to open and close a connection on each request.
While in theory it might be acceptable to open a single connection at the start of the program, keep a global reference to that connection, and reuse it, in practice there are common ways in which a connection becomes unusable that you would have to account for, and handling all the possibilities requires complex code. It gets even more complicated when, as is possible with MongoDB replica sets, you are actually connecting to more than one server and want to retry a command on a second server if the first one fails to respond.
That is why the standard and "best" practice is to use a "connection pool" to manage your database connections. A pool opens a set of network connections to the database, verifies and maintains their health, and dynamically assigns virtual database connections to actual network connections as needed. The pool is implemented in a library that will have received a lot of real world testing and is extremely likely to be better than anything you would write yourself. Connection pools have configuration options that would let you set any behavior you want, including opening a new connection for each request and closing it when done, but offer a wide range of performance enhancing capabilities, such a reusing connections and avoiding the overhead of creating them for each request.
This is why for MongoDB, the standard Node.js client already implements a connection pool. I do not know what mongo.mongoConnect in your code refers to; you said in the title that you are using mongoose but it uses connect, not mongoConnect to connect to the database. In general you should either be using the standard client or a JavaScript ORM library like mongoose. Either of them will take care of the connection management issues for you.
Refer to the documentation for the client/library you use for exactly the right way to use it. In general, you would initialize some kind of client object and store it globally before entering your main application handler. Then you would use this object to handle your database operations, and the object will transparently manage the underlying connections via the pool implementation. In this kind of setup, you would only close the connection when exiting the program, and usually the library takes care of that for you automatically, so you really never need to close the connection.
Thus, when using a MongoDB connection pool in NodeJS, you write your program basically the same way you would as if you just opened a connection at startup and then kept reusing it. The libraries take care of isolating you from all the problems that can arise from actually doing this. You do not need to, and in fact should not, close the connection after a database operation when using standard MongoDB NodeJS libraries.
Note that other connection pool implementations exist that do require you to close the connection. What you do with those pools is reserve (or "check out" or "open") a connection, use it, perhaps for multiple operations, and the release (or "check in" or "close") the connection when you are done. This is probably what you were doing in PHP. It is important to read and follow the documentation for the connection pool library you are using to make sure you are using it correctly.
This may not be the exact answer you are looking for, but it is not a good idea to open a new connection for every request and then close it. It is an overhead because it takes some time (even in milliseconds) to create a new connection.
Instead, you should create a pool of connections and use it in your app.
It's a good idea to close your mongo connection when your process dies or is stopped, but you should not need to close your mongoose connection after every successful query.
If you are instantiating a new mongo connection before each query you shouldn't need to be doing that either. You should just need to do that once when booting up your server.
you have two approaches
1) reopen a connection on every call using middle wares
2) you have to save your's query in node sometime later on execute all it onces

Recycle Ably realtime connections

I kinda came across a strange problem.
In our application (based on React-native) we hosted 70 concurrent clients but the peak in the monitoring page showed 380 connections.
I assume maybe clients exit and come back or reload the app somehow so Ably connections regenerates again and therefore the peak increases.
Now the question: is there any way to force Ably disconnect all unused connections so the peak decreases? (Maybe from back-end)
Thanks.
By default, the connection will stay active until closed explicitly (using connection.close()), or two minutes after the connection is disconnected unexpectedly to allow for connection state recovery.
Recent versions of ably-js in a browser environment automatically close the connection on page reload (that is, the closeOnUnload client option defaults to true) -- this is just a connection.close() added to a beforeunload handler. The trouble is that isn't going to do anything in a React Native environment, which doesn't use that event.
So you probably just need to actively manage your Ably connection using React Native app lifecycle events. If you don't want it to stay active when the app is backgroundend, then in the handler for the app being in the background (per the React Native AppState event), close the Ably connection. Then re-open it (call connect()) when the app is active again.
For other possible reasons your peak connection count may be higher than expected, see Why are my peak connection counts higher than expected? and How does Ably count peak connections?.

Does Mongodb automatically disconnect when the Node server closes

I just started using MongoDB. One of my confusions is, I hear it is good to have your MongoDB connection open on initiation and re-use that connection throughout your application.
However, should I ever explicitly close the MongoDB connection eventually? Or does MongoDB implicitly close the connection when the Node server goes down?
unless explicitly closed, the connection will be kept open in the event loop until the process terminates. So if you intend your app to maintain an open connection to mongodb throughout its life cycle, then there is no need to explicitly close it. It will happen automatically when the process is terminated.
now if you're writing a command script, then you should close the connection explicitly otherwise the open socket will keep your process from terminating.

Resources