Elections and Automatic Failover
Learners will simulate a primary failure and observe the election algorithm that promotes a secondary, keeping downtime under 10 seconds.
Why Automatic Failover Matters
Automatic failover is the ability of a MongoDB replica set to recover from a primary node failure without human intervention. When the primary becomes unreachable, the remaining members automatically elect a new primary — typically within 10 to 30 seconds — so that applications experience only a brief pause rather than a full outage.
Heartbeats: Detecting Failures
Replica set members continuously exchange heartbeat messages every 2 seconds. If a member does not receive a heartbeat response within electionTimeoutMillis (default 10 seconds), it marks the silent member as inaccessible. If the missing member is the primary, the remaining eligible members begin an election.
// Check heartbeat interval and election timeout in replica set config
rs.conf().settings.heartbeatIntervalMillis // 2000 ms
rs.conf().settings.electionTimeoutMillis // 10000 ms