MongoDB Tutorial 0/120 lessons ~6 min read Lesson 83

    Replication Workflow

    Replication is how MongoDB delivers high availability and durability.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Replication is how MongoDB delivers high availability and durability. A replica set is a group of mongod processes that maintain the same data: one primary accepts writes, multiple secondaries stream them via the oplog, and an optional arbiter votes in elections without holding data.

    If the primary dies, the secondaries hold an election and a new primary is chosen in seconds — clients reconnect automatically. Replication is mandatory in production; running a single mongod is a disaster waiting for the next reboot.

    Learning objective: Apply Replication Workflow correctly in a TechLearningPRO MongoDB workload — with clear data-model choices, safe writes, and failure modes you can explain in review.

    Treat every example as production-shaped MongoDB: explicit projections, indexes that match the access path, and Atlas-safe defaults. Prefer mongosh / Node driver shapes used in SaaS backends.

    Purpose of this lesson

    Apply Replication Workflow correctly in a TechLearningPRO MongoDB workload — with clear data-model choices, safe writes, and failure modes you can explain in review.

    Understanding the topic

    How the replication workflow runs:

    • Oplog — capped collection on the primary recording every write as an idempotent operation.
    • Tail & apply — secondaries tail the oplog asynchronously and replay operations.
    • Heartbeat — members ping every 2s; missed heartbeats trigger an election.
    • Election — Raft-based consensus picks the most up-to-date member with majority votes.
    • Write concerns — w: "majority" waits for replication before acknowledging the client.
    • Read preferences — primary, secondary, nearest route reads where they make sense.

    Step-by-step explanation

    1. State when Replication Workflow is the right MongoDB tool versus an alternative.
    2. Map the diagram boxes to driver, mongod, WiredTiger, and your collection.
    3. Run the smallest correct mongosh / driver example against a TechLearningPRO learners collection.
    4. Name two failure modes (missing index, bad shard key, unbounded scan) and how you detect them.

    Syntax reference

    Topology of a typical 3-node replica set:

    bash
    ┌─────────────┐ writes
    clients ─┤ PRIMARY │◄──────────── app
    └─────┬───────┘
    │ oplog stream (async)
    ┌──────┴──────┐
    ▼ ▼
    ┌─────────┐ ┌─────────┐
    │SECONDARY│ │SECONDARY│ ← analytics reads
    └─────────┘ └─────────┘
    • heartbeats every 2 s
    • election quorum = majority (2 of 3)
    • failover typically completes in 10–12 s

    Informative example

    Initiating a self-hosted replica set:

    js
    // On each node start mongod with --replSet rs0
    // Connect to one and initiate:
    rs.initiate({
    _id: "rs0",
    members: [
    { _id: 0, host: "mongo-a:27017", priority: 2 },
    { _id: 1, host: "mongo-b:27017", priority: 1 },
    { _id: 2, host: "mongo-c:27017", priority: 1 }
    ]
    });
    rs.status(); // verify PRIMARY + 2 SECONDARY
    rs.conf(); // election priorities, hidden members, tags

    Real-world use

    Atlas always provisions a 3-node replica set behind every cluster — even the free tier. Production teams typically run 3 data-bearing nodes in 3 availability zones plus a hidden analytics node tagged for BI tools.

    Security implications

    MongoDB is a trust boundary. Drivers must not interpolate untrusted input into query operators.

    • Never build queries by concatenating user strings into operator objects.
    • Use least-privilege Atlas database users; apps should not have root.
    • Enable TLS and avoid exposing mongod on public networks.

    Best practices

    • Always use an odd number of voting members (3, 5, 7) to avoid split-brain.
    • Spread members across different availability zones — same-AZ replica sets fail together.
    • Default writes to w: "majority" and reads to readConcern: "majority" for durable consistency.
    • Avoid arbiters in 3-node sets — replace with a data-bearing node for stronger durability.

    Common mistakes

    • Long-running operations on the primary can block oplog application on secondaries — watch rs.printSecondaryReplicationInfo().
    • Letting an oplog window shrink below 24h — a slow secondary will need a full resync.
    • Reading from a secondary with default read concern — you may see stale data.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is Replication Workflow and when do you use it?+

    Answer

    Replica sets = automatic failover + durable writes + scalable reads.
    2IntermediateQuestionHow would you verify Replication Workflow is working in production?+

    Answer

    Oplog + heartbeats + Raft elections drive the entire workflow.
    3AdvancedQuestionWhat breaks if you misuse Replication Workflow?+

    Answer

    Always spread members across AZs and use w: "majority".

    Hands-on exercise

    Hands-on drill:

    • Implement the smallest correct example for Replication Workflow on a learners/orders-like collection.
    • Capture explain('executionStats') and confirm an index was used when expected.

    Summary

    Replication Workflow is a production MongoDB skill: model for your read path, prove it with explain(), and ship with indexes and least-privilege roles.

    Ready to mark this lesson complete?Track your journey across the entire course.