A MongoDB replica-set elects a new primary when members stop hearing from the current one. The defaults — 10s election timeout, 2s heartbeats — work for well-behaved data-centre networks and feel painfully aggressive on cross-region links. Tune the wrong knob and you trade one symptom (spurious elections) for another (a five-minute window where writes go to a primary that’s already isolated). This article maps the four heartbeat-related parameters to the failure modes they actually control.
How to verify
Read the current replica-set configuration and compare against running member state:
mongosh --host primary.example.internal:27017
rs.conf().settings
rs.status().members.forEach(m => print(m.name, m.stateStr, m.lastHeartbeatRecv, m.pingMs))
db.adminCommand({ replSetGetConfig: 1, commitmentStatus: true })
db.serverStatus().electionMetrics
pingMs and lastHeartbeatRecv per member reveal the actual round-trip you’re working with. electionMetrics exposes counters — numElectionTimeoutsCalled, numStepDownsCausedByHigherTerm, priorityTakeover — that tell you whether you’re tuning a real problem or a phantom.
What’s happening
Every member sends a heartbeat to every other member every heartbeatIntervalMillis (default 2000). A secondary considers the primary unreachable when it has not received a heartbeat reply within electionTimeoutMillis (default 10000). When that threshold trips, the secondary calls for a vote; majority wins and becomes primary. The replication protocol (pv1) couples elections to a monotonically increasing term, so a primary discovering a higher term immediately steps down — preventing the textbook split-brain.
The trouble is that a flaky network can make a healthy primary look dead. Cross-region links lose packets in bursts; a microbursting LAN can lose ten seconds of heartbeats without dropping a single TCP connection. Each spurious election causes a write outage of up to electionTimeoutMillis + the election duration, plus the time the application needs to retry against the new primary. Lengthening the timeout reduces the spurious-election rate but extends the legitimate-failure detection window.
catchUpTimeoutMillis is the other failover knob: after winning, the new primary spends up to that long pulling oplog entries from members that were ahead before declaring itself ready. Set too short, you lose recent writes from the old primary; set too long and the post-election write outage extends.
The procedure
-
Measure before you tune. Collect a week of
pingMsfrom every secondary and chart the 99th percentile. A 200 ms p99 on a “1 ms LAN” is a network problem, not a MongoDB problem.db.serverStatus().repl.heartbeatIntervalMillis rs.printSecondaryReplicationInfo() -
Set
electionTimeoutMillisto roughly 5× p99 cross-member ping plus a buffer. For a same-region replica-set with p99 around 5 ms, the default 10s is generous. For a stretched cluster spanning two regions with 60 ms p99 and occasional 300 ms spikes, set it to 30000 or 60000.const cfg = rs.conf() cfg.settings.electionTimeoutMillis = 30000 rs.reconfig(cfg) -
Leave
heartbeatIntervalMillisat 2000 unless you have a reason. Lower values increase chatter without meaningfully improving detection — heartbeats are not the rate-limiting factor in election initiation. -
Tune
catchUpTimeoutMillisagainst your write SLA. Default is -1 (no upper bound; respectelectionTimeoutMillis). Set to a small positive value if your application cannot tolerate the post-election write outage and you accept the risk of losing a few oplog entries that the old primary had not yet propagated.const cfg = rs.conf() cfg.settings.catchUpTimeoutMillis = 5000 rs.reconfig(cfg) -
Configure
priorityandvotesto bias elections. A region-2 secondary you do not want to become primary should havepriority: 0(eligible to vote but not to win) orvotes: 0(read-only replica, ignored by quorum math). Stretched clusters typically runpriority: 1in the primary region andpriority: 0in the DR region. -
Set
writeConcernMajorityJournalDefault: trueif it is not already. This is what makes “majority” mean “durable on disk on a majority”. Without it, a flapping replica-set can lose committed writes.
Operational notes
- Heartbeat timeouts do not bound everything. The
serverSelectionTimeoutMSdriver setting controls how long client retries hunt for a primary — a short app timeout will surface failovers as application errors even when the cluster has recovered. - Arbiters skew elections without participating in writes. A PSA (primary-secondary-arbiter) topology survives a single member loss but cannot offer majority write concern when the secondary is down. Avoid arbiters for any cluster doing serious writes.
rs.reconfig()with aforce: trueflag can split-brain a cluster. Only use it when there is documented unanimous consent that the previous primary is gone for good.- Network partitions can cause double-elections. A member that briefly sees the primary go away, then reconnects, may have already started an election in another partition. Run with the latest driver — modern drivers handle “not primary” errors with retry-writes turned on.
- Election storm — repeated elections from priority churn. Set every secondary to the same priority (1) unless you specifically need a preferred-primary configuration.
Stack Harbor tunes replica-set heartbeat parameters for clients running MongoDB across regions, in colocated environments with noisy networks, and on cloud providers where heartbeats compete with other traffic for the same NIC. We instrument every member’s heartbeat round-trip and election counters so changes are evidence-based, not guesswork. The /en/solutions/multi-region-environments/ page describes how we operate stretched MongoDB topologies for customers who need a primary in one region and a hot standby in another.