Lesson 39 of 50 – MongoDB Replication
78%

MongoDB Replication

MongoDB replication maintains multiple copies of data across MongoDB servers. A group of MongoDB servers that maintain the same data set is called a replica set. Replication helps provide data availability and supports recovery when a server becomes unavailable.

1. What Is Replication?

Replication is the process of maintaining copies of database data on multiple servers.

For example, a school management system stores:

  • Student records
  • Course details
  • Fee payment information
  • Attendance records

If the primary server becomes unavailable, an eligible secondary member may be elected as the new primary. This helps the application continue operating, subject to the replica set's health and configuration.

Replication is not a replacement for backups. Accidental changes or deletions may also be replicated to other members.

2. What Is a Replica Set?

A replica set is a group of MongoDB instances that maintain the same data set and coordinate through replication and elections.

                 Replica Set
                      |
          ---------------------------
          |            |            |
       Primary      Secondary    Secondary
          |            |            |
       Writes      Data Copy    Data Copy

This diagram illustrates a common three-member replica set. The primary receives writes, and secondary members replicate the primary's operations.

Secondary members can serve certain reads if the application uses an appropriate read preference. By default, MongoDB reads from the primary.

3. Types of Replica Set Members

Member Purpose
Primary Normally receives write operations.
Secondary Replicates operations from the primary.
Arbiter Votes in elections but does not maintain a copy of the data set.
Hidden member A secondary hidden from normal client discovery and unsuitable for ordinary application reads.

An arbiter can participate in elections, but it cannot replace a data-bearing member or provide a copy of the data. Production deployments should be designed carefully around voting members, failure tolerance, and data redundancy.

4. Benefits of Replication

  • High availability: Helps keep the service available during certain server failures.
  • Automatic elections: Eligible members can elect a new primary when required.
  • Data redundancy: Multiple data-bearing members maintain copies of the data.
  • Read scaling: Some read workloads can be directed to secondary members.
  • Maintenance flexibility: Supports certain maintenance operations with less downtime when planned correctly.

Replication does not guarantee zero data loss or uninterrupted availability in every failure scenario. Durability depends on settings such as write concern and on the health of the replica set.

5. Requirements for a Local Practice Replica Set

You can practise replication locally by running multiple MongoDB server processes on the same computer, each using a different data directory and port.

Example directory structure:

mongodb-replica/
    node1/
    node2/
    node3/

For this beginner example, use a development machine, keep the test server private, and do not use production data.

The following commands assume MongoDB Server is installed and mongod is available in your PATH. Run each server in a separate terminal.

Terminal 1 – First member:

mkdir -p ./mongodb-replica/node1

mongod \
  --replSet rs0 \
  --port 27017 \
  --dbpath ./mongodb-replica/node1 \
  --bind_ip localhost

Terminal 2 – Second member:

mkdir -p ./mongodb-replica/node2

mongod \
  --replSet rs0 \
  --port 27018 \
  --dbpath ./mongodb-replica/node2 \
  --bind_ip localhost

Terminal 3 – Third member:

mkdir -p ./mongodb-replica/node3

mongod \
  --replSet rs0 \
  --port 27019 \
  --dbpath ./mongodb-replica/node3 \
  --bind_ip localhost

These shell commands use Unix-style syntax. On Windows, create the directories manually or use the appropriate PowerShell commands, and ensure each process has a writable data directory.

These are local practice instances without authentication. Keep them bound to localhost and never expose them to an untrusted network. A production replica set needs suitable access controls and internal member authentication.

6. Initialize the Replica Set

Connect to the first member using MongoDB Shell:

mongosh --port 27017

Initialize the replica set:

rs.initiate({
    _id: "rs0",
    members: [
        { _id: 0, host: "localhost:27017" },
        { _id: 1, host: "localhost:27018" },
        { _id: 2, host: "localhost:27019" }
    ]
})

The _id value identifies the replica set. Each member also has a unique numeric ID and a host address that other members can reach.

Wait briefly for the election to complete. The first member will normally become primary in this practice setup, but the election outcome is not guaranteed.

All configured hostnames must resolve correctly and be reachable by the other members. For production deployments, use stable network addresses and follow MongoDB's security and deployment requirements.

7. Check Replica Set Status

Run the following command in the shell:

rs.status()

The output includes replica set health, member state, and replication information.

You can also check the current member's role:

db.hello()

Look for the isWritablePrimary field. A value of true indicates that the connected member is currently writable as primary.

To inspect the replica set configuration, run:

rs.conf()

8. Insert Data into the Primary

Once the replica set has a primary, connect to the replica set and insert a test document.

mongosh "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0"

Then run:

use school

db.students.insertOne({
    name: "Rahul Kumar",
    course: "MongoDB",
    city: "Aurangabad"
})

The write is sent to the primary. Secondary members replicate the operation from the primary's operation log.

With the default write concern, acknowledgment and replication timing depend on the deployment and its configuration. Do not assume every secondary has already applied a write immediately after it succeeds.

9. Read Data from a Secondary

By default, MongoDB clients read from the primary. To read from a secondary, select a suitable read preference, such as secondary.

mongosh "mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0&readPreference=secondary"

Then query the collection:

use school

db.students.find()

A secondary may lag behind the primary, so a secondary read may not immediately include the latest write. Use a read preference and consistency strategy suitable for the application's requirements.

10. Primary Election and Failover

If the primary becomes unavailable, eligible voting members may hold an election to choose a new primary. The application may experience a temporary interruption while the election takes place.

For example:

Before failure:
Primary   -> Node 1
Secondary -> Node 2
Secondary -> Node 3

After a successful election:
Secondary -> Node 1 (unavailable)
Primary   -> Node 2
Secondary -> Node 3

This is an illustrative example. The actual new primary depends on member health, voting configuration, eligibility, and election results.

Do not stop database processes on a production server to test failover unless you have an approved maintenance or testing plan. Practise with local test instances instead.

11. Replication vs Backup

Replication Backup
Maintains copies across replica set members. Stores a recoverable copy of data.
Supports availability and failover. Supports recovery from accidental deletion or corruption.
Changes are generally replicated to other members. A backup preserves the data captured at its backup point.
Does not replace a backup strategy. Does not by itself provide automatic failover.

12. Best Practices

  • Use multiple data-bearing members for production high availability.
  • Place members across suitable failure domains where possible.
  • Configure authentication and network security.
  • Monitor member health, replication lag, and elections.
  • Use an appropriate write concern for important writes.
  • Maintain and test independent backups.
  • Use stable hostnames and correct network configuration.
  • Test failover and recovery procedures in a non-production environment.

13. Practical Assignment

  1. Run three local MongoDB instances on different ports.
  2. Initialize a replica set named rs0.
  3. Check the replica set status using rs.status().
  4. Insert a sample student document into the primary.
  5. Connect using a replica set connection string.
  6. Read data using a secondary read preference.
  7. Inspect the replica set configuration using rs.conf().
  8. Explain how a new primary can be elected.
  9. Describe the difference between replication and backup.
  10. Explain why authentication and backups are still necessary.

🧠 Quick Quiz

1. What is a MongoDB replica set?




2. Which member normally receives write operations?




3. Does replication replace independent backups?