Elections, Sharding, Shard Keys and Backup

Article · 5:00

How elections work and what can go wrong, sharding architecture, the shard key decision, balancing, backup and restore, and Atlas.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Elections, in detail. Members exchange heartbeats every two seconds. If a secondary has not heard from the primary within electionTimeoutMillis (10 seconds by default), it calls an election. A candidate needs votes from a majority of voting members, and its oplog must be current enough. The practical consequences: an even number of voting members can deadlock, which is what arbiters exist to break - and an arbiter holds no data, so a three-member set of two data nodes and an arbiter survives a node loss for availability but cannot acknowledge w: "majority" with one node down. Prefer three data-bearing members.

priority: 0 makes a member ineligible to become primary - correct for an analytics node or one in a distant region. Hidden members are invisible to clients. Delayed members apply the oplog deliberately late, which is a human-error safety net: a delayed secondary four hours behind still holds the data a bad migration destroyed.

Sharding distributes a collection across shards by a shard key. The architecture: mongos routers that clients connect to, config servers holding the metadata, and shards that are each themselves a replica set. Documents are grouped into chunks by shard key range, and the balancer moves chunks between shards to keep them even.

The shard key is the most consequential and least reversible decision in MongoDB. It determines write distribution, which queries can be routed to one shard, and whether the balancer can do its job. A good key has high cardinality, low frequency (no single value dominating) and a non-monotonic pattern. The failures:

  • Monotonically increasing key (a timestamp, an ObjectId): every insert goes to the one chunk holding the maximum, so one shard takes all writes. Hashed sharding fixes the distribution and loses range queries.
  • Low cardinality (a country code with 20 values): chunks cannot be split beyond the distinct values, so you get jumbo chunks the balancer cannot move.
  • A key not in your queries: every query becomes a scatter-gather across all shards, which is slower than not sharding.

Modern MongoDB can reshard a collection, which is a real improvement over the old answer of "dump and reload", but it is an expensive online operation, not an undo button. Choose carefully the first time.

Backup and restore. mongodump and mongorestore are logical and fine for smaller datasets; they are not point-in-time without the oplog. Filesystem or volume snapshots are the standard for large deployments and require the journal to be on the same volume. Atlas provides continuous backup with point-in-time restore, which is one of the strongest arguments for it. Whatever you use, the restore is the thing you test, and the metric is a measured RTO, not an assumption.

Laboratory exercise 5 - lose a node, then shard badly.

On your three-node set, step down the primary under load and measure the election time and the error window. Then shut down two of three and show that the set has no primary and accepts no writes - and that it is not corrupt, just unavailable.

Add a delayed secondary four hours behind. Perform a destructive mistake on the primary (a bad updateMany), and recover the data from the delayed member.

Build a sharded cluster - mongos, config servers, two shards. Shard a collection deliberately badly, on a monotonically increasing key, drive inserts, and show one shard taking all writes. Then reshard on a good key and show the distribution change. Record chunk counts per shard before and after.

Take a mongodump, restore into a new deployment, and record a measured RPO and RTO. Then do the same with a filesystem snapshot if your environment allows.

Deliverable: the recovery runbook, measured election time and error window, the no-primary demonstration with its exact error, the delayed-member recovery, the shard distribution before and after with chunk counts, and the restore with measured RPO and RTO.

JS Example 1 108 lines
// ------------------------------------------------------------------
// Elections, and the member roles that matter.
// ------------------------------------------------------------------
rs.conf().members;
rs.conf().settings.electionTimeoutMillis;    // 10000 default

cfg = rs.conf();
cfg.members[2].priority = 0;       // never becomes primary: correct for
cfg.members[2].hidden = true;      // an analytics or distant node
cfg.members[2].votes = 0;
// A DELAYED member: a human-error safety net. Four hours behind, so a
// bad migration's damage has not reached it yet.
cfg.members[2].secondaryDelaySecs = 14400;
rs.reconfig(cfg);

// ARBITERS break a tie and HOLD NO DATA. A set of 2 data nodes + 1
// arbiter survives a node loss for AVAILABILITY and then cannot
// acknowledge w:"majority" - because a majority of 3 is 2, and only
// 1 data node remains. Prefer three data-bearing members.
rs.addArb("localhost:27020");     // know what this costs you

// Lose 2 of 3: NO PRIMARY, no writes. Not corrupt - unavailable.
//   MongoServerError: not primary and secondaryOk=false
//   -> Could not find host matching read preference { mode: "primary" }

// ------------------------------------------------------------------
// SHARDING. The architecture.
// ------------------------------------------------------------------
//   client -> mongos (router) -> shards (each a REPLICA SET)
//                   \-> config servers (the metadata, also a set)

sh.enableSharding("shop");

// ------------------------------------------------------------------
// THE SHARD KEY: the most consequential, least reversible decision.
// ------------------------------------------------------------------
// BAD 1 - monotonically increasing. Every insert goes to the chunk
// holding the maximum, so ONE SHARD takes ALL writes:
sh.shardCollection("shop.event_log", { createdAt: 1 });        // DO NOT

// BAD 2 - low cardinality. Chunks cannot split beyond the distinct
// values, so you get jumbo chunks the balancer cannot move:
sh.shardCollection("shop.customer", { country: 1 });           // DO NOT

// BAD 3 - not in your queries. Every query is a scatter-gather across
// every shard, which is SLOWER than not sharding at all.

// GOOD - high cardinality, low frequency, and present in the queries
// you actually run:
sh.shardCollection("shop.orders", { customerId: 1, placedAt: 1 });
//   A customer's orders live together -> a targeted single-shard
//   query for the dominant access pattern.

// HASHED - fixes distribution for a monotonic key, and LOSES range
// queries, which then scatter-gather:
sh.shardCollection("shop.event_log", { _id: "hashed" });

// Prove the distribution. This is the lab deliverable:
db.orders.getShardDistribution();
//   Shard shard0000: 4,998,112 docs (49.98%)  1.2GiB
//   Shard shard0001: 5,001,888 docs (50.02%)  1.2GiB   <- balanced
//
// Badly sharded looks like:
//   Shard shard0000: 9,998,221 docs (99.98%)  <- all writes here
//   Shard shard0001:     1,779 docs ( 0.02%)

// Targeted vs scatter-gather - read this in explain:
db.orders.find({customerId: cid}).explain().queryPlanner.winningPlan.shards.length;
//   1 = targeted. n = scatter-gather across every shard.

sh.status();
db.getSiblingDB("config").chunks.aggregate([
  {$group: {_id: "$shard", chunks: {$sum: 1}}}
]);

// Resharding exists, and is an expensive ONLINE operation, not an
// undo button. Choose carefully the first time:
db.adminCommand({ reshardCollection: "shop.orders",
                  key: {customerId: "hashed"} });
db.adminCommand({ balancerStatus: 1 });

// ------------------------------------------------------------------
// BACKUP and RESTORE. The RESTORE is the thing you test.
// ------------------------------------------------------------------
//   mongodump --uri="mongodb://.../?replicaSet=rs0" \
//       --oplog --archive=/backup/shop-$(date +%F).archive --gzip
//            ^^^^^^^ without --oplog a dump of a live system is NOT
//                    point-in-time consistent across collections
//
//   mongorestore --uri="mongodb://newhost/" \
//       --oplogReplay --archive=/backup/shop-2026-11-30.archive --gzip
//
//   One collection, into a new database, for a partial recovery:
//   mongorestore --nsFrom='shop.orders' --nsTo='shop_recovery.orders' ...
//
// Logical dumps are fine for smaller datasets. For large deployments
// the standard is a FILESYSTEM or VOLUME SNAPSHOT, which requires the
// journal on the same volume. Atlas gives continuous backup with
// point-in-time restore, which is one of the strongest arguments for
// it.
//
// Measure it. Both numbers, from an actual restore:
//   RPO = time since the last backup or oplog point
//   RTO = measured wall-clock time of the restore + verification

// Verify with assertions, not with "mongod started":
db.orders.countDocuments({});
db.orders.aggregate([{$group: {_id: null, total: {$sum: "$total"}}}]);

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.