A replica set is MongoDB's primary mechanism for high availability and data redundancy. It consists of a group of MongoDB instances that maintain the same data set, including one primary node that handles all write operations and one or more secondary nodes that replicate data from the primary. If the primary fails, the replica set automatically triggers an election to promote a secondary to primary, ensuring continuous service with minimal downtime.
Replication itself works through the oplog, a special capped collection on the primary that records every write operation. Secondary nodes continuously tail the oplog and apply the operations locally, keeping their copies of the data in sync. This architecture provides data redundancy, enables automatic failover, and allows read operations to be distributed across secondaries to reduce load on the primary. When a replica set has an even number of data-bearing members, an arbiter can be added to break ties during primary elections. Arbiters participate in elections but do not hold any data, making them lightweight and resource-efficient, though they should be used sparingly in production environments.
Two important settings govern how clients interact with replica sets. Write concern specifies the level of acknowledgment requested for write operations: w: 0 means no acknowledgment, w: 1 means acknowledgment from the primary alone (the default), and w: "majority" requires acknowledgment from a majority of members. Higher write concern improves durability at the cost of latency. Read preference, on the other hand, determines which members receive read operations. Options include primary (the default), primaryPreferred, secondary, secondaryPreferred, and nearest (the member with the lowest latency). Together, these settings allow applications to balance consistency, availability, and performance based on their specific requirements.