4 Hours

6. Replica Sets: High Availability & Data Redundancy

High Availability

Building Highly Available MongoDB Deployments

A single MongoDB server is a single point of failure. If it dies, your application stops. Senior engineers build High Availability (HA) systems using Replica Sets. This module covers how MongoDB replica sets work, how to configure them, and how to handle failover.

Replica sets provide redundancy and high availability. A replica set consists of multiple MongoDB nodes that replicate data. One node is the primary (writes), and the others are secondaries (reads). If the primary fails, the secondaries elect a new primary automatically. Replica sets also provide data redundancy — if a node fails, the data is still available on other nodes. Understanding replica sets is essential for production MongoDB deployments. Replica sets are the foundation of high availability and disaster recovery.

Replica Set Architecture

A replica set typically has three nodes: one primary and two secondaries. The primary accepts all write operations. The secondaries replicate the primary's oplog (operation log) and apply the changes asynchronously. This provides data redundancy. If the primary fails, the secondaries elect a new primary through a consensus process. The election is automatic and takes 10-30 seconds. Replica sets also support read preferences — you can read from secondaries to distribute read load. Secondary reads are eventually consistent. Use secondary reads for non-critical queries.

JavaScript
// Configure replica set in MongoDB shell
rs.initiate({
  _id: 'rs0',
  members: [
    { _id: 0, host: 'mongo1:27017' },
    { _id: 1, host: 'mongo2:27017' },
    { _id: 2, host: 'mongo3:27017' }
  ]
});

// Check replica set status
rs.status();

// Check replica set configuration
rs.conf();

// Read from secondary
const client = new MongoClient('mongodb://primary:27017', {
  readPreference: 'secondaryPreferred'
});

Failover and Election

Failover is the process of switching from a failed primary to a secondary. MongoDB uses a consensus protocol (Raft) for leader election. When the primary fails, the secondaries detect the failure and hold an election. The election chooses a new primary based on priority, optime, and other factors. The election typically takes 10-30 seconds. During the election, the replica set is read-only. Application code should handle connection failures and retry logic. Use connection pooling with retryable writes for automatic retry.

JavaScript
// Connection string for replica set
const uri = 'mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0';

// Configure retryable writes
const client = new MongoClient(uri, {
  retryWrites: true,
  w: 'majority'
});

// Handle connection failures with retry
async function withRetry(operation) {
  let retries = 3;
  while (retries > 0) {
    try {
      return await operation();
    } catch (error) {
      retries--;
      if (retries === 0) throw error;
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
}

Monitoring and Maintenance

Monitoring replica sets is essential for maintaining reliability. The rs.status() command shows the current state of the replica set. It shows which node is the primary, the state of each node, and replication lag. Replication lag is the delay between the primary and secondaries. High lag indicates performance issues. The MongoDB Atlas monitoring provides real-time insights. Regular maintenance includes oplog management and backup. The oplog grows over time and needs to be sized appropriately. Backup strategies include mongodump and file system snapshots.

  • rs.status(): Shows replica set state and member status.
  • rs.conf(): Shows replica set configuration.
  • Replication Lag: Monitor the delay between primary and secondaries.
  • Oplog Size: Ensure the oplog is sized for your replication needs.
  • Backups: Use mongodump or file system snapshots.

Knowledge Check

Ready to test your understanding of 6. Replica Sets: High Availability & Data Redundancy?

Back