Working with Replication
1. Understanding Replica Set Architecture
┌──────────┐ replication ┌──────────┐
│ Primary │ ───────────────▶ │Secondary │
└────┬─────┘ └──────────┘
│ ┌──────────┐
└──────────────────────▶ │Secondary │
└──────────┘
| Role | Detail |
|---|---|
| Primary | Accepts writes |
| Secondary | Replicates oplog; can serve reads |
| Arbiter | Votes only; no data |
2. Initiating Replica Set
rs.initiate({ _id: "rs0", members: [
{ _id: 0, host: "m1:27017" },
{ _id: 1, host: "m2:27017" },
{ _id: 2, host: "m3:27017" }
]});
| Method | Detail |
|---|---|
| rs.initiate() | Bootstraps replica set |
| rs.conf() / rs.status() | Inspect |
3. Adding Replica Members
| Method | Form |
|---|---|
| rs.add | rs.add("m4:27017") |
| With config | rs.add({host, priority, votes, hidden}) |
4. Removing Replica Members
| Method | Detail |
|---|---|
| rs.remove("host:port") | Removes from config |
| Reconfig | Use rs.reconfig() for atomic updates |
5. Configuring Priority
| Value | Effect |
|---|---|
| 0 | Cannot become primary |
| 1 (default) | Normal eligibility |
| >1 | Preferred primary |
6. Setting Up Arbiter
| Aspect | Detail |
|---|---|
| Add | rs.addArb("host:port") |
| Purpose | Break ties in odd-vote situations |
| Caution | Avoid PSA topologies—affects majority writes |
7. Using Hidden Members
| Property | Detail |
|---|---|
| hidden: true | Invisible to clients |
| priority: 0 | Required |
| Use | Analytics, backup, reporting |
8. Configuring Delayed Members
| Property | Detail |
|---|---|
| secondaryDelaySecs | Delay before applying ops |
| Requires | priority:0, hidden:true |
| Use | Protection against operator errors |
9. Checking Replica Status
| Method | Detail |
|---|---|
| rs.status() | Member states, lag, optime |
| rs.printReplicationInfo() | Oplog window summary |
| rs.printSecondaryReplicationInfo() | Per-secondary lag |
10. Forcing Election
| Method | Detail |
|---|---|
| rs.stepDown(secs) | Steps down current primary |
| rs.freeze(secs) | Prevent secondary from being elected |
| replSetStepUp | Request election |
11. Understanding Oplog
| Aspect | Detail |
|---|---|
| Namespace | local.oplog.rs (capped) |
| Idempotent | Ops can be re-applied safely |
| Window | How far back secondaries can resync |
12. Setting Oplog Size
| Method | Detail |
|---|---|
| --oplogSize MB | Set at startup |
| replSetResizeOplog | Resize at runtime (4.0+) |
| minRetentionHours | Minimum retention window (4.4+) |