Logical dump tools cannot produce a cluster-consistent backup of a multi-terabyte sharded MongoDB deployment; reliable recovery on AWS EC2 requires stopping the balancer and taking coordinated block-level EBS snapshots of dedicated hidden secondaries.

TL;DR

  • Problem: mongodump --oplog only guarantees point-in-time consistency within a single replica set, so multi-hour sharded dumps suffer WiredTiger cache eviction and cross-shard chunk skew.
  • Answer: Stop the balancer, optionally db.fsyncLock() dedicated hidden secondaries (priority: 0, hidden: true) on every shard and the CSRS, trigger AWS EBS snapshots, and unlock immediately.
  • Watch out: Keep data and journal on one EBS volume (or use single-instance ec2:CreateSnapshots), and remember that CreateSnapshots is atomic per EC2 instance—not across multiple shards.

Stop the balancer and snapshot dedicated hidden secondaries to keep primaries unlocked

Situation

Self-managed MongoDB sharded clusters on AWS EC2—composed of a 3-node Config Server Replica Set (CSRS), multiple shard replica sets on memory-optimized instances, and EBS gp3 storage volumes—must satisfy strict Recovery Point Objectives (RPO) and Recovery Time Objectives (RTO) for audit and disaster recovery compliance.

Many teams start with MongoDB Database Tools (mongodump and mongorestore) streaming BSON archives to Amazon S3. For small standalone databases or single replica sets under a few hundred gigabytes, mongodump is simple and portable. Once a sharded cluster grows into multiple terabytes, however, mongodump shifts from a convenience utility into a production hazard: full collection scans evict active working sets from the WiredTiger cache, restore times stretch past RTO limits, and cross-shard consistency breaks down completely.

The Problem

Logical backups and naive snapshot scripts fail on sharded EC2 clusters because of four physical and distributed constraints:

  1. No cross-shard --oplog synchronization: While mongodump --oplog captures oplog entries for a single replica set during a dump, it cannot freeze or align a global point-in-time timestamp across multiple independent shards and the CSRS. If Shard 1 finishes dumping hours before Shard 2 while the balancer migrates chunks or distributed transactions commit, restoring the shards via mongorestore yields duplicated or missing documents across chunk boundaries.
  2. WiredTiger cache eviction and restore RTO math: mongodump reads every document in every collection sequentially. On datasets larger than RAM, paging cold documents off EBS volumes evicts hot B-tree pages from the WiredTiger cache, causing read latency spikes on live traffic. Worse, mongorestore only dumps and restores index definitions, forcing mongod to rebuild every secondary B-tree index from scratch on restore. Exporting a 4 TB cluster at 150 MB/s takes ~7.4 hours, and rebuilding indexes across multi-terabyte collections stretches total RTO past 12–24 hours—whereas block-level EBS snapshots preserve pre-built .wt index B-trees and replay at most 60 seconds of WiredTigerLog.* journal records on boot.
  3. Single-volume vs. multi-volume journal atomicity: WiredTiger writes checkpoints every 60 seconds (checkpoint=(wait=60)) and appends intervening writes to journal/WiredTigerLog.*. If data and journal reside on the same EBS volume, a single EBS snapshot is crash-consistent. If they are split across separate EBS volumes without AWS CreateSnapshots (which supports up to 128 volumes on a single EC2 instance) or db.fsyncLock(), microsecond skew between independent CreateSnapshot calls can corrupt WiredTiger recovery on boot.
  4. S3 lazy-loading on EBS restore: Newly created EBS volumes from snapshots load blocks lazily from Amazon S3 on first read. Without AWS Fast Snapshot Restore (FSR)—which is governed by per-AZ FastSnapshotRestoreCreditsBucketSize volume-creation credits—or pre-warming via fio, initial database reads hit elevated storage latency.

Cross-shard skew, WiredTiger volume rules, and EBS lazy loading constrain EC2 backups

The core engineering question is: How do platform teams capture fast, point-in-time consistent backups across all shards and config servers on EC2 without locking shard primaries or stalling live application writes?

Options Considered

Four backup architectures are available for MongoDB on AWS. Each trades off operational complexity, primary-node impact, and cross-shard consistency:

Backup OptionWhat It Gets RightWhere It BreaksDecision
mongodump + mongorestorePortable BSON output; selective collection exportEvicts WiredTiger cache; slow restore; no cross-shard PITRReject for multi-TB clusters
Primary fsyncLock() + EBS SnapshotsEnforces exact write freeze before snapshotBlocks all app writes on primaries; AWS API throttling causes outageReject
Hidden Secondary EBS SnapshotsZero primary write lock; fast block-level restoreRequires 1 extra node per shard + CSRS; balancer pause during snapRecommended for self-managed EC2
MongoDB Ops Manager / Atlas BackupContinuous oplog tailing with per-second PITRRequires Enterprise license or migration to MongoDB AtlasUse if managed PITR is funded

Issuing db.fsyncLock() on shard primaries is a classic outage trigger: if the AWS EC2 snapshot API experiences transient throttling or network timeouts, the primary remains write-locked and client connection pools saturate. Moving the snapshot target to a dedicated hidden secondary (priority: 0, hidden: true) on each shard and the CSRS isolates backup locks from live traffic completely.

Compare mongodump, primary fsyncLock snapshots, hidden secondary snapshots, and managed backup

The Coordinated Snapshot Architecture

The production standard on self-managed EC2 combines a dedicated hidden backup tier with balancer quiescence and block-level EBS snapshots.

Coordinated backup architecture isolates hidden secondaries from production traffic

1. Dedicated Hidden Secondary Tier (priority: 0, hidden: true)

Add one non-voting, hidden member to the CSRS and to each shard replica set:

  • priority: 0: Prevents the backup node from ever winning an election and becoming primary.
  • hidden: true: Hides the node from client drivers (hello / isMaster responses), so it serves zero application read queries.
  • Equal hardware sizing and buildIndexes: true: Provision the hidden node with the same CPU, RAM, and EBS gp3 IOPS as voting members, and keep buildIndexes: true (the default). An undersized backup node accumulates replication lag, causing snapshots to miss RPO targets or fall off the oplog, while buildIndexes: false would force hours of index rebuilds after restore.

2. WiredTiger Crash Consistency, fsyncLock(), and Oplog Window Sizing

Between 60-second checkpoints (WiredTiger.turtle / WiredTiger.wt), WiredTiger appends mutations to journal/WiredTigerLog.*. When data and journal share one EBS volume, an EBS snapshot captures a crash-consistent image that replays the journal cleanly on startup. If you use LVM striping across multiple EBS volumes on Linux, ec2:CreateSnapshots (or xfs_freeze -f / lvcreate --snapshot) is required so the striped volume set freezes atomically.

In a sharded cluster, however, MongoDB’s documented filesystem-snapshot procedure requires stopping the balancer (sh.stopBalancer()) and briefly locking (db.fsyncLock()) one secondary on each shard and the CSRS if you need all shards frozen at a coordinated window without cross-shard transaction skew—or if data and journal live on separate volumes. Because the lock is applied strictly to the hidden secondaries, primaries and voting secondaries continue serving application writes uninterrupted.

Size the replica set oplog (storage.oplogSizeMB or oplogMinRetentionHours) with enough headroom to cover both the brief fsyncLock() window and your snapshot retention cadence if you plan to restore a snapshot and rejoin it to an existing replica set. If a snapshot is older than the primary’s oldest oplog entry, a restored node cannot catch up via oplog tailing and must perform a full initial sync from scratch, delaying recovery.

3. Auditing Oplog Alignment and Hidden Node Lag (mongosh)

Before taking snapshots, verify that hidden backup nodes are caught up to their primaries and inspect optime alignment across shards:

// Run on each replica set to verify hidden secondary replication lag
(function() {
  const status = rs.status();
  const primary = status.members.find(m => m.stateStr === "PRIMARY");
  status.members.filter(m => m.hidden || m.priority === 0).forEach(node => {
    const lag = ((primary.optimeDate.getTime() - node.optimeDate.getTime()) / 1000).toFixed(2);
    print(`${node.name} | Lag: ${lag}s | Health: ${node.health}`);
  });
})();

4. Coordinated Snapshot Orchestrator (pymongo + boto3)

The orchestrator stops the balancer, discovers hidden secondaries across the CSRS and all shards, locks them with fsyncLock, triggers ec2:CreateSnapshots per backup instance, and always unlocks and restarts the balancer in a finally block:

#!/usr/bin/env python3
import argparse, time, boto3
from pymongo import MongoClient

def run_backup(mongos_uri, cluster_tag, region, dry_run):
    client = MongoClient(mongos_uri, serverSelectionTimeoutMS=5000)
    ec2 = boto3.client("ec2", region_name=region)
    hidden_clients = []
    try:
        if not dry_run:
            client.admin.command("balancerStop")
            while client.admin.command("balancerStatus").get("inBalancerRound"):
                time.sleep(1)

        for shard in client.config.shards.find():
            sc = MongoClient(shard["host"], serverSelectionTimeoutMS=5000)
            for m in sc.admin.command("replSetGetStatus")["members"]:
                if m.get("hidden") or m.get("priority") == 0:
                    hc = MongoClient(m["name"], directConnection=True, serverSelectionTimeoutMS=5000)
                    if not dry_run:
                        hc.admin.command("fsync", lock=True)
                    hidden_clients.append(hc)
                    break

        res = ec2.describe_instances(Filters=[
            {"Name": "tag:Cluster", "Values": [cluster_tag]},
            {"Name": "tag:Role", "Values": ["backup-hidden-node"]}
        ])
        for r in res["Reservations"]:
            for inst in r["Instances"]:
                if not dry_run:
                    ec2.create_snapshots(InstanceSpecification={"InstanceId": inst["InstanceId"]})
                else:
                    print(f"[DRY-RUN] create_snapshots for {inst['InstanceId']}")
    finally:
        for hc in hidden_clients:
            try:
                hc.admin.command("fsyncUnlock")
            except Exception as exc:
                print(f"[ERROR] fsyncUnlock failed: {exc}")
        if not dry_run:
            client.admin.command("balancerStart")

if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--mongos-uri", required=True)
    p.add_argument("--cluster-tag", required=True)
    p.add_argument("--aws-region", default="us-east-1")
    p.add_argument("--dry-run", action="store_true")
    a = p.parse_args()
    run_backup(a.mongos_uri, a.cluster_tag, a.aws_region, a.dry_run)

How It Rolls Out

Execute backups and periodic restore drills in four gated phases so locks never linger and restore procedures stay verified.

Four gated phases from snapshot to verified restore

Phase 1: Quiesce the Cluster Balancer

Connect to mongos and run sh.stopBalancer() (or balancerStop).

  • Validation gate: Poll db.adminCommand({ balancerStatus: 1 }) until mode is "off" and inBalancerRound is false. This guarantees no moveChunk or moveRange migration is mid-flight.
  • Rollback: If any step fails before snapshotting, call sh.startBalancer().

Phase 2: Lock Hidden Secondaries and Trigger CreateSnapshots

Verify hidden-node replication lag is within RPO, issue db.fsyncLock() on the hidden secondary of the CSRS and each shard, then call ec2:CreateSnapshots for each hidden-node instance (plus CreateSnapshot if single-volume). Lock all hidden nodes before issuing any snapshot calls rather than locking and unlocking shards one by one; otherwise, writes or distributed transactions applied to Shard 2 after Shard 1’s snapshot cut will be captured unevenly across shards.

  • Validation gate: Confirm every snapshot ID returns in pending state from the EC2 API. Remember CreateSnapshots is asynchronous for S3 block upload; the point-in-time block mapping is captured as soon as the API returns.
  • Rollback: Execute db.fsyncUnlock() inside a finally block even if an EC2 API call raises an exception.

Phase 3: Unlock Hidden Nodes and Resume the Balancer

Immediately run db.fsyncUnlock() on all locked hidden secondaries and call sh.startBalancer().

  • Validation gate: Confirm db.currentOp() on each hidden node no longer shows fsyncLock, replication lag drains back to near zero, and sh.getBalancerState() is true.
  • Rollback: If a node fails to unlock via mongosh, connect directly to that mongod on localhost and issue db.adminCommand({ fsyncUnlock: 1 }).

Phase 4: Isolated VPC Restore Drill

Attach snapshots to test EC2 instances in an isolated VPC. If Fast Snapshot Restore (FSR) is enabled, verify FastSnapshotRestoreCreditsBucketSize >= 1 per AZ; otherwise pre-warm volumes with fio before starting mongod so lazy S3 block fetches do not stall initial database reads.

Restoring a sharded cluster into a new VPC requires rewriting cluster topology metadata because the restored snapshots still contain production hostnames and IPs:

  1. Start each restored CSRS and shard mongod in standalone mode (without --replSet, --configsvr, or --shardsvr) on a temporary port.
  2. Update the local local.system.replset document (or restart with --replSet and run rs.reconfig(..., { force: true })) so each replica set recognizes its new VPC hostnames.
  3. On the restored CSRS primary, update config.shards so each shard’s host string points to the new shard replica set seed list. On each restored shard primary, also update configsvrConnectionString inside admin.system.version (_id: "shardIdentity") to match the restored CSRS seed list (using recoverShardingState: false during standalone repair if needed) so shards do not attempt to contact production config servers, then restart mongos routers pointing to the restored CSRS.
  • Validation gate: mongod replays WiredTigerLog.* without WT_NOTFOUND errors, sh.status() reports all shards healthy, and application checksums pass.
  • Rollback: Terminate the isolated drill instances; production is untouched.

In Practice

Documented WiredTiger and AWS EBS mechanics explain why this architecture holds up under production load:

  • Why db.fsyncLock() on hidden secondaries is safe while primary locking is not: On a primary node, db.fsyncLock() blocks all client writes; any AWS API retry or timeout immediately stalls application connection pools. On a priority: 0, hidden: true secondary, db.fsyncLock() only pauses local oplog application for the few seconds needed to issue ec2:CreateSnapshots. Once unlocked, the secondary catches up from the primary’s oplog—provided the cluster’s oplog retention window comfortably exceeds the backup duration.
  • Why CreateSnapshots does not replace cross-shard orchestration: AWS ec2:CreateSnapshots guarantees crash-consistency across up to 128 EBS volumes attached to a single EC2 instance, solving the split data/journal volume problem on that host. It does not synchronize snapshots across separate EC2 instances (multiple shards and the CSRS), which is why stopping the balancer and locking hidden nodes remains mandatory for cross-shard consistency.
  • Why Fast Snapshot Restore credits matter for RTO: Even though EBS snapshots restore volumes instantly in the AWS control plane, blocks are fetched lazily from S3 on first access. If an FSR-enabled snapshot has fewer than 1 volume-creation credit remaining in its AZ bucket, AWS falls back to standard lazy loading, degrading initial query latency until blocks hydrate. When FSR is not enabled on a snapshot, running a sequential fio read pass across the restored block device before starting mongod forces S3 hydration ahead of live traffic, preventing cold-block latency spikes from hitting application queries.

Where It Breaks

ConditionBreaks HowDetectMitigate
Issuing fsyncLock() on shard primariesBlocks all client writes; EC2 API latency turns into a site-wide outageApp write timeouts; currentOp shows fsyncLock on primaryTarget only priority: 0, hidden: true secondaries
Snapshotting while balancer is activemoveChunk moves ranges mid-backup, duplicating or losing documents on restoreinBalancerRound: true during snapshot windowCall sh.stopBalancer() and wait for inBalancerRound: false
Splitting data and journal without CreateSnapshotsSeparate CreateSnapshot calls skew by milliseconds, causing WT_NOTFOUND on bootWiredTiger panic / journal recovery failure on restoreCo-locate data + journal on one EBS volume or use ec2:CreateSnapshots
Omitting CSRS from the snapshot batchRestored config.chunks metadata mismatches shard data ownershipStaleConfigException or missing data after restoreAlways lock and snapshot the CSRS hidden node in the same batch
Hidden secondary undersized on CPU/IOPSNode falls hours behind primary, violating RPO or dropping off the oplogrs.status() lag alerts on hidden memberMatch hidden secondary instance type and EBS gp3 IOPS to voting nodes
Restoring into a new VPC without rs.reconfig()mongod boots with old private IPs in rs.conf(), failing to form quorumReplica set stuck in STARTUP2 / RECOVERINGBoot standalone, rewrite rs.conf() and config.shards, then restart
Exhausted FSR credits on restoreVolume falls back to lazy S3 block loading, spiking read latencyCloudWatch FastSnapshotRestoreCreditsBucketSize < 1Monitor FSR credits or pre-warm restored EBS volumes with fio

Four critical failure modes in sharded EC2 backup and restore

April 2026 Update

Modern MongoDB releases (7.0 and 8.0) and AWS EBS capabilities reinforce the separation between logical exports and block-level recovery:

  1. Logical dumps remain unsuitable for large sharded DR: MongoDB documentation continues to advise against mongodump for large sharded clusters because it cannot coordinate a cluster-wide point-in-time snapshot across shards and saturates WiredTiger cache with full collection scans.
  2. Per-instance multi-volume crash consistency via ec2:CreateSnapshots: AWS CreateSnapshots handles up to 128 attached EBS volumes on a single EC2 instance atomically, eliminating manual dmsetup / LVM freeze scripts when data and journal reside on separate volumes on the same host—though cross-instance orchestration across shards and CSRS is still required.
  3. Managed continuous PITR in Atlas: Where self-managed EC2 snapshot orchestration and hidden-node overhead are undesirable, MongoDB Atlas Continuous Cloud Backups automate cross-shard snapshots and oplog tailing for point-in-time recovery.

Key Takeaways

  • Do not rely on mongodump for multi-terabyte sharded DR: It evicts WiredTiger working sets and cannot synchronize a point-in-time cut across shards.
  • Never run db.fsyncLock() on shard primaries: Lock only dedicated priority: 0, hidden: true secondaries so application writes never block on AWS API calls.
  • Co-locate data and journal on one EBS volume (or use ec2:CreateSnapshots): Prevent microsecond snapshot skew between WiredTiger.turtle checkpoints and WiredTigerLog.* journal files.
  • Stop the balancer and include the CSRS in every snapshot batch: Restored shards are unusable without matching config.chunks metadata.
  • Automate restore drills with rs.reconfig() and FSR/pre-warming: An untested snapshot is not a verified RTO.

What to Do Next

  • Problem: Verify whether your sharded EC2 backups rely on mongodump or fsyncLock() against primary nodes.
  • Solution: Provision one priority: 0, hidden: true secondary on the CSRS and each shard, and orchestrate balancerStop -> hidden fsyncLock -> ec2:CreateSnapshots -> fsyncUnlock -> balancerStart.
  • Proof: Run an isolated VPC restore drill from the latest snapshot batch, verify clean WiredTiger journal recovery, and confirm sh.status() health.
  • Action: Audit your backup cron/Lambda scripts this week to confirm CSRS inclusion, single-volume data+journal layout, and finally-block unlock safety.