Automating MongoDB Patch and Major-Version Upgrades Across Large Replica Sets and Sharded Clusters
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
mongosor shards before the Config Server Replica Set (CSRS), skipping major versions, or bumpingfeatureCompatibilityVersion(FCV) immediately removes your binary rollback path.- Answer: Automate a strict state machine in Ansible:
sh.stopBalancer()-> CSRS -> Shards -> NLB-drainedmongos->sh.startBalancer()-> 7–14 day soak at FCVN->setFeatureCompatibilityVersion: N+1.- Watch out: Starting in MongoDB 7.0,
setFeatureCompatibilityVersionrequiresconfirm: truefor FCV downgrades/sensitive transitions, andmongodwill refuse to start if you jump two major versions at once (N -> N+2).
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:
- No skipped major versions (
N -> N+1only): MongoDBmongodbinaries cannot mount data directories created more than one major release prior. Installing MongoDB 7.0 directly over 5.0 data files aborts on startup withInvalidFeatureCompatibilityVersion. - Strict tier ordering: Newer
mongosrouters 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 transitionBalancer stop -> CSRS -> Shards -> mongos -> Balancer start. - 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. - 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 andNotWritablePrimaryerrors for applications lackingretryWrites=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).
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:
| Strategy | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|
| Manual CLI Runbook | Zero tooling setup | Easy to invert CSRS vs mongos order or skip lag checks before rs.stepDown() | Reject for multi-shard fleets |
| Declarative Ansible Rolling Upgrade | Enforces tier order, lag gates, NLB draining, and FCV soak with zero extra hardware | Requires N -> N+1 sequential runs for multi-version jumps | Recommended for self-managed EC2 |
Blue-Green Cluster + mongosync | Clean N+2 jump on fresh instances; instant DNS/NLB fallback | Doubles EC2/EBS spend during migration; complex cutover sync | Use only when jumping multiple versions |
| MongoDB Atlas Managed Upgrades | Control plane automates rolling sequence and pre-flight checks | Requires migrating off self-managed EC2 | Use 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.
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.
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
mongodruns versionN+1withfeatureCompatibilityVersionpinned toN, WiredTiger suppresses new major-version on-disk cell, index, and catalog formats so versionNbinaries 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" })(addingconfirm: truewhere 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+1binaries, auditmongod.conffor removed startup options (such asstorage.journal.enabled, which was removed in 7.0 because journaling is always on) and inspectdb.collection.getIndexes()for deprecated index versions that newermongodreleases reject on startup. Always stopmongodcleanly viaSIGTERM(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, sizeoplogMinRetentionHoursagainst 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 latestoptimebefore handing off leadership viareplSetStepUp, while barring the stepped-down node from re-election for 60 seconds. - Driver retryability: Application connection strings must enable
retryWrites=trueandw: "majority"on SDAM-compliant drivers (verified against the MongoDB Driver Compatibility Matrix before upgrading). When a primary steps down, the driver catchesNotWritablePrimary, refreshes topology viahelloheartbeats, 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.
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/SECONDARYhealth, and replication lag under 0.5 seconds. - Rollback: Stop
mongod, reinstall versionNpackages, and restart (safe because FCV is stillN).
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+1binaries, healthy quorum, and near-zero replication lag. - Rollback: Downgrade shard binaries back to
Nwhile FCV remainsN.
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 allmongosinstances onN+1andsh.isBalancerRunning()succeeds withoutconfig.lockserrors. - Rollback: Reinstall
Nonmongosif 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 }returnsN+1across CSRS and all shards. - Rollback: During soak (before FCV bump), binary downgrade to
Nis available; in 7.0/8.0, query-engine regressions from the Slot-Based Execution (SBE) engine can be mitigated online viadb.adminCommand({ setParameter: 1, internalQueryFrameworkControl: "forceClassicEngine" })without downgrading binaries. Once FCV is advanced, downgrading FCV back toNin 7.0+ requiresconfirm: trueand fails if anyN+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
moveChunkbetween 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, andmongosall reachN+1eliminates cross-version migration aborts andconfig.lockscontention. - Why
secondaryCatchUpPeriodSecsprevents 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 primaryoptimebefore transferring leadership, keeping election pauses brief enough forretryWrites=truedrivers to absorb. - Why
internalQueryFrameworkControlreduces 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$lookupplan regresses in memory or latency during the soak window, settinginternalQueryFrameworkControl: "forceClassicEngine"reverts query execution to the Classic Engine dynamically without touching binaries or FCV. - Why NLB target deregistration prevents
mongosconnection storms: Simply runningsystemctl restart mongoswhile 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 onemongosfrom 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 verifyingwiredTiger.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
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Skipping major versions (N -> N+2) | Newer mongod rejects older on-disk catalog/WiredTiger metadata | mongod aborts startup with InvalidFeatureCompatibilityVersion | Enforce linear N -> N+1 -> N+2 upgrades |
Upgrading mongos or shards before CSRS | Newer routers/shards send metadata commands legacy CSRS cannot parse | Metadata RPC errors and mongos routing stalls | Always upgrade CSRS 100% before shards and mongos |
| Bumping FCV before soaking | Irreversible catalog/index changes block clean binary downgrade | Post-upgrade driver or query bugs with no rollback path | Hold FCV at N for 7–14 days under full peak load |
| Stepping down primary with lagging secondaries | Election stalls or fails while secondaries catch up; client writes time out | maxSecondaryLag > 1s or NotWritablePrimary errors | Gate rs.stepDown(60, 30) on maxLag < 1.0s |
| Balancer active during mixed-version rolling upgrade | moveChunk fails across disparate shard versions, leaving orphaned docs | config.changelog moveChunk.from errors | Run sh.stopBalancer() in Phase 0 and verify idle |
| Oplog window shorter than node downtime | Restarted node falls off primary oplog and requires full initial sync | Node enters RECOVERING / OplogStartMissing | Verify rs.printReplicationInfo() headroom before maintenance |
Client drivers missing retryWrites=true or old SDK | Primary stepdown surfaces as unhandled socket/write exceptions | Application 5xx spikes during rs.stepDown() | Audit Driver Compatibility Matrix and mandate retryWrites=true |
April 2026 Update
MongoDB 7.0 and 8.0 introduced important operational safeguards for major upgrades and query-engine transitions:
- Mandatory
confirm: trueonsetFeatureCompatibilityVersion(MongoDB 7.0+): Starting in MongoDB 7.0, downgrading FCV or executing guarded FCV transitions requiresconfirm: true(db.adminCommand({ setFeatureCompatibilityVersion: "7.0", confirm: true })), preventing accidental irreversible metadata changes. - 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 withdb.adminCommand({ setParameter: 1, internalQueryFrameworkControl: "forceClassicEngine" })if a plan regression appears during soak. - 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) somongodcan read on-disk WiredTiger and catalog formats. - Enforce strict sharded tier order: Stop the balancer, upgrade CSRS first, upgrade shards second, drain and upgrade
mongoslast, then resume the balancer. - Decouple binary upgrades from FCV: Keep
featureCompatibilityVersionpinned atNfor a 7–14 day production soak before advancing FCV toN+1. - Gate every stepdown on replication lag and driver retries: Assert
maxSecondaryLag < 1.0sbeforers.stepDown(60, 30)and requireretryWrites=trueon SDAM-compliant drivers. - Use
internalQueryFrameworkControlfor 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 startstate machine in Ansible with automated lag and health gates. - Proof: Check
db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }),rs.printReplicationInfo(), and applicationretryWrites=truedriver versions in staging. - Action: Enforce a mandatory 7–14 day soak window at FCV
Non your next patch or major-version upgrade before issuingsetFeatureCompatibilityVersion.
Interactive tools for this topic