How detect MongoDB reconnection for replica set - node.js

If I try to register for the event 'reconnect' in a MongoDB replicaset:
db.on('reconnect', () => console.log('Reconnected'));
I receive a deprecation warning as:
DeprecationWarning: The `reconnect` event is no longer supported by the unified topology
How can I handle a case of lost MongoDB connection (all servers in the replica set) but I want to be notified of servers availability status (when at least one server become again available)?
Suppose to handle this in a Node app with MongoDB native drivers.
Thanks in advance.

If we take a look at the spec regarding the unified topology, we can find the following section:
The unified topology is the first step in a paradigm shift away from a
concept of “connecting” to a MongoDB deployment using a connect
method. Consider for a moment what it means to be connected to a
replica set: do we trigger this state when connected to a primary? A
primary and one secondary? When connected to all known nodes? It’s
unclear whether its possible to answer this without introducing
something like a ReadPreference parameter to the connect method. At
this point “connecting” is just one half of “operation execution” -
you pass a ReadPreference in, and await a selectable server for the
operation, now we’re connected!
There are, however, new events you can listen to and that might be useful for your usecase -> see this for more information.

Related

Should I keep Sequelize instance throughout server running time?

I have a Sequelize instance and it is exported in a file to be accessed when doing DB operations.
const sequelize = new Sequelize('database', 'username', null, {
dialect: 'mysql'
});
module.exports = sequelize;
So the instance is created when the expressjs server starts and never destroys. I wonder if this is the correct way to do, or should I call new Sequelize every time I use the DB operation?
I think it should be kept alive because that's how DB pooling could take effect. Right?
The bottom line is - yes, it should stay alive. There is no performance hit whatsoever if you keep the instance alive. Because it will be the Sequelize instance (and by extension the ORM) which will handle the future connections. This also includes (as you noted) pooling.
The connections
When it comes to the pooling configuration itself, it get's a little tricky though. Depending on your configuration, the pool has some amount of "space" to work with - the limit to create connections, the idle duration after which connections are removed etc. I can certainly imagine a situation when keeping a connection alive is simply not needed - for example an internal system for a company which is not used overnight.
The Sequelize ORM gives you a good set of options to choose from when configuring your connection pool. In general, you do want to reuse connections as establishing new ones is quite expensive - not just because of the network (e.g. authorization, maybe proxy etc.) but also because of memory allocation which happens when you create a database connection (which is why reconnecting on every request is not a good idea..).
However, it all comes down to which database engine you use (and how busy your system is); MySQL can for example cache connections. When a connection is closed, it is returned to the thread cache rather than discarded (for some period of time). When a new connection opens, MySQL will look into the thread cache rather than try and establish a new connection.
You might want to go through these:
https://stackoverflow.com/a/4041136/8775880 (Good explanation on how pooling works)
https://stackoverflow.com/a/11659275/8775880 (Good explanation on how expensive it is to keep connections open)

how does mongodb replica set work with nodejs-mongoose?

Techstack used nodejs,mongoose,mongodb
i'm working on product that handles many DBrequests. During beginning of every month the db requests are high due to high read/write requests (bulk data processing). The number of records in each collection's targeted for serving these read/write requests are quite high. Read is high but write is not that high.
So the cpu utilization on the instance in which mongodb is running reaches the dangerzone(above 90%) during these times. The only thing that gets me through these times is HOPE (yes, hoping that instance will not crash).
Rather than scaling vertically, i'm looking for solutions to scale horizontally (not a revolutionary thought). i looked at replicaset and sharding. This question is only related to replicaSet.
i went through documents and i feel like the understanding i have on replicaset is not really the way it might work.
i have configured my replicaset with below configuration. i simply want to add one more instance because as per the understanding i have right now, if i add one more instance then my database can handle more read requests by distributing the load which could minimize the cpuUtilization by atleast 30% on primaryNode. is this understanding correct or wrong? Please share your thoughts
var configuration = {
_id : "testReplicaDB",
members:[
{_id:0,host:"localhost:12017"},
{_id:1,host:"localhost:12018",arbiterOnly:true,buildIndexes:false},
{_id:2,host:"localhost:12019"}
]
}
When i broughtup the replicaset with above config and ran my nodejs-mongoose code, i ran into this issue . Resolution they are proposing is to change the above config into
var configuration = {
_id : "testReplicaDB",
members:[
{_id:0,host:"validdomain.com:12017"},
{_id:1,host:"validdomain.com:12018",arbiterOnly:true,buildIndexes:false},
{_id:2,host:"validdomain.com:12019"}
]
}
Question 1 (related to the coding written in nodejsproject with mongoose library(for handling db) which connects to the replicaSet)
const URI = mongodb://167.99.21.9:12017,167.99.21.9:12019/${DB};
i have to specify both uri's of my mongodb instances in mongoose connection URI String.
When i look at my nodejs-mongoose code that will connect to the replicaSet, i have many doubts on how it might handle the multipleNode.
How does mongoose know which ip is the primaryNode?
Lets assume 167.99.21.9:12019 is primaryNode and rs.slaveOk(false) on secondaryReplica, so secondaryNode cannot serve readRequests.
In this situation, does mongoose trigger to the first uri(167.99.21.9:12017) and this instance would redirect to the primaryNode or will the request comeback to mongoose and then mongoose will trigger another request to the 167.99.21.9:12019 ?
Question 2
This docLink mention's that data redundancy enables to handle high read requests. Lets assume, read is enabled for secondaryNode, and
Lets assume the case when mongoose triggers a request to primaryNode and primaryNode was getting bombarded at that time with read/write requests but secondaryNode is free(doing nothing) , then will mongodb automatically redirect the request to secondaryNode or will this request fail and redirect back to mongoose, so that the burden will be on mongoose to trigger another request to the next available Node?
can mongoose automatically know which Node in the replicaSet is free?
Question 3
Assuming both 167.99.21.9:12017 & 167.99.21.9:12019 instances are available for read requests with ReadPreference.SecondaryPreferred or ReadPreference.nearest, will the load get distributed when secondaryNode gets bombarded with readRequests and primaryNode is like 20% utilization? is this the case? or is my understanding wrong? Can the replicaSet act as a loadbalancer? if not, how to make it balance the load?
Question 4
var configuration = {
_id : "testReplicaDB",
members:[
{_id:0,host:"validdomain.com:12017"},
{_id:1,host:"validdomain.com:12018",arbiterOnly:true,buildIndexes:false},
{_id:2,host:"validdomain.com:12019"}
]
}
You can see the DNS name in the configuration, does this mean that when primaryNode redirects a request to secondaryNode, DNS resolution will happen and then using that IP which corresponds to secondaryNode, the request will be redirected to secondaryNode? is my understanding correct or wrong? (if my understanding is correct, this is going to fireup another set of questions)
:|
i could've missed many details while reading the docs. This is my last hope of getting answers. So please share if you know the answers to any of these.
if this is the case, then how does mongoose know which ip is the primaryReplicaset?
There is no "primary replica set", there can be however a primary in a replica set.
Each MongoDB driver queries all of the hosts specified in the connection string to discover the members of the replica set (in case one or more of the hosts is unavailable for whatever reason). When any member of the replica set responds, it does so with the full list of current members of the replica set. The driver then knows what the replica set members are, and which of them is currently primary (if any).
secondaryReplica cannot serve readRequests
This is not at all true. Any data-bearing node can fulfill read requests, IF the application provided a suitable read preference.
In this situation, does mongoose trigger to the first uri(167.99.21.9:12017) and this instance would redirect to the primaryReplicaset or will the request comeback to mongoose and then mongoose will trigger another request to the 167.99.21.9:12019 ?
mongoose does not directly talk to the database. It uses the driver (node driver for MongoDB) to do so. The driver has connections to all replica set members, and sends the requests to the appropriate node.
For example, if you specified a primary read preference, the driver would send that query to the primary if one exists. If you specified a secondary read preference, the driver would send that query to a secondary if one exists.
i'm assuming that when both 167.99.21.9:12017 & 167.99.21.9:12019 instances are available for read requests with ReadPreference.SecondaryPreferred or ReadPreference.nearest
Correct, any node can fulfill those.
the load could get distributed across
Yes and no. In general replicas may have stale data. If you require current data, you must read from the primary. If you do not require current data, you may read from secondaries.
how to make it balance the load?
You can make your application balance the load by using secondary or nearest reads, assuming it is OK for your application to receive stale data.
if mongoose triggers a request to primaryReplica and primaryReplica is bombarded with read/write requests and secondaryReplica is free(doing nothing) , then will mongodb automatically redirect the request to secondaryReplica?
No, a primary read will not be changed to a secondary read.
Especially in the scenario you are describing, the secondary is likely to be stale, thus a secondary read is likely to produce wrong results.
can mongoose automatically know which replica is free?
mongoose does not track deployment state, the driver is responsible for this. There is limited support in drivers for choosing a "less loaded" node, although this is measured based on network latency and not CPU/memory/disk load and only applies to the nearest read preference.

mongodb failover connection

I have a nodejs app that connects to mongodb.
Mongodb allows replicaset client connection to provide a level of resilience.
e.g "mongodb://localhost:50000,localhost:50001/myproject?replicaSet=foo", the client first connects to localhost#50000 and if that dies it switches to localhost#50001.
This is fine but if when the application starts and if one of the two mongo is dead then the application dies - with can't connect error.
The only solution I can think is to reformat the url so it excludes the inactive instance, but would like to avoid this ...
Any ideas?
Thanks
Replicaset works fine when do you have an odd number of servers, because MongoDB ReplicaSet work using election between nodes for define what server will be the "primary".
You can to add a new node in your ReplicaSet just for voting. It's called "ARBITER".
You can understand more about ReplicaSet Elections on this page https://docs.mongodb.com/manual/core/replica-set-elections/#replica-set-elections.
As Rafael mentioned, a replica set needs an odd number of members to be able to function properly when some of the members are offline. There are more details in the Replica Set Elections docs page, but the most relevant is:
If a majority of the replica set is inaccessible or unavailable to the current primary, the primary will step down and become a secondary. The replica set cannot accept writes after this occurs, but remaining members can continue to serve read queries if such queries are configured to run on secondaries.
The node driver by default requires a Primary to be online to be able to connect to the replica set, and will output an error you observed when you try to connect to a replica set without a Primary.
This default behaviour can be changed by setting connectWithNoPrimary to true. However, to be able to do queries, you also should set the proper readPreference setting (which also defaults to Primary). For example:
var MongoClient = require('mongodb').MongoClient
conn = MongoClient.connect('mongodb://localhost:27017,localhost:27018,localhost:27019/test',
{
replicaSet: 'replset',
connectWithNoPrimary: true,
readPreference: 'primaryPreferred'
}).catch(console.log)
More information about the connection options can be found in the Node Driver URI Connection Settings page

MongoDB Replica Connections from NodeJS

My NodeJS client is able to connect to the MongoDB primary server and interact with it, as per requirements.
I use the following code to build a Server Object
var dbServer = new Server(
host, // primary server IP address
port,
{
auto_reconnect: true,
poolSize: poolSize
});
and the following code to create a DB Object:
var db = new Db(
'MyDB',
dbServer,
{ w: 1 }
);
I was under the impression, that when the primary goes down, the client will automatically figure out that it now needs to talk to one of the secondaries, which will be elected to be a primary.
But when I manually kill the primary server, one of the secondary servers does become the primary (as can be observed from its mongo shell and the fact that it now responds to mongo shell commands), but the client doesn't automatically talk to it. How do I configure NodeJS server to automatically switch to the secondary?
Do, I need to specify all 3 server addresses somewhere? But that doesn't seem like a good solution, as once the primary is back on line, it's IP address will be different from what it originally was.
I feel that I am missing something very basic, please enlighten me :)
Thank You,
Gary
Well your understanding is part there but there are some problems. The general premise of assigning more than a Single server in the connection is that should that server address be unavailable at the time of connection, then something else from the "seed list" will be chosen in order to establish the connection. This removes a single point of failure such as the "Primary" being unavailable at this time.
Where this is a "replica Set" then the driver will discover the members once connected and then "automatically" switch to the new "Primary" as that member is elected. So this does require that your "replica Set" is actually capable of electing a new "Primary" in order to switch the connection. Additionally, this is not "instantaneous", so there can be a delay before the new "Primary" is promoted and able to accept operations.
Your "auto_reconnect" setting is also not doing what you think it is doing. All this manages is that if a connection "error" occurs, the driver will "automatically" retry the connection without throwing an exception. What you likely really want to do is handle this yourself as you could end up infinitely retrying a connection that just cannot be made. So good code would take this into account, and manage the "re-connect" attempts itself with some reasonably handling and logging.
Your final point on IP addresses is generally addressed by using hostnames that resolve to an IP address where those "hostnames" never change, regardless of what they resolve to. This is equally important for the driver as it is for the "replica set" itself. As indeed if the server members are looking for another member by an IP address that changes, then they do not know what to look for.
So the driver will "fail over" or otherwise select a new available "Primary", but only within the same tolerances that the servers can also communicate with each other. You should seed you connections as you cannot guarantee which node is the "Primary" when you connect. Finally you should use hostnames instead of IP addresses if the latter is subject to change.
The driver will "self discover", but again it is only using the configuration available to the replica set in order to do so. If that configuration is invalid for the replica set, then it is invalid for the driver as well.
Example:
MongoClient.connect("mongodb://member1,member2,member3/database", function(err,db) {
})
Or other with an array of Server objects instead.

reuse mongodb connection and close it

I'm using the Node native client 1.4 in my application and I found something in the document a little bit confusing:
A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback:
Several questions come in mind when reading this:
Does it mean the db object also maintains the fail over feature provided by replica set? Which I thought should be the work of MongoClient (not sure about this but the C# driver document does say MongoClient maintains replica set stuff)
If I'm reusing the db object, when should I invoke the db.close() function? I saw the db.close() in every example. But shouldn't we keep it open if we want to reuse it?
EDIT:
As it's a topic about reusing, I'd also want to know how we can share the db in different functions/objects?
As the project grows bigger, I don't want to nest all the functions/objects in one big closure, but I also don't want to pass it to all the functions/objects.
What's a more elegant way to share it among the application?
The concept of "connection pooling" for database connections has been around for some time. It really is a common sense approach as when you consider it, establishing a connection to a database every time you wish to issue a query is very costly and you don't want to be doing that with the additional overhead involved.
So the general principle is there that you have an object handle ( db reference in this case ) that essentially goes and checks for which "pooled" connection it can use, and possibly if the current "pool" is fully utilized then and create another ( or a few others ) connection up to the pool limit in order to service the request.
The MongoClient class itself is just a constructor or "factory" type class whose purpose is to establish the connections and indeed the connection pool and return a handle to the database for later usage. So it is actually the connections created here that are managed for things such as replica set fail-over or possibly choosing another router instance from the available instances and generally handling the connections.
As such, the general practice in "long lived" applications is that "handle" is either globally available or able to be retrieved from an instance manager to give access to the available connections. This avoids the need to "establish" a new connection elsewhere in your code, which has already been stated as a costly operation.
You mention the "example" code which is often present through many such driver implementation manuals often or always calling db.close. But these are just examples and not intended as long running applications, and as such those examples tend to be "cycle complete" in that they show all of the "initialization", the "usage" of various methods, and finally the "cleanup" as the application exits.
Good application or ODM type implementations will typically have a way to setup connections, share the pool and then gracefully cleanup when the application finally exits. You might write your code just like "manual page" examples for small scripts, but for a larger long running application you are probably going to implement code to "clean up" your connections as your actual application exits.

Resources