A major-version MongoDB upgrade is a non-reversible state-machine transition across three distributed tiers; inverting component order or advancing Feature Compatibility Version before soaking turns a rolling maintenance window into an unbootable cluster.

TL;DR

  • Problem: Upgrading mongos or shards before the Config Server Replica Set (CSRS), skipping major versions, or bumping featureCompatibilityVersion (FCV) immediately removes your binary rollback path.
  • Answer: Automate a strict state machine in Ansible: sh.stopBalancer() -> CSRS -> Shards -> NLB-drained mongos -> sh.startBalancer() -> 7–14 day soak at FCV N -> setFeatureCompatibilityVersion: N+1.
  • Watch out: Starting in MongoDB 7.0, setFeatureCompatibilityVersion requires confirm: true for FCV downgrades/sensitive transitions, and mongod will refuse to start if you jump two major versions at once (N -> N+2).

Sharded MongoDB upgrades follow a strict order and hold FCV behind a soak gate

Situation

Self-managed MongoDB clusters on AWS EC2—spanning multiple 3-node shard replica sets, a 3-node Config Server Replica Set (CSRS), and stateless mongos query routers behind Network Load Balancers (NLBs)—require regular patch releases for CVEs and annual major-version upgrades to stay within vendor support windows.

In a standalone replica set, a rolling upgrade is straightforward: upgrade secondaries one at a time, step down the primary with rs.stepDown(), and upgrade the former primary. In a sharded cluster, however, three interdependent tiers must transition without breaking metadata RPCs, dropping client writes, or triggering mid-migration chunk corruption.

The Problem

Manual upgrade runbooks fail on sharded clusters because four distributed invariants cannot be violated:

  1. No skipped major versions (N -> N+1 only): MongoDB mongod binaries cannot mount data directories created more than one major release prior. Installing MongoDB 7.0 directly over 5.0 data files aborts on startup with InvalidFeatureCompatibilityVersion.
  2. Strict tier ordering: Newer mongos routers and shard binaries are backward-compatible with older CSRS metadata only within the documented upgrade sequence, whereas legacy CSRS nodes cannot serve newer metadata commands from upgraded routers. Every sharded upgrade must transition Balancer stop -> CSRS -> Shards -> mongos -> Balancer start.
  3. FCV irreversibility boundary: Binary installation (N+1) is decoupled from internal catalog and WiredTiger format activation (featureCompatibilityVersion). Advancing FCV immediately after binary replacement mutates internal system collections (config.version, config.chunks, index formats) and blocks clean binary downgrade if a driver bug or query regression surfaces under load.
  4. Oplog retention and stepdown catch-up: If a secondary is down longer than the primary’s oplog window, it falls off the oplog and requires a full initial sync. Similarly, issuing rs.stepDown() while secondaries lag causes election stalls and NotWritablePrimary errors for applications lacking retryWrites=true. Even on a healthy 3-node replica set, restarting a second node before the first upgraded secondary finishes re-syncing leaves only one voting member online, breaking majority quorum (w: "majority" writes stall until two of three nodes are back).

Sequential N to N+1 upgrades, FCV boundaries, and oplog windows constrain every rollout

The core engineering question is: How do platform teams codify sharded MongoDB upgrades into an automated pipeline that enforces tier ordering, absorbs primary stepdowns without write errors, and preserves binary rollback during a production soak window?

Options Considered

Three primary patterns exist for upgrading self-managed MongoDB clusters, plus managed Atlas automation:

StrategyWhat It Gets RightWhere It BreaksDecision
Manual CLI RunbookZero tooling setupEasy to invert CSRS vs mongos order or skip lag checks before rs.stepDown()Reject for multi-shard fleets
Declarative Ansible Rolling UpgradeEnforces tier order, lag gates, NLB draining, and FCV soak with zero extra hardwareRequires N -> N+1 sequential runs for multi-version jumpsRecommended for self-managed EC2
Blue-Green Cluster + mongosyncClean N+2 jump on fresh instances; instant DNS/NLB fallbackDoubles EC2/EBS spend during migration; complex cutover syncUse only when jumping multiple versions
MongoDB Atlas Managed UpgradesControl plane automates rolling sequence and pre-flight checksRequires migrating off self-managed EC2Use if adopting Atlas

Manual shell execution fails under fatigue when managing dozens of nodes across shards. Blue-green cluster replacement doubles infrastructure cost and introduces dual-write or mongosync lag complexity. A declarative Ansible state machine gives zero-downtime rolling upgrades on existing EC2 instances while keeping FCV pinned at N until telemetry clears the soak gate.

Compare manual runbooks, Ansible rolling upgrades, blue-green logical migration, and Atlas

The Distributed Upgrade Architecture

A zero-downtime upgrade pipeline coordinates the Ansible control plane, AWS NLB target groups, SDAM-compliant client drivers, and WiredTiger’s FCV compatibility boundary.

Ansible orchestrator coordinates NLB draining, SDAM stepdowns, and FCV gating

1. Decoupling Binaries from FCV (and Patch vs. Major Releases)

Patch-version upgrades (for example, 6.0.4 to 6.0.15) do not modify featureCompatibilityVersion or on-disk WiredTiger formats, so rolling back a patch release only requires reinstalling the prior patch binary. Major-version upgrades (5.0 -> 6.0 or 6.0 -> 7.0) introduce on-disk format and catalog changes, which MongoDB gates behind featureCompatibilityVersion:

  • On-disk compatibility: While mongod runs version N+1 with featureCompatibilityVersion pinned to N, WiredTiger suppresses new major-version on-disk cell, index, and catalog formats so version N binaries can still mount the data directory if a rollback is required.
  • Post-soak activation: Only after a 7–14 day soak under peak production load do operators advance FCV via db.adminCommand({ setFeatureCompatibilityVersion: "N+1" }) (adding confirm: true where required in 7.0+ for FCV transitions/downgrades). Once FCV advances, binary downgrade is either unsupported or requires explicit FCV downgrade cleanup first.
  • Pre-flight config, clean shutdown, and oplog headroom: Before installing N+1 binaries, audit mongod.conf for removed startup options (such as storage.journal.enabled, which was removed in 7.0 because journaling is always on) and inspect db.collection.getIndexes() for deprecated index versions that newer mongod releases reject on startup. Always stop mongod cleanly via SIGTERM (systemctl stop mongod) so WiredTiger writes a clean final checkpoint; MongoDB forbids upgrading binaries over an uncleanly shut down data directory that still requires journal recovery. Finally, size oplogMinRetentionHours against total maintenance duration: if a cluster writes 40 GB/hour of oplog and a 3-node shard takes 30 minutes to roll (serial: 1), maintain at least 4–6 hours of oplog retention so a delayed node restart never triggers a full initial sync.

2. Graceful Stepdowns and Client SDAM (rs.stepDown(60, 30))

To avoid dropping inflight writes when upgrading a replica set primary:

  • Secondary catch-up grace period: rs.stepDown(60, 30) instructs the primary to quiesce new writes and wait up to 30 seconds for an eligible secondary to catch up to its latest optime before handing off leadership via replSetStepUp, while barring the stepped-down node from re-election for 60 seconds.
  • Driver retryability: Application connection strings must enable retryWrites=true and w: "majority" on SDAM-compliant drivers (verified against the MongoDB Driver Compatibility Matrix before upgrading). When a primary steps down, the driver catches NotWritablePrimary, refreshes topology via hello heartbeats, and retries the write transparently on the new primary.

3. Declarative Ansible Rolling Playbook

The Ansible playbook enforces FCV pre-flight validation, balancer quiescence, secondary lag gating (maxLag < 1.0s), serial: 1 rolling upgrades per replica set, and NLB draining for mongos routers:

- name: Phase 0 - Pre-Flight FCV and Balancer Quiescence
  hosts: mongos_routers[0]
  gather_facts: false
  tasks:
    - name: Assert Baseline FCV
      ansible.builtin.command: >
        mongosh --quiet --eval
        "db.adminCommand({getParameter: 1, featureCompatibilityVersion: 1}).featureCompatibilityVersion.version"
      register: current_fcv
      failed_when: current_fcv.stdout != target_baseline_fcv

    - name: Stop Balancer and Wait for Idle
      ansible.builtin.command: mongosh --quiet --eval "sh.stopBalancer()"
    - name: Verify Balancer Idle
      ansible.builtin.command: mongosh --quiet --eval "sh.isBalancerRunning()"
      register: bal
      until: bal.stdout == "false"
      retries: 30
      delay: 5

- name: Phase 1 - Rolling CSRS Upgrade (Then Repeat for Shards)
  hosts: mongo_config_servers
  serial: 1
  gather_facts: false
  tasks:
    - name: Check Node Role
      ansible.builtin.command: mongosh --quiet --eval "rs.status().members.find(m => m.self).stateStr"
      register: role

    - name: Graceful Stepdown on Primary
      block:
        - name: Gate on Secondary Lag < 1.0s
          ansible.builtin.command: >
            mongosh --quiet --eval "
              const s = rs.status(), p = s.members.find(m => m.stateStr === 'PRIMARY');
              print(Math.max(0, ...s.members.filter(m => m.stateStr === 'SECONDARY').map(x => (p.optimeDate - x.optimeDate)/1000)));
            "
          register: max_lag
          failed_when: (max_lag.stdout | float) > 1.0
        - name: Step Down Primary
          ansible.builtin.command: mongosh --quiet --eval "rs.stepDown(60, 30)"
      when: role.stdout == "PRIMARY"

    - name: Stop mongod, Install N+1 Binary, and Start
      ansible.builtin.systemd: { name: mongod, state: stopped }
    - name: Install Target Packages
      ansible.builtin.apt:
        name: ["mongodb-org-server={{ target_binary_version }}"]
        state: present
    - name: Start mongod
      ansible.builtin.systemd: { name: mongod, state: started }

For mongos routers in Phase 3, deregister each router from its AWS NLB target group (amazon.aws.elb_target_group_instance with state: deregister), pause for connection draining, upgrade mongodb-org-mongos, assert db.adminCommand({ ping: 1 }).ok == 1, and re-register before moving to the next router.

How It Rolls Out

Execute every major-version upgrade in four sequential execution phases followed by a mandatory soak gate before advancing FCV.

Five-phase rolling upgrade workflow with rollback gates

Phase 1: Pre-Flight Validation and CSRS Upgrade

Verify all client drivers meet the target version’s compatibility matrix, confirm rs.printReplicationInfo() oplog headroom exceeds the maintenance window, assert baseline FCV equals N, and stop the balancer (sh.stopBalancer()). Upgrade the 3-node CSRS serial: 1 (secondaries first, then rs.stepDown(60, 30) on the CSRS primary). Ensure systemd sets TimeoutStopSec=300 (or call db.adminCommand({ shutdown: 1 }) explicitly) so mongod never receives SIGKILL mid-checkpoint on busy nodes, which would force journal recovery and block N+1 startup.

  • Validation gate: All CSRS members report version: N+1, PRIMARY/SECONDARY health, and replication lag under 0.5 seconds.
  • Rollback: Stop mongod, reinstall version N packages, and restart (safe because FCV is still N).

Phase 2: Rolling Upgrade of Shard Replica Sets

Upgrade each shard replica set serial: 1 within the shard (shards may run concurrently with each other once CSRS is on N+1). Gate every primary stepdown on maxSecondaryLag < 1.0s.

  • Validation gate: Every shard reports N+1 binaries, healthy quorum, and near-zero replication lag.
  • Rollback: Downgrade shard binaries back to N while FCV remains N.

Phase 3: NLB-Drained mongos Upgrade and Balancer Resume

Deregister one mongos at a time from the AWS NLB target group, wait for inflight connections to drain, upgrade mongodb-org-mongos to N+1, verify ping: 1, and re-register. Only once every mongos router reports N+1 should you run sh.startBalancer(), ensuring no legacy router issues mixed-version chunk-migration metadata calls.

  • Validation gate: sh.status() shows all mongos instances on N+1 and sh.isBalancerRunning() succeeds without config.locks errors.
  • Rollback: Reinstall N on mongos if router issues appear.

Phase 4: Operational Soak Window and FCV Advancement

Run the cluster on N+1 binaries with FCV pinned at N for 7–14 days. Monitor query latencies, plan cache behavior, and driver error rates. Only after clearing the soak gate, run db.adminCommand({ setFeatureCompatibilityVersion: "N+1" }) (and on 7.0+ note confirm: true for FCV transitions/downgrades).

  • Validation gate: getParameter: { featureCompatibilityVersion: 1 } returns N+1 across CSRS and all shards.
  • Rollback: During soak (before FCV bump), binary downgrade to N is available; in 7.0/8.0, query-engine regressions from the Slot-Based Execution (SBE) engine can be mitigated online via db.adminCommand({ setParameter: 1, internalQueryFrameworkControl: "forceClassicEngine" }) without downgrading binaries. Once FCV is advanced, downgrading FCV back to N in 7.0+ requires confirm: true and fails if any N+1-only index or collection feature was created in the interim, making the pre-FCV soak window your cheapest rollback boundary.

In Practice

Documented MongoDB and WiredTiger behaviors explain why this state machine prevents the most common upgrade outages:

  • Why mixed-version balancing fails: When the balancer runs moveChunk between shards on different major versions, internal chunk-migration RPCs and metadata schemas can diverge across versions. Stopping the balancer in Phase 0 and keeping it off until CSRS, shards, and mongos all reach N+1 eliminates cross-version migration aborts and config.locks contention.
  • Why secondaryCatchUpPeriodSecs prevents write loss on stepdown: Without a catch-up grace period, an immediate stepdown can force a secondary to roll back un-replicated primary writes or delay election while it finishes applying oplog entries. rs.stepDown(60, 30) pauses new writes on the primary and waits for a voting secondary to reach the exact primary optime before transferring leadership, keeping election pauses brief enough for retryWrites=true drivers to absorb.
  • Why internalQueryFrameworkControl reduces post-upgrade rollback pressure in 7.0/8.0: Upgrading into MongoDB 7.0 or 8.0 shifts eligible queries onto the Slot-Based Execution (SBE) engine. If a specific aggregation or $lookup plan regresses in memory or latency during the soak window, setting internalQueryFrameworkControl: "forceClassicEngine" reverts query execution to the Classic Engine dynamically without touching binaries or FCV.
  • Why NLB target deregistration prevents mongos connection storms: Simply running systemctl restart mongos while an AWS Network Load Balancer is actively forwarding TCP flows drops inflight cursors and forces every application pod to tear down and rebuild its connection pool simultaneously. Deregistering one mongos from the NLB target group and waiting for its active client connections to drain shifts new requests to healthy peers before the daemon restarts, keeping router turnover transparent to application services.
  • Why secondary-first rolling order protects WiredTiger cache: Upgrading secondaries one at a time (serial: 1) means only one member of a replica set is cold-starting its WiredTiger cache at any moment. Waiting for replication lag to drop below 0.5 seconds—and verifying wiredTiger.cache["pages read into cache"] settles—before advancing to the next node ensures the replica set always maintains a full voting majority with warm caches before the primary steps down.

Where It Breaks

ConditionBreaks HowDetectMitigate
Skipping major versions (N -> N+2)Newer mongod rejects older on-disk catalog/WiredTiger metadatamongod aborts startup with InvalidFeatureCompatibilityVersionEnforce linear N -> N+1 -> N+2 upgrades
Upgrading mongos or shards before CSRSNewer routers/shards send metadata commands legacy CSRS cannot parseMetadata RPC errors and mongos routing stallsAlways upgrade CSRS 100% before shards and mongos
Bumping FCV before soakingIrreversible catalog/index changes block clean binary downgradePost-upgrade driver or query bugs with no rollback pathHold FCV at N for 7–14 days under full peak load
Stepping down primary with lagging secondariesElection stalls or fails while secondaries catch up; client writes time outmaxSecondaryLag > 1s or NotWritablePrimary errorsGate rs.stepDown(60, 30) on maxLag < 1.0s
Balancer active during mixed-version rolling upgrademoveChunk fails across disparate shard versions, leaving orphaned docsconfig.changelog moveChunk.from errorsRun sh.stopBalancer() in Phase 0 and verify idle
Oplog window shorter than node downtimeRestarted node falls off primary oplog and requires full initial syncNode enters RECOVERING / OplogStartMissingVerify rs.printReplicationInfo() headroom before maintenance
Client drivers missing retryWrites=true or old SDKPrimary stepdown surfaces as unhandled socket/write exceptionsApplication 5xx spikes during rs.stepDown()Audit Driver Compatibility Matrix and mandate retryWrites=true

Four upgrade failure modes that cause outages or unbootable nodes

April 2026 Update

MongoDB 7.0 and 8.0 introduced important operational safeguards for major upgrades and query-engine transitions:

  1. Mandatory confirm: true on setFeatureCompatibilityVersion (MongoDB 7.0+): Starting in MongoDB 7.0, downgrading FCV or executing guarded FCV transitions requires confirm: true (db.adminCommand({ setFeatureCompatibilityVersion: "7.0", confirm: true })), preventing accidental irreversible metadata changes.
  2. Dynamic SBE fallback via internalQueryFrameworkControl (MongoDB 7.0 / 8.0): MongoDB 8.0 enables the Slot-Based Execution (SBE) engine by default for eligible queries; operators can switch back to the Classic Engine dynamically with db.adminCommand({ setParameter: 1, internalQueryFrameworkControl: "forceClassicEngine" }) if a plan regression appears during soak.
  3. Managed rolling upgrades in Atlas: For teams on MongoDB Atlas, the control plane automates component sequencing, secondary lag checks, and FCV management, removing the need for self-maintained Ansible playbooks.

Key Takeaways

  • Never skip major versions: Always upgrade sequentially (N -> N+1 -> N+2) so mongod can read on-disk WiredTiger and catalog formats.
  • Enforce strict sharded tier order: Stop the balancer, upgrade CSRS first, upgrade shards second, drain and upgrade mongos last, then resume the balancer.
  • Decouple binary upgrades from FCV: Keep featureCompatibilityVersion pinned at N for a 7–14 day production soak before advancing FCV to N+1.
  • Gate every stepdown on replication lag and driver retries: Assert maxSecondaryLag < 1.0s before rs.stepDown(60, 30) and require retryWrites=true on SDAM-compliant drivers.
  • Use internalQueryFrameworkControl for 7.0/8.0 query regressions: Fall back to "forceClassicEngine" online instead of rushing an emergency downgrade.

What to Do Next

  • Problem: Audit your self-managed MongoDB upgrade runbooks for manual stepdowns, missing CSRS-first ordering, or immediate FCV bumps.
  • Solution: Codify the Balancer stop -> CSRS -> Shards -> NLB-drained mongos -> Balancer start state machine in Ansible with automated lag and health gates.
  • Proof: Check db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }), rs.printReplicationInfo(), and application retryWrites=true driver versions in staging.
  • Action: Enforce a mandatory 7–14 day soak window at FCV N on your next patch or major-version upgrade before issuing setFeatureCompatibilityVersion.