Search code examples
node.jsdatabasemongodbmongodb-queryreplicaset

Mongo replica sets load management


Currently I have two node applications which use a mongo replica set (1 primary and 6 secondary). Currently the read queries of one application cause a load on mongo and affect the performance of the other application. So, I want to divide the secondary nodes such that 1 application uses the primary and 4 secondary members and the other application uses the primary and the other 2 secondary members. I don't want the load on one application to affect the other. How do i achieve the same?


Solution

  • You can set different tags per application and read from SECONDARY members per defined tag , for example:

    app1--> db.collection.find({}).readPref( "secondary", [ { "app": "app1" } ] )
    app2--> db.collection.find({}).readPref( "secondary", [ { "app": "app2" } ] )
    

    And have you replicaSet as follow:

    {
    "_id" : "myrs",
    "version" : 2,
    "members" : [
             {
                     "_id" : 0,
                     "host" : "host1:27017",
                     "tags" : {
                             "app": "app1"
                     }
             }, {
                     "_id" : 1,
                     "host" : "host2:27017",
                     "tags" : {
                             "app": "app1"
                     }
             }, {
                     "_id" : 2,
                     "host" : "host3:27017",
                     "tags" : {
                             "app": "app1"
                     }
             },  {
                     "_id" : 3,
                     "host" : "host4:27017",
                     "tags" : {
                             "app": "app2"
    
                     }
             },  {
                     "_id" : 4,
                     "host" : "host4:27017",
                     "tags" : {
                             "app": "app2"
    
                     }
             }           
    ]
    }
    

    How to add the tags:

    conf = rs.conf();
    conf.members[0].tags = { "app": "app1" };
    conf.members[1].tags = { "app": "app1" };
    conf.members[2].tags = { "app": "app2" };
    conf.members[3].tags = { "app": "app2" };
    conf.members[4].tags = { "app": "app2" };
    rs.reconfig(conf);