MongoDB keeps every document in a replica set: one primary takes writes, secondaries copy its oplog, and a majority of voting members elects a new primary when the old one disappears. A sharded cluster spreads collections across many replica sets by a shard key, behind mongos routers. Whether a write survives a failure depends on its write concern, and whether a cluster scales depends almost entirely on that shard key. This lesson follows one insert through a sharded cluster, then through an election, then through a shard key that sends every new document to the same shard, and covers running all of it with MongoDB's Kubernetes operators.
Difficulty: Advanced · Know this first: Lesson 34, Lesson 37, Lesson 38
This bar splits one insert, in milliseconds. It is a worked example, not a measurement. Journaling and replication are most of a healthy write; an election or a hot shard swamps everything else.
Choose voting members and how many are up, and set the oplog size and the write rate. The first two decide whether a primary can exist; the last two decide how long a secondary may be away.
majority = floor(members ÷ 2) + 1 · a primary exists while up ≥ majority · oplog window = oplog size ÷ write rate
Healthy, but a 20-hour window is short for a weekend outage
Three questions. No score is saved anywhere — this is just you against the material.
MongoDB operations grow in four levels: first replica sets and sharding, then running a replica set well, then sharded clusters and their keys, and finally operating MongoDB on Kubernetes as a platform.
At the basic level you know the two structures. A replica set is a primary and secondaries (three members is the usual minimum) that elect a new primary by majority. A sharded cluster is several replica sets (shards), config servers, and mongos routers, with each collection split into chunks by a shard key.
Terms: primary, secondary, arbiter, oplog, election, write concern, read concern, read preference, shard key, chunk, balancer.
Where it breaks: two-member replica sets cannot elect a primary when one is down; use three data-bearing members, and avoid arbiters with w:majority.
Try it: Basic
Why are replica sets usually three members, not two?
Now do it: Run mongo_ops.py in Go deeper and read the first four lines.
At the intermediate level you run a replica set.
w: "majority" for anything that matters; read concern "majority" where reads must survive failover.mongodump plus oplog for small sets), tested.explain() for slow ones.Try it: Intermediate
Which write concern makes a write survive the failover of the primary that accepted it?
Now do it: Check the write concern your application actually uses, including driver defaults and ORM settings.
At the advanced level you shard.
reshardCollection (5.0+) rewrites the collection online, at the cost of extra disk and load during the reshard.Try it: Advanced
Most queries filter by customerId, and inserts must spread evenly. Which shard key fits?
Now do it: For one collection you know, list its top three queries and check that a candidate shard key appears in all of them.
At the master level you run MongoDB for many teams, often on Kubernetes.
Trade-off: self-run MongoDB on Kubernetes keeps data and cost under your control and needs operator, storage, and backup discipline; a managed service such as Atlas removes most of that at a price.
Try it: Master
You upgrade a replica set on Kubernetes. In what order?
Now do it: Write the upgrade runbook for one replica set, including the checks between members.
Three calculations decide most MongoDB operations questions: whether a majority exists, how long a secondary may be away, and whether a shard key spreads writes. This script runs all three. Standard library only; python3 mongo_ops.py.
# mongo_ops.py - majorities, the oplog window, and why a shard key can create a hot shard
import hashlib
from collections import Counter
def majority(voting):
return voting // 2 + 1
for members, up in [(3, 3), (3, 2), (3, 1), (5, 3)]:
can = up >= majority(members)
print(f"{up} of {members} voting members up: {'a primary can be elected; w:majority writes succeed' if can else 'no primary; writes fail, reads only from secondaries'}")
# The oplog window: how long a secondary can be offline and still catch up without a full resync.
oplog_gb, writes_gb_per_hour = 50, 2.5
print(f"oplog {oplog_gb} GB at {writes_gb_per_hour} GB/h of writes -> window of about {oplog_gb / writes_gb_per_hour:.0f} hours")
# Shard key: 10,000 inserts over 4 shards, keyed by creation time (ranged) or by a hash of the id.
SHARDS, N = 4, 10_000
# ranged on a timestamp: every new key is larger than all existing ones, so it lands in the
# top chunk (MaxKey), which one shard owns until the balancer moves chunks after the fact
ranged = Counter({f"shard-{s}": 0 for s in range(SHARDS)})
for i in range(N):
ranged["shard-3"] += 1
hashed = Counter(f"shard-{int(hashlib.md5(str(i).encode()).hexdigest(), 16) % SHARDS}" for i in range(N))
print("ranged by time:", dict(sorted(ranged.items())))
print("hashed id: ", dict(sorted(hashed.items())))
$ python3 mongo_ops.py
3 of 3 voting members up: a primary can be elected; w:majority writes succeed
2 of 3 voting members up: a primary can be elected; w:majority writes succeed
1 of 3 voting members up: no primary; writes fail, reads only from secondaries
3 of 5 voting members up: a primary can be elected; w:majority writes succeed
oplog 50 GB at 2.5 GB/h of writes -> window of about 20 hours
ranged by time: {'shard-0': 0, 'shard-1': 0, 'shard-2': 0, 'shard-3': 10000}
hashed id: {'shard-0': 2518, 'shard-1': 2460, 'shard-2': 2474, 'shard-3': 2548}
Read it like this: one member of three is not a majority, so no primary; a 50 GB oplog at 2.5 GB an hour lets a secondary be away for about 20 hours; and a time-ranged key sends all 10,000 new documents to one shard where a hashed key spreads them almost evenly.
apiVersion: mongodbcommunity.mongodb.com/v1
kind: MongoDBCommunity
metadata:
name: orders-rs
namespace: data
spec:
members: 3
type: ReplicaSet
version: "8.0.4"
security:
authentication:
modes: ["SCRAM"]
users:
- name: orders-app
db: admin
passwordSecretRef:
name: orders-app-password
roles:
- name: readWrite
db: orders
scramCredentialsSecretName: orders-app-scram
additionalMongodConfig:
storage.wiredTiger.engineConfig.journalCompressor: zlib
Field names follow the MongoDB community operator's MongoDBCommunity resource and the manifest parses as YAML; the Enterprise operator's MongoDB resource adds sharded clusters and Ops Manager integration. Check the operator release you install for the MongoDB versions it supports, and apply it to a test cluster first.
// mongosh, connected to a member or mongos rs.status().members.map(m => [m.name, m.stateStr, m.optimeDate]) rs.printReplicationInfo() // oplog size and window rs.printSecondaryReplicationInfo() // lag per secondary db.orders.getShardDistribution() // data per shard sh.status() // chunks, balancer, shards
This is a composite of a failure pattern that keeps repeating; the numbers are illustrative. A logistics company sharded its events collection on a ranged timestamp.
The collection was resharded online on a compound key of a hashed device ID and the timestamp, after a dry run on a copy. Inserts spread across all shards, and the oplog was enlarged to hold three days. Shard key reviews became a required step before any new collection is sharded.
Design a MongoDB deployment on Kubernetes for an orders service that will grow from 200 GB to 4 TB in two years, with writes peaking at 15,000 a second, and must lose no acknowledged order.
What are the top queries, and which fields do they filter on? How fast does data grow, and when does one replica set stop being enough? What recovery point and time do you need? Will you run Ops Manager, use Atlas, or the community operator with your own backups?
Say documents of 2 KB, 15,000 inserts a second at peak, 3 zones, and a working set of 40 percent of the data.
Start with one three-member replica set across zones with w:majority and read concern majority for order reads, an oplog for three days, TLS and SCRAM users per app, and backups with point-in-time restore. Plan sharding at about 1 TB on { customerId: "hashed" }, which matches the main queries; three mongos and a config server replica set; alerts on elections, lag, oplog window, cache usage, and per-shard insert rate.
w:majority adds a replication round trip to each write and removes rollbacks. Sharding later avoids early complexity but needs a reshard if the first key is wrong; choosing the key carefully up front is cheaper. Running on Kubernetes keeps one platform; a managed service removes operator and backup work at a higher price.