MongoDB Backup and Restore on EC2: LVM/EBS Snapshots vs mongodump
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 --oplogonly 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 thatCreateSnapshotsis atomic per EC2 instance—not across multiple shards.
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:
- No cross-shard
--oplogsynchronization: Whilemongodump --oplogcaptures 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 viamongorestoreyields duplicated or missing documents across chunk boundaries. - WiredTiger cache eviction and restore RTO math:
mongodumpreads 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,mongorestoreonly dumps and restores index definitions, forcingmongodto 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.wtindex B-trees and replay at most 60 seconds ofWiredTigerLog.*journal records on boot. - Single-volume vs. multi-volume journal atomicity: WiredTiger writes checkpoints every 60 seconds (
checkpoint=(wait=60)) and appends intervening writes tojournal/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 AWSCreateSnapshots(which supports up to 128 volumes on a single EC2 instance) ordb.fsyncLock(), microsecond skew between independentCreateSnapshotcalls can corrupt WiredTiger recovery on boot. - 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
FastSnapshotRestoreCreditsBucketSizevolume-creation credits—or pre-warming viafio, initial database reads hit elevated storage latency.
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 Option | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|
mongodump + mongorestore | Portable BSON output; selective collection export | Evicts WiredTiger cache; slow restore; no cross-shard PITR | Reject for multi-TB clusters |
Primary fsyncLock() + EBS Snapshots | Enforces exact write freeze before snapshot | Blocks all app writes on primaries; AWS API throttling causes outage | Reject |
| Hidden Secondary EBS Snapshots | Zero primary write lock; fast block-level restore | Requires 1 extra node per shard + CSRS; balancer pause during snap | Recommended for self-managed EC2 |
| MongoDB Ops Manager / Atlas Backup | Continuous oplog tailing with per-second PITR | Requires Enterprise license or migration to MongoDB Atlas | Use 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.
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.
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/isMasterresponses), so it serves zero application read queries.- Equal hardware sizing and
buildIndexes: true: Provision the hidden node with the same CPU, RAM, and EBSgp3IOPS as voting members, and keepbuildIndexes: true(the default). An undersized backup node accumulates replication lag, causing snapshots to miss RPO targets or fall off the oplog, whilebuildIndexes: falsewould 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.
Phase 1: Quiesce the Cluster Balancer
Connect to mongos and run sh.stopBalancer() (or balancerStop).
- Validation gate: Poll
db.adminCommand({ balancerStatus: 1 })untilmodeis"off"andinBalancerRoundisfalse. This guarantees nomoveChunkormoveRangemigration 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
pendingstate from the EC2 API. RememberCreateSnapshotsis asynchronous for S3 block upload; the point-in-time block mapping is captured as soon as the API returns. - Rollback: Execute
db.fsyncUnlock()inside afinallyblock 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 showsfsyncLock, replication lag drains back to near zero, andsh.getBalancerState()istrue. - Rollback: If a node fails to unlock via
mongosh, connect directly to thatmongodon localhost and issuedb.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:
- Start each restored CSRS and shard
mongodin standalone mode (without--replSet,--configsvr, or--shardsvr) on a temporary port. - Update the local
local.system.replsetdocument (or restart with--replSetand runrs.reconfig(..., { force: true })) so each replica set recognizes its new VPC hostnames. - On the restored CSRS primary, update
config.shardsso each shard’shoststring points to the new shard replica set seed list. On each restored shard primary, also updateconfigsvrConnectionStringinsideadmin.system.version(_id: "shardIdentity") to match the restored CSRS seed list (usingrecoverShardingState: falseduring standalone repair if needed) so shards do not attempt to contact production config servers, then restartmongosrouters pointing to the restored CSRS.
- Validation gate:
mongodreplaysWiredTigerLog.*withoutWT_NOTFOUNDerrors,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 apriority: 0, hidden: truesecondary,db.fsyncLock()only pauses local oplog application for the few seconds needed to issueec2: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
CreateSnapshotsdoes not replace cross-shard orchestration: AWSec2:CreateSnapshotsguarantees 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
1volume-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 sequentialfioread pass across the restored block device before startingmongodforces S3 hydration ahead of live traffic, preventing cold-block latency spikes from hitting application queries.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Issuing fsyncLock() on shard primaries | Blocks all client writes; EC2 API latency turns into a site-wide outage | App write timeouts; currentOp shows fsyncLock on primary | Target only priority: 0, hidden: true secondaries |
| Snapshotting while balancer is active | moveChunk moves ranges mid-backup, duplicating or losing documents on restore | inBalancerRound: true during snapshot window | Call sh.stopBalancer() and wait for inBalancerRound: false |
Splitting data and journal without CreateSnapshots | Separate CreateSnapshot calls skew by milliseconds, causing WT_NOTFOUND on boot | WiredTiger panic / journal recovery failure on restore | Co-locate data + journal on one EBS volume or use ec2:CreateSnapshots |
| Omitting CSRS from the snapshot batch | Restored config.chunks metadata mismatches shard data ownership | StaleConfigException or missing data after restore | Always lock and snapshot the CSRS hidden node in the same batch |
| Hidden secondary undersized on CPU/IOPS | Node falls hours behind primary, violating RPO or dropping off the oplog | rs.status() lag alerts on hidden member | Match 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 quorum | Replica set stuck in STARTUP2 / RECOVERING | Boot standalone, rewrite rs.conf() and config.shards, then restart |
| Exhausted FSR credits on restore | Volume falls back to lazy S3 block loading, spiking read latency | CloudWatch FastSnapshotRestoreCreditsBucketSize < 1 | Monitor FSR credits or pre-warm restored EBS volumes with fio |
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:
- Logical dumps remain unsuitable for large sharded DR: MongoDB documentation continues to advise against
mongodumpfor large sharded clusters because it cannot coordinate a cluster-wide point-in-time snapshot across shards and saturates WiredTiger cache with full collection scans. - Per-instance multi-volume crash consistency via
ec2:CreateSnapshots: AWSCreateSnapshotshandles up to 128 attached EBS volumes on a single EC2 instance atomically, eliminating manualdmsetup/ 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. - 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
mongodumpfor 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 dedicatedpriority: 0, hidden: truesecondaries 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 betweenWiredTiger.turtlecheckpoints andWiredTigerLog.*journal files. - Stop the balancer and include the CSRS in every snapshot batch: Restored shards are unusable without matching
config.chunksmetadata. - 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
mongodumporfsyncLock()against primary nodes. - Solution: Provision one
priority: 0, hidden: truesecondary on the CSRS and each shard, and orchestratebalancerStop-> hiddenfsyncLock->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.