skip to content

How do you back up a self-managed sharded MongoDB cluster, and why can't you simply run mongodump --oplog through mongos?

level: seniorimportance: should knowfreq 38%

answer

  1. each shard keeps its own oplog
  2. chunks moving during the copy
  3. stop three things before you start
  4. lock through the router
  5. what restore must leave out

basics

~20 s

Stop the balancer, DDL and writes, take db.fsyncLock() through mongos, then dump through mongos or snapshot the config server and each shard, then unlock and restart the balancer. mongodump refuses --oplog on mongos, so only stopped writes hold the copy together.

solid answer

~50 s

The manual gives two self-managed procedures, and both start the same way. Pick a window with no migrations, resharding or schema changes, run `sh.stopBalancer()`, and lock the cluster with `db.fsyncLock()` through `mongos`, which needs 7.1, or 7.0.2, 6.0.11 or 5.0.22. Then run `mongodump` against `mongos`, or snapshot the config server primary and each shard's primary. Finally unlock and run `sh.startBalancer()`. `--oplog` can't help: each shard has its own oplog, `mongodump` refuses the flag on a `mongos`, and `mongorestore` refuses `--oplogReplay` there because sharded clusters don't support `applyOps`. Without it, only stopped writes hold the copy together, and the manual still calls the result not guaranteed. To restore a dump, pre-shard the target, run through `mongos` with `--nsExclude='config.*'`, and avoid `--drop`. Atlas, Cloud Manager and Ops Manager offer coordinated backups that keep cross-shard atomicity while accepting writes.

code

javascript · 9 lines
javascript
// mongosh, connected to mongos
sh.stopBalancer()
while (sh.isBalancerRunning().mode != "off") { sleep(1000) }

db.getSiblingDB("admin").fsyncLock()

// run mongodump from the OS shell now, then:
db.getSiblingDB("admin").fsyncUnlock()
sh.startBalancer()

go deeper

for a junior

Recall the pieces a sharded backup must cover: shards and config servers. Know that the balancer is stopped first and restarted last, with writes locked in between.

for a middle

Explain why chunk migrations corrupt a copy, and why one oplog can't describe a cluster. Walk the order: window, balancer, lock, copy, unlock, balancer.

for a senior

Say the tools refuse --oplog at mongos, name the restore traps of config and --drop, and state that the manual still calls the result not guaranteed. Plan for an election during the lock.

for a principal

Weigh the write stop against what the cluster can tolerate, because the backup's length is now an outage's length. That cost is the argument for a coordinated service or a different recovery design.

## Why a sharded cluster is a different problem A **sharded cluster** spreads collections across shards, each a replica set, with a **config server replica set (CSRS)** holding the metadata and `mongos` routers in front. A backup has to capture all of it as if at one moment, and three things work against that: - **No shared timeline.** Each shard has its own oplog, so no single oplog file can describe the cluster. - **Chunk migrations.** The balancer moves chunks between shards. If that happens during a backup, the manual warns the artifacts may be incomplete or hold duplicate data. - **Cross-shard operations.** Transactions and DDL touch several shards, and independent copies can catch them half done. ## Why `--oplog` doesn't help The replica set trick is unavailable, and the tools enforce that: - `mongodump` run against a `mongos` with `--oplog` stops with `can't use --oplog option when dumping from a mongos`. One line of the docs says the flag has no effect there, but the 100.20.1 source errors, and another docs line agrees with the source. - `mongorestore --oplogReplay` through a `mongos` stops with `cannot use --oplogReplay when restoring to a sharded cluster`, because it is built on `applyOps`, which sharded clusters don't support. `--preserveUUID` is refused for the same reason. - Running `--oplog` against each shard's replica set separately gives each dump its own end moment, and the manual directs replica sets in a sharded environment to the sharded procedure. So `mongodump` can back up a sharded cluster, but only by stopping the things that would change the data while it runs. ## The procedure with `mongodump` This is available where `fsync` can run on `mongos`: from MongoDB 7.1, and also 7.0.2, 6.0.11 and 5.0.22, so 8.0 and 9.0 behave alike. The user needs the `fsync` action, for example through `hostManager`. 1. **Find a window** when migrations, resharding and schema changes are unlikely. The steps give a consistent backup only if no such operation is in progress when you begin. 2. **Stop the balancer** with `sh.stopBalancer()` and wait until `sh.isBalancerRunning().mode` is `off`. 3. **Lock** with `db.getSiblingDB("admin").fsyncLock()` through `mongos`, then confirm with the `$currentOp` pipeline on `mongos` and on the CSRS primary. 4. **Dump** with `mongodump` connected to `mongos`. 5. **Unlock** with `db.fsyncUnlock()` until the lock count is zero, and confirm the same way. 6. **Restart the balancer** with `sh.startBalancer()`. The cluster takes no writes for the length of step 4. On a large cluster that's the real objection to this route, as the manual's table marks both self-managed routes as high impact and requiring a write lock. Reads through `mongos` default to each shard's primary. A non-primary read preference through `mongos` makes the tool warn that it may produce inconsistent duplicates or miss some documents. `mongodump` also fails if a resharding operation is running or starts. For an automated schedule, the manual also shows setting an `activeWindow` in `config.settings`, so that the balancer stays idle while the backup runs. ## The procedure with snapshots The shape is the same, with a different step 4. Lock on `mongos` and the CSRS primary, snapshot the CSRS primary, since one config server is enough, and snapshot the primary of each shard. Without stopped writes the snapshots only approximate a moment. To restore, the target must have the same number of shards and the same server version as the source. ## Restoring a dump | Target | Key steps | |---|---| | Sharded cluster | Stop the balancer, create and shard each collection with the same shard key, run `mongorestore` through `mongos` with `--nsExclude='config.*'`, restart the balancer | | Replica set or standalone | `mongorestore --nsExclude='config.*'` directly against `mongod` | Excluding `config` keeps the destination's own configuration, and a full restore through `mongos` with a `config` directory present is refused. Don't use `--drop` after pre-sharding, because the docs warn that it removes the sharding configuration. ## What the manual concludes For both self-managed routes the comparison table says consistency in a sharded cluster is **not guaranteed**, and that fsync locking reduces inconsistencies. The coordinated services it names, Atlas, Cloud Manager and Ops Manager, guarantee atomicity across shards while still accepting writes, and don't need the balancer stopped.

  • What happens if a shard's primary fails while the cluster is fsync-locked for a backup?
    The new primary doesn't inherit the lock and takes writes, so the backup may be inconsistent or unusable. The manual says to run `fsyncUnlock` until the count reaches zero, which releases the lock on all nodes, lock again and restart the backup. The old primary also needs an unlock when it returns.
  • What do Cloud Manager and Ops Manager add over the manual procedures?
    The manual says these coordinated processes, like Atlas, guarantee atomicity across shards while accepting writes, and you needn't disable the balancer for them. They read the oplog and offer point-in-time recovery. The manual also states their requirements: Cloud Manager backup needs Enterprise Server, and Ops Manager comes with Enterprise Advanced.

  • mongodump cannot connect to a sharded cluster at all.
  • Running mongodump --oplog through mongos yields a consistent cluster-wide copy.
  • Stopping the balancer alone makes a sharded backup consistent while writes continue.
  • Snapshotting all shards at about the same time gives an exact moment with writes running.
  • Restoring the config database through mongos is how the target learns its shard layout.
  • mongorestore --drop is safe on a target whose collections you have just pre-sharded.

Assumes MongoDB 9.0; fsync and fsyncUnlock through mongos need 7.1, or 7.0.2, 6.0.11 or 5.0.22, so 8.0 and 9.0 follow the same procedure.