Problem Statement
Explain the concept of replica sets in MongoDB and how they ensure high availability.
Explanation
A replica set in MongoDB is a group of mongod instances that maintain identical copies of data. It consists of one primary node and multiple secondary nodes. The primary node receives all write operations, while secondary nodes replicate the primary's data by continuously copying and applying operations from the oplog.
Replica sets ensure high availability through automatic failover. If the primary node becomes unavailable due to hardware failure, network issues, or maintenance, the replica set automatically initiates an election. During the election, the remaining secondary nodes vote to select a new primary from among themselves.
The election process typically completes within seconds. The node with the highest priority and most up-to-date data is usually elected. Once a new primary is elected, the replica set resumes normal operations, accepting writes again. This automatic failover ensures that your application experiences minimal downtime.
Replica sets also provide data redundancy. Since data is stored on multiple servers, you can recover from server failures without data loss. Additionally, you can use secondaries for read operations, distributing the load and improving read performance for read-heavy applications.
Code Solution
SolutionRead Only
// Three-member replica set // Primary: handles all writes // Secondary 1: replicates data, can serve reads // Secondary 2: replicates data, can serve reads // If primary fails: // 1. Secondaries detect primary is unreachable // 2. Election starts automatically // 3. One secondary becomes new primary // 4. Applications reconnect to new primary // 5. Failed node rejoins as secondary when recovered
