Platform Engineering · Lesson 141

MongoDB in Production: Replica Sets, Write Concern, Shard Keys, and Kubernetes Operators

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 27, Lesson 30, Lesson 31

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: members, failures, and the oplog window

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

2majority
yesprimary possible
20 hoplog window

Healthy, but a 20-hour window is short for a weekend outage

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Replica sets and sharding

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.

Intermediate — Run a replica set well

At the intermediate level you run a replica set.

  • Three data-bearing members across zones; authentication (SCRAM or x.509) and TLS on.
  • w: "majority" for anything that matters; read concern "majority" where reads must survive failover.
  • An oplog sized for days, not hours; replication lag and elections on dashboards.
  • Backups with point-in-time restore (Ops Manager, Atlas, or mongodump plus oplog for small sets), tested.
  • Indexes for every common query; the profiler and 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.

Advanced — Sharded clusters and the shard key

At the advanced level you shard.

  • Choose the key: high cardinality, even write distribution, and present in the common queries; hashed for even inserts, ranged or compound for range queries.
  • Avoid: monotonically increasing ranged keys, low-cardinality keys (country, status), and keys the common queries do not include (every query becomes scatter-gather).
  • Operate: the balancer's window, jumbo chunks, config server health, and several mongos for availability.
  • Fix a bad key: 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.

Master — MongoDB on Kubernetes as a platform

At the master level you run MongoDB for many teams, often on Kubernetes.

  • Operators: MongoDB's Enterprise operator manages replica sets and sharded clusters with Ops Manager or Cloud Manager for backup and monitoring; the community operator manages replica sets without them; MongoDB has been consolidating them into MongoDB Controllers for Kubernetes.
  • Storage: fast persistent volumes per member, spread across zones with anti-affinity; volume expansion planned in advance.
  • Security: TLS and x.509 or SCRAM from secrets managed by the operator, network policies, and least-privilege roles per application.
  • Upgrades: one member at a time, secondaries first, then a step-down; feature compatibility version raised only after the upgrade is proven.
  • Capacity: working set in WiredTiger cache, oplog window, disk growth, and when to shard.

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.

Go deeper

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.

Majorities, the oplog window, and shard keys

# 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.

A replica set with the community operator

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.

Health checks from the shell

// 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

One time it broke

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.

Timeline

  • Month 1Four shards. Data is balanced; the balancer moves old chunks around nightly. Insert latency looks fine at low volume.
  • Month 4Peak season. Inserts climb to 20,000 a second, all on whichever shard owns the top chunk. Its primary saturates and replication lag grows to minutes.
  • Month 4A secondary on the hot shard falls out of the oplog window and needs a full resync, which adds more load to the same shard.

What changed after

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.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

Say documents of 2 KB, 15,000 inserts a second at peak, 3 zones, and a working set of 40 percent of the data.

Shape of the answer

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.

Trade-offs to name

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.

Saved on this device, in this browser.
Next in this series · Lesson 142
Redis & In-Memory Data

Lesson 25 gave you caching. This lesson gives you the tool that runs most caches in production. Redis is an in-memory data store that answers in about a millisecond, and it is also a queue, a leaderboard, a session store, and a…

Go to Lesson 142 →

Or browse the full course from the Lessons index.