Replica sets

Replication and Read Preferences

 1. Replication

Replication means copying data across multiple servers.

MongoDB uses something called a Replica Set

How it works:

  • Primary node → handles all writes
  • Secondary nodes → copy data from primary


Example:

  • Server 1 → Primary
  • Server 2 → Secondary
  • Server 3 → Secondary

All data is duplicated


🔹 Why Replication is Used

  • High availability (if one server fails)
  • Data redundancy
  • Disaster recovery


🔹 Failover

If primary fails:

  • One secondary becomes new primary automatically

This ensures system keeps running


🔹 2. Read Preferences

Read preference decides from which node data is read.


🔹 Types of Read Preferences

1. primary

Read only from primary

  • Most consistent data
  • Default mode


2. primaryPreferred

Read from primary, fallback to secondary


3. secondary

Read only from secondary

  • Reduces load on primary


4. secondaryPreferred

Prefer secondary, fallback to primary


5. nearest

Read from closest node (lowest latency)


🔹 Why Read Preferences Matter

  • Improve performance
  • Reduce load on primary
  • Balance traffic

Important Note

  • Primary → always up-to-date
  • Secondary → may have slight delay (eventual consistency)


Simple Understanding

  • Replication → copy data to multiple servers
  • Read preference → choose where to read from