Skip to main content

MongoDB Replica set

  • Primary node: where write happened
  • Secondory nodes: Syncs data from Primary node.
  • Election: When primary node goes down, voting happens and one of the secondory becomes primary. But once the earlier primary node is back healthy, it will join the replicaset and sync from new primare and acts as secondory.

Binary replicationโ€‹

  • Less data
  • Faster
  • Tight dependancy on underlying OS and the mongod version

Statement-based replicationโ€‹

  • Bigger data
  • Not bound to OS, so useful for cross platform solutions.
    note

    MongoDB uses statement-based replication, not binary replication. MongoDB uses a small variation of statement-based replication which reduces statements to idempotent versions so they can be repeated.

Replication in MondoDBโ€‹

  • Write happens to primary
  • Protocol version 1 (PV1)
  • oplog is statement-based log
  • Arbitor node can be useful for Primary election and it does not hold any data. But better not to use them.
    important

    Any topoogy change will trigger an election

Steps to create replicaโ€‹

  • Create key file for the mongo nodes to talk to each other
openssl rand -base64 741 > /var/mongodb/pki/m103-keyfile
chmod 600 /var/mongodb/pki/m103-keyfile
  • Add the key file info in the mongod.conf
security:
authorization: enabled
keyFile: /var/mongodb/pki/m103-keyfile
  • Create user
use admin
db.createUser({
user: "m103-admin",
pwd: "m103-pass",
roles: [
{role: "root", db: "admin"}
]
})
rs.initiate()
rs.status()
rs.add("m103:27017")
rs.add("m103:27017")
rs.isMaster()

When connecting to a replica set, the mongo shell will redirect the connection to the primary node.

Member propertiesโ€‹

  • arbitorOnly: true or false; when selected true, member contribute only for master election; default = false
  • hidden: true or false; not visible to the application, not listed in rs.isMaster() response; default = false
  • priority: 1-1000, higher the number - higher the chance to be elected as master, set to zero if member should not be primery ever.
  • slaveDelay: replication delay in seconds. default = 0
    info

    If non-zero integer is set as slaveDelay, update hidden: true and priority: 0 . The intention of providing this options is to provide the feasibility of restoring the data from past in case unexpected events happens on data.

Replication commandsโ€‹

  • rs.status() :
    • Reports health, state, uptime on replica set nodes
    • Uses data from heartbeats
  • rs.isMaster() :
    • briefs rs.status().
    • Display list of node and wich is master node
  • db.serverStatus()['repl']:
    • along with isMaster() status, it is display roleback information.
  • rs.printReplicationInfo():
    • Displays oplog info such as size, first event time, last event time.

Connection Stringโ€‹

mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?authSource=admin&replicaSet=myRepl