A MongoDB secondary is lagging or stuck in RECOVERING state. What do you do?
IntermediateScenarioMongoDB
Answer
Short answer
Check replication lag and the member's state in rs.status(). Lag usually comes from heavy write load, a slow/undersized secondary or long-running queries on it. RECOVERING that never ends often means the secondary fell off the oplog (it was behind longer than the oplog window) and needs an initial sync / resync.
Investigate
rs.status().members.map(m => ({ name: m.name, state: m.stateStr, lagSec: m.optimeDate && (rs.status().date - m.optimeDate) / 1000 }))
rs.printSecondaryReplicationInfo()
rs.printReplicationInfo() // oplog window
Check the secondary's logs for too stale to catch up.
Fixes
| Situation | Action |
|---|---|
| Lag from heavy writes / weak node | Same instance size and disk as primary; reduce bulk write batches |
| Long queries on secondary | Move analytics to a hidden member; kill long ops |
| "Too stale to catch up" | Resync: stop mongod, clear its data directory, start → initial sync (or restore from a snapshot) |
| Oplog too small | Increase it (replSetResizeOplog) to give more headroom |
What to say in the interview
"I check rs.status and replication info for lag and the oplog window. Lag is usually load or an undersized node; a member stuck in RECOVERING with 'too stale' in logs has fallen off the oplog and needs an initial sync or snapshot restore, then I enlarge the oplog."