Sobes.tech
Junior

What is a replica set and what is it used for?

sobes.tech AI

Answer from AI

A replica set in MongoDB is a group of multiple MongoDB servers (nodes, members) that collectively store identical sets of data. It provides high availability and fault tolerance.

Key components:

  • Primary: One node that accepts all write operations.
  • Secondaries: One or more nodes that replicate data from the primary and can handle read operations.
  • Arbiter (optional): A node that does not store data but participates only in elections for the primary in case of failure.

Main purposes:

  • High availability: If the primary node fails, secondaries automatically elect a new primary, ensuring continuous operation.
  • Fault tolerance: Data is duplicated across multiple nodes, minimizing the risk of data loss in case of a node failure.
  • Distributed reading: Read operations can be distributed among secondary nodes, increasing throughput.
  • Data recovery: The replica set simplifies data recovery after a failure.

Working process: write operations are first applied to the primary, then asynchronously replicated to secondaries via the oplog (operation log).

Example configuration (initializing a replica set):

// Connect to MongoDB as usual
// ...
rs.initiate({
  _id: "myReplicaSet", // Name of the replica set
  members: [
    { _id: 0, host: "mongo1.example.com:27017" }, // Primary
    { _id: 1, host: "mongo2.example.com:27017" }, // Secondary
    { _id: 2, host: "mongo3.example.com:27017", priority: 0, votes: 1 } // Arbiter
  ]
})

Node roles table:

Role Accepts writes Accepts reads (default) Stores data Participates in elections
Primary Yes Yes Yes Yes
Secondary No Yes* Yes Yes
Arbiter No No No Yes

*Reading from secondary can be configured using read policies.