MongoDB deep-dive · Part 10 of 11. Previous: Backup & point-in-time recovery. Next: Under the hood: WiredTiger storage.
Monitoring and security are both about surface area: monitoring tells you which part of the system is behaving unexpectedly, and security limits which parts of the system any given identity can reach. Neither is a one-time configuration — both require understanding the signals well enough to act on them and the access model well enough to tighten it.
The four signals to check when latency spikes
When a MongoDB node’s read or write latency suddenly increases, there are four places to look in order:
1. Current operations ($currentOp)
The first question is: what is the database doing right now?
# $currentOp aggregation stage — preferred since MongoDB 6.2
result = list(client.admin.aggregate([
{"$currentOp": {"allUsers": True, "idleSessions": False}},
{"$match": {"secs_running": {"$gt": 5}}}, # ops running > 5 seconds
{"$project": {"opid": 1, "op": 1, "ns": 1, "secs_running": 1,
"planSummary": 1, "client": 1}},
]))
for op in result:
print(op)
Look for long-running operations (secs_running > 5 is a good starting
threshold), operations doing COLLSCAN (planSummary: "COLLSCAN"), and
operations holding locks (waitingForLock: true). A single runaway query
can block everything behind it if it holds a collection lock.
To kill a problem operation:
client.admin.command("killOp", op=12345) # opid from $currentOp output
2. Slow query log / database profiler
The profiler records operations that exceed slowOpThresholdMs (default:
100ms) to the system.profile collection:
# Enable profiling for ops > 50ms on a specific database
db.set_profiling_level(1, slow_ms=50)
# Check recent slow queries
slow = list(db.system.profile.find().sort("ts", -1).limit(20))
for op in slow:
print(f"{op['op']:8} {op['millis']:5}ms {op.get('planSummary','?'):30} {op['ns']}")
The profiler output includes planSummary (which plan was used), millis
(total time), keysExamined, docsExamined, and nreturned — the same
metrics as explain("executionStats"), but for operations that already ran.
3. Replication lag
Replication lag is the delay between when a write is committed on the primary and when it’s replicated to a secondary. High lag means secondaries are serving stale data (Part 5) and that your recovery window for failover is wider than expected.
repl_status = client.admin.command("replSetGetStatus")
for member in repl_status["members"]:
if member["state"] == 2: # 2 = SECONDARY
# optime difference in seconds
primary_optime = max(
m["optimeDate"] for m in repl_status["members"]
if m["state"] == 1
)
lag = (primary_optime - member["optimeDate"]).total_seconds()
print(f"{member['name']:30} lag: {lag:.1f}s")
Alert when lag exceeds your oplog window divided by some safety factor (e.g., alert at 10% of the oplog window). If lag is rising, the common causes are: high write throughput exceeding replication capacity, a secondary with degraded I/O, or a secondary processing a long-running background operation.
4. WiredTiger cache eviction
WiredTiger (MongoDB’s storage engine since 3.2) maintains a cache of hot data in RAM. When the cache is full, it evicts pages to free space. Normal background eviction is fine. Application-thread eviction — where the threads serving your queries are also doing eviction work — kills latency.
server_status = client.admin.command("serverStatus")
wt_cache = server_status["wiredTiger"]["cache"]
cache_bytes_in_use = wt_cache["bytes currently in the cache"]
cache_bytes_max = wt_cache["maximum bytes configured"]
cache_pct = cache_bytes_in_use / cache_bytes_max * 100
eviction_server = wt_cache["eviction server evictions"]
eviction_app = wt_cache["application threads page eviction attempts"]
print(f"Cache utilisation: {cache_pct:.1f}%")
print(f"Server evictions: {eviction_server}")
print(f"App thread evictions: {eviction_app}")
If application threads page eviction attempts is non-zero and rising, your
working set exceeds your cache. Options: add RAM, reduce the working set
(better indexes so less data is loaded), or scale to more shards.
Security: RBAC for a Python service
MongoDB’s Role-Based Access Control (RBAC) system lets you define roles with exactly the privileges a service needs — nothing more.
Principle of least privilege
A Python service that only reads from one collection should not have read
access to the entire database, and absolutely should not have readWrite,
dbAdmin, or any cluster-level role. It should have exactly:
findaction on the specific collection it reads- Optionally,
listCollectionsif it needs to introspect the collection list
Creating a minimum-privilege role
// In the mongo shell or via db.command()
db.createRole({
role: "orderReader",
privileges: [
{
resource: {db: "mydb", collection: "orders"},
actions: ["find"]
}
],
roles: [] // inherit nothing
})
db.createUser({
user: "order_service",
pwd: "...",
roles: [
{role: "orderReader", db: "mydb"}
]
})
In PyMongo:
db.command("createRole", "orderReader",
privileges=[{
"resource": {"db": "mydb", "collection": "orders"},
"actions": ["find"],
}],
roles=[],
)
db.command("createUser", "order_service",
pwd="...",
roles=[{"role": "orderReader", "db": "mydb"}],
)
Transport encryption and auth mechanism
Always require TLS for client connections. Never deploy MongoDB without authentication enabled. For Python services, the recommended auth mechanism is SCRAM-SHA-256 (default since MongoDB 4.0):
client = MongoClient(
"mongodb://order_service:password@host1:27017/mydb"
"?authSource=mydb"
"&authMechanism=SCRAM-SHA-256"
"&tls=true"
"&tlsCAFile=/etc/ssl/mongo-ca.pem"
)
Audit logging
For compliance workloads, MongoDB Enterprise (and Atlas) support audit logging
— a record of every operation, including authentication events, privilege
changes, and read/write access. Configure it in mongod.conf:
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.json
filter: '{"atype": {"$in": ["authenticate", "createCollection", "dropCollection"]}}'
The filter field takes a query expression — log only the event types you
care about to keep the audit log manageable.
Putting the signals together: a runbook
When latency spikes:
$currentOp— is there a long-running operation? Kill it if appropriate.system.profile— have there been slow queries in the last 5 minutes? What’s theirplanSummary? ACOLLSCANpoints to a missing index.- Replication lag — is a secondary falling behind? Check its I/O and CPU.
- WiredTiger cache — is
application threads page evictionnon-zero? If yes, working set > cache. - Connections —
serverStatus().connections.currentnear the limit indicates connection pool exhaustion; check application connection pool config.
Each signal narrows the search. In practice, the cause is usually one of: a missing index triggering a COLLSCAN, a runaway aggregation, a secondary with disk pressure causing lag, or a cache working set that grew beyond RAM.
Security and observability are both about surface area. Minimum-privilege RBAC limits the blast radius of any single account compromise. The four-signal runbook limits the time you spend in the dark when something goes wrong. Both are built once and paid for every day you run in production.
Recall · check yourself
Before you go
Answer from memory first, then reveal. These cards also live in the review queue — come back in a few days.
-
R01 What replaced
db.currentOp()and why is it better?The
$currentOpaggregation stage (helper deprecated in 6.2) — you filter and project with the full pipeline (secs_running,ns) instead of post-processing. -
R02 Why is profiler level 2 dangerous on a write-heavy cluster?
It logs ALL operations to
system.profile— the profiling writes are themselves operations, creating a write feedback loop. Level 1 (slow ops only) gives the signal without the overhead. -
R03 What are the four signals worth alerting on?
Replication lag, connections, oplog window, and slow operations — they cover falling behind, resource exhaustion, shrinking recovery headroom, and degrading queries.
-
R04 What's the RBAC baseline for a monitoring agent?
Minimum privilege: the built-in
clusterMonitorrole — read-only visibility into cluster state, no data access, no admin writes.