Ch. 12 · MongoDB

MongoDB Replica Sets and Primary Elections

MongoDB Replica Sets and Primary Elections. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Replica sets replicate data and elect a primary after eligible failures. Applications must handle transient unavailability and changing topology.

Before you start

You should understand documents, collections and indexes. Sketch representative documents and the reads and writes they must support. MongoDB-specific examples assume a collection with the shown fields; deployment topology, permissions and existing indexes can affect the operational behavior being discussed.

The practical goal is to reason through this situation: A driver discovers a new primary after an election. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Use topology-aware clients

Supported drivers track changing replica-set roles.

Step 2: Bound transient waits

Set appropriate selection and operation deadlines.

Step 3: Handle uncertain writes

Failover does not prove every in-flight write either completed or disappeared.

Worked scenario

A driver discovers a new primary after an election.

The primary becomes unavailable during a request. An election selects another eligible primary, after which the driver can target it. The application may still see a transient error or uncertain operation result; unconditional replay of non-idempotent work can duplicate effects even when topology recovery succeeds.

Common mistake

Failover is not a promise that every in-flight operation completes transparently.

Verify the behavior

Exercise an election in a controlled replica set and inspect both errors and persisted outcomes.

Interview exercise

Prepare a write client.

Answer and reasoning

Use supported driver topology handling, appropriate timeouts and safe retry semantics for uncertain operations.

Continue learning

Compare the scenario with the MongoDB interview questions and test your understanding with the MongoDB MCQs. For terminology and implementation details, consult the reference material.

More in MongoDB

read ✓MongoDB · mid

MongoDB Bulk Writes

Batch inserts and updates with bulkWrite, choose ordered or unordered, and handle partial failures correctly.

~2 min readread →
read ✓MongoDB · mid

MongoDB Capped Collections

Use capped collections for fixed-size, insertion-ordered logs, and know why documents cannot grow.

~2 min readread →
read ✓MongoDB · hard

MongoDB Change Streams and Resume Tokens

React to inserts and updates with change streams, persist resume tokens, and handle invalidate and failover correctly.

~2 min readread →
esc