Finding Slow MongoDB Queries: Profiler, Slow Logs, explain(), mongostat, and mongotop
Observability overhead must never exceed the capacity of the system being observed; enabling aggressive database profiling on a high-throughput cluster turns a diagnostic step into a self-inflicted write-ticket outage.
TL;DR
- Problem: Enabling
db.setProfilingLevel(2)or low-threshold unsampled profiling writes BSON documents intosystem.profileon the hot WiredTiger write path, draining concurrent write tickets and pushing dirty cache past the 20% eviction trigger.- Answer: Keep the profiler at level
0in steady state, emit slow operations exceedingslowmsas structured JSON tomongod.log, ship and group them byqueryHashexternally, triage live pressure withmongostatandmongotop, and runexplain("executionStats")only on hidden secondaries.- Watch out: Log shippers running without
systemdCPU and memory limits compete withmongodfor EBS read bandwidth, and blocking sorts above 100 MB abort unless covered by an ESR-ordered index orallowDiskUse: true.
Production Scope: MongoDB 5.0 / 6.0 / 7.0 / 8.0 on AWS EC2 + EBS
gp3
Situation
Operating high-throughput MongoDB replica sets on AWS EC2 memory-optimized instances (r6g.2xlarge, r7g.2xlarge) backed by EBS gp3 volumes requires continuous query plan verification to hold sub-10ms p99 latencies. Across microservice architectures, new product filters, dynamic API sort parameters, and ad-hoc analytical predicates continuously introduce unseen query shapes into production.
Most indexed point lookups complete in single-digit milliseconds, but a single unindexed collection scan (COLLSCAN) or blocking in-memory sort (SORT) can consume provisioned EBS gp3 IOPS and evict the active working set from the WiredTiger cache. During a latency regression, on-call engineers need a way to isolate the offending query shape immediately—without introducing diagnostic overhead that pushes an already stressed storage engine over its saturation cliff.
The Problem
The Observability Invalidation Hazard
When application latency spikes, the standard reflex is to turn on the MongoDB database profiler. Unlike filesystem logging, the profiler writes execution metadata directly into the WiredTiger catalog of the database being observed, creating four compounding constraints:
- The Profiler Level 2 Write Amplification: Executing
db.setProfilingLevel(2)instructsmongodto insert a full BSON execution document into thesystem.profilecapped collection for every read, write, and command. Consider the arithmetic on anr6g.2xlargeinstance backed by a baseline EBSgp3volume (3,000 IOPS, 125 MB/s throughput): at 10,000 reads per second, a read-only workload normally consumes zero WiredTiger write tickets. Enabling Level 2 converts those 10,000 reads into 10,000system.profileinserts per second. Even at ~1 KB per BSON profile record, that adds ~10 MB/s of raw document payload plus WiredTiger B-tree page dirtying, journal flushes, and capped-collection truncation overhead—quickly saturating the 3,000 IOPS baseline unless IOPS are explicitly provisioned higher. - WiredTiger Concurrent Ticket Exhaustion: In MongoDB 6.0 and earlier, WiredTiger enforces a static ceiling of
128concurrent write tickets (wiredTigerConcurrentWriteTransactions). Everysystem.profileinsert must acquire a write ticket, modify in-memory B-tree pages, and mark cache buffers dirty. When diagnostic inserts consume the 128-ticket pool, application writes queue behind profiler writes. (MongoDB 7.0 replaced the static 128 ceiling with dynamic concurrency control, but heavysystem.profilecontention still reduces available admission capacity under overload.) - The 20% Dirty Cache Trigger: WiredTiger background eviction threads work to keep dirty cache below
eviction_dirty_trigger(default 20%) and total cache usage beloweviction_target(80%) andeviction_trigger(95%). Whensystem.profilewrites saturate provisioned EBSgp3IOPS, background eviction falls behind, crossing the 20% dirty threshold and conscripting application client threads into synchronous page eviction. - Blocking Sort Memory Ceiling (100 MB): Queries without an index that satisfies both filter and sort predicates must run a blocking
SORTstage in RAM. Since MongoDB 4.4,internalQueryMaxBlockingSortMemoryUsageBytescaps this at 100 MB (104,857,600bytes; older 4.2 and earlier releases capped it at 32 MB). Crossing 100 MB abortsfindqueries outright, whileallowDiskUse: trueon aggregations spills temporary sort files to the same saturated EBS volume.
The core engineering question is: How can platform engineers capture, group, and explain pathological query shapes in high-throughput production clusters without consuming WiredTiger write tickets or saturating EBS IOPS?
Options Considered
| Option | Write Ticket Impact | Dirty Cache Impact | Visibility Scope | Decision |
|---|---|---|---|---|
| Profiler Level 2 | Consumes 1 write ticket per operation | High; forces continuous B-tree dirtying | 100% of reads, writes, and commands | Rejected: Indistinguishable from a self-inflicted write flood at high QPS |
Level 1 Unsampled (slowms too low) | Unbounded during latency storms | Spikes when baseline p95 exceeds slowms | All operations exceeding slowms | Rejected: Latency degradation turns slow-query logging into Level 2 |
Level 1 + sampleRate (e.g., 0.05) | Bounded to 5% of slow operations | Low when slowms >= 250 | Sampled slow queries and pipelines | Fallback: Acceptable only for short-lived debugging when logs lack detail |
JSON Slow Logs (mongod.log) + CLI | Zero WiredTiger tickets consumed | Zero WiredTiger dirty pages | All operations exceeding slowms | Chosen: Decouples capture from the storage engine via OS-buffered I/O |
Profiler Level 2 and unsampled low-threshold Level 1 were rejected because both couple diagnostic volume directly to storage-engine write capacity: the exact moment a cluster slows down is when slowms triggers most frequently, amplifying write pressure during an outage. Structured JSON slow logs (mongod.log) paired with mongostat and mongotop keep the storage engine write path untouched.
The Safe Query Observability Architecture: Decoupled Telemetry
A resilient observability architecture separates hot-path query execution from log shipping and offline execution plan analysis across three distinct planes.
flowchart TD
Client["Application Queries — High QPS"] --> Router["mongod Query Executor"]
Router --> Planner["Query Optimizer — Plan Cache via queryHash"]
Planner --> IndexDecision{"Usable Index Identified?"}
IndexDecision -->|Yes — IXSCAN| BTree["Traverse B-Tree Index Pages"]
IndexDecision -->|No — COLLSCAN| FullScan["Examine Every Document in Collection"]
BTree --> WTCache["WiredTiger Cache — Read Tickets"]
FullScan --> CacheChurn["Working Set Cache Eviction Spike"]
Router -->|Exceeds slowms| SlowLog["Structured JSON Log — mongod.log"]
SlowLog --> Vector["Log Shipper — Vector or Fluent Bit"]
Vector --> Aggregator["External Analytics — Group by queryHash"]
Aggregator --> HiddenSecondary["Hidden Secondary — explain executionStats"]
1. Structured JSON Slow Query Logging (mongod.log)
Since MongoDB 4.4, operations exceeding slowms (default 100 ms) are written to mongod.log as structured JSON using OS-buffered filesystem I/O. This path bypasses WiredTiger’s transaction ticketing, B-tree page locks, dirty-cache tracking, and checkpoint cycles. A log shipper such as Vector or Fluent Bit tails mongod.log and forwards parsed events externally so engineers can group slow queries by queryHash and planCacheKey.
2. Bounded Fallback: Level 1 Profiling with sampleRate
If an incident requires capturing fields not surfaced in standard slow logs, enable Level 1 profiling temporarily with an elevated slowms and an explicit sampleRate:
// Safely capture 5% of operations exceeding 250ms
db.setProfilingLevel(1, {
slowms: 250,
sampleRate: 0.05
});
Always revert to db.setProfilingLevel(0) immediately after capturing the sample.
3. Non-Invasive Live Triage: mongostat and mongotop
During an active incident, external administrative polling isolates storage bottlenecks without touching system.profile:
mongostat --discover 1: Reports per-second operation counters alongsidedirty%,used%, andqrw(queued read/write operations). Climbingqrwpaired withdirty%approaching20%confirms WiredTiger eviction backpressure;used%crossing95%indicates total cache exhaustion where client threads stall on eviction.mongotop 5: Reports cumulative read and write time per namespace over 5-second intervals, isolating which collection is absorbing disk I/O. Keep intervals at 5 seconds or higher to avoid administrative lock jitter.$currentOpfor In-Flight Stalls: Becausemongod.logemits slow-query records only after an operation completes, queries stuck behind a lock or running a multi-minuteCOLLSCANwill not appear in logs yet. Queryingdb.getSiblingDB("admin").aggregate([{ $currentOp: { allUsers: true } }, { $match: { active: true, secs_running: { $gt: 1 } } }])surfaces active offenders and lock-wait states (waitingForLock: true) in real time.
Deep Internals: Multi-Planner Trial and Blocking Sort Gate
Understanding why a query appears in mongod.log requires tracing how the MongoDB query optimizer compiles and caches execution plans.
- Plan Cache Lookup: On query arrival,
mongodhashes the query shape (filter, sort, projection, collation) toplanCacheKey. Cache hits reuse the winning plan directly. - Multi-Planner Trial Race: On a cache miss, the optimizer identifies candidate indexes and races them in parallel up to
internalQueryPlanEvaluationWorks(default10000work units). A work unit corresponds to an index key scan, document fetch, or filter evaluation. - Winner Selection and Eviction: The candidate that returns the required batch with the fewest work units wins and enters the plan cache. Cached plans remain active until an index is built or dropped, the node restarts, or the plan’s observed work ratio degrades significantly during execution.
- Blocking Sort Enforcement: If no index covers the
sortspecification,mongodinserts a blockingSORTstage. Crossing the 100 MBinternalQueryMaxBlockingSortMemoryUsageByteslimit abortsfindoperations:Executor error during find command :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting.
High-Resolution Telemetry: Decoding mongod.log and explain()
A MongoDB 5.0+ structured JSON slow query entry exposes exact examination counts and physical storage reads:
{
"t": { "$date": "2026-05-21T10:14:22.105+00:00" },
"s": "I",
"c": "COMMAND",
"id": 51803,
"ctx": "conn4281",
"msg": "Slow query",
"attr": {
"type": "command",
"ns": "production_commerce.orders",
"command": {
"find": "orders",
"filter": { "merchant_id": "M-8841", "status": "PENDING" },
"sort": { "created_at": -1 },
"limit": 50
},
"planSummary": "IXSCAN { merchant_id: 1 }",
"keysExamined": 120500,
"docsExamined": 120500,
"hasSortStage": true,
"nreturned": 50,
"storage": { "data": { "bytesRead": 42189000 } },
"durationMillis": 1420
}
}
Evaluate three forensic signals from this record:
- Examination-to-Return Ratio ($E/R$):
docsExamined / nreturned(120,500 / 50 = 2,410). Ratios near1.0indicate tight index selectivity; ratios in the thousands indicate wasted document fetches. hasSortStage: true: Confirms the chosen index ({ merchant_id: 1 }) did not satisfysort({ created_at: -1 }), forcing an in-memorySORT.storage.data.bytesRead: Measures physical bytes pulled from EBS into WiredTiger cache during execution.
To validate a fix without impacting the primary, run explain("executionStats") on a hidden secondary node:
db.orders.find({
"merchant_id": "M-8841",
"status": "PENDING"
}).sort({ "created_at": -1 }).limit(50).explain("executionStats");
Automated Log Extraction and Plan Validation
Use a Vector remap transform to compute er_ratio on the fly and alert only on high-duration or unselective query shapes:
[sources.mongo_logs]
type = "file"
include = ["/var/log/mongodb/mongod.log"]
read_from = "end"
[transforms.parse_mongo_json]
type = "remap"
inputs = ["mongo_logs"]
source = '''
. = parse_json!(.message)
if .msg != "Slow query" { abort }
.duration_ms = .attr.durationMillis
.namespace = .attr.ns
.docs_examined = .attr.docsExamined
.n_returned = .attr.nreturned
.er_ratio = if .n_returned > 0 { .docs_examined / .n_returned } else { .docs_examined }
'''
[transforms.filter_pathological]
type = "filter"
inputs = ["parse_mongo_json"]
condition = ".duration_ms >= 500 || .er_ratio >= 100"
Pair the log pipeline with a read-only Python validator targeting a hidden secondary to verify whether a candidate query shape exhibits a blocking SORT or high totalDocsExamined ratio:
#!/usr/bin/env python3
import argparse, json, sys
from pymongo import MongoClient
from pymongo.errors import PyMongoError
def analyze_query_plan(client, namespace, query_filter, sort_spec):
db_name, coll_name = namespace.split(".", 1)
coll = client[db_name][coll_name]
try:
cursor = coll.find(query_filter)
if sort_spec:
cursor = cursor.sort(list(sort_spec.items()))
explanation = cursor.explain("executionStats")
except PyMongoError as e:
sys.exit(f"Explain failed: {e}")
stats = explanation.get("executionStats", {})
n_ret = stats.get("nReturned", 0)
docs_ex = stats.get("totalDocsExamined", 0)
curr = explanation.get("queryPlanner", {}).get("winningPlan", {})
has_sort = False
while curr:
if curr.get("stage") == "SORT":
has_sort = True
break
curr = curr.get("inputStage")
ratio = docs_ex / n_ret if n_ret > 0 else docs_ex
print(f"ns={namespace} ms={stats.get('executionTimeMillis')} returned={n_ret} examined={docs_ex} E/R={ratio:.2f} sort={has_sort}")
How It Rolls Out
Deploying safe slow-query observability across an existing replica set follows four gated phases so each step can be verified and rolled back independently:
- Phase 1 — Verify Profiler Off & Baseline
slowms: Rundb.getProfilingStatus()across all members to confirmwas: 0. Setslowmsabove baseline p95 latency (minimum100ms) viadb.setProfilingLevel(0, { slowms: 100 })so slow queries emit only tomongod.log. Rollback: restore priorslowms. - Phase 2 — Deploy Constrained Log Shipper: Roll out Vector or Fluent Bit on one secondary first, pinned via
systemdCPUAffinityandMemoryMax, shippingid: 51803(Slow query) records. Verify zero rise inmongostatqrwor hostiowait. Rollback:systemctl stop vector. - Phase 3 — Aggregate by
queryHashand Validate Off-Primary: Rank top offenders bydurationMillis * countander_ratio. Reproduce candidate shapes withexplain("executionStats")on a hidden secondary node. - Phase 4 — Remediate via ESR Index or
setQuerySettings: Deploy compound indexes ordered by Equality, Sort, Range (ESR), or apply MongoDB 8.0setQuerySettings(indexHints) as an immediate cluster-wide guard before application code changes ship.
In Practice
Documented MongoDB query planner and WiredTiger storage engine behaviors explain both the common failure modes and their fixes:
- Equality, Sort, Range (ESR) Index Ordering: Per MongoDB’s documented indexing behavior, placing equality predicates before sort fields and range predicates last lets
IXSCANsatisfy both filtering and ordering directly from the B-tree. For a query filtering onmerchant_idandstatuswhile sorting bycreated_atwithlimit(50), an index on{ merchant_id: 1, created_at: -1 }forcesmongodto fetch every document matchingmerchant_idto evaluatestatus, inflatingtotalDocsExamined. Reordering to{ merchant_id: 1, status: 1, created_at: -1 }eliminates document fetches for non-matching statuses and removes the blockingSORTstage. - Query Shape Grouping (
queryHashvs.planCacheKey): MongoDB computesqueryHashfrom the structural shape of a query (filter fields, sort, projection) whileplanCacheKeyincorporates available indexes and collation. Groupingmongod.logslow queries byqueryHashaggregates identical query patterns across different literal filter values, revealing whether a latency spike stems from one unselective query shape or parameter skew poisoning a cached plan. - Profiler Level 2 Write-Path Coupling: Per MongoDB’s database profiler documentation,
system.profileis a capped collection backed by WiredTiger. Every profiled operation executes a storage-engine insert that acquires a write ticket and dirties cache pages. Under high concurrency, enabling Level 2 causes diagnostic writes to compete directly with application writes for cache eviction and EBS IOPS, whereasmongod.logwrites use OS-buffered I/O outside WiredTiger. - MongoDB 7.0+ and 8.0 Operational Controls: MongoDB 7.0 introduced dynamic WiredTiger concurrency ticket scaling to reduce static 128-ticket starvation during overload, and MongoDB 8.0 replaced node-local
planCacheSetFilterwith persistent, cluster-widesetQuerySettings:
db.adminCommand({
setQuerySettings: {
find: "orders",
filter: { "merchant_id": "M-8841", "status": "PENDING" },
sort: { "created_at": -1 },
$db: "production_commerce"
},
settings: {
indexHints: {
ns: { db: "production_commerce", coll: "orders" },
allowedIndexes: ["merchant_id_1_status_1_created_at_-1"]
}
}
});
Where It Breaks
| Diagnostic Approach | Physical Failure Mechanism | Architectural Consequence | Safe Mitigation Protocol |
|---|---|---|---|
| Profiler Level 2 in Production | Inserts 100% of ops into system.profile. | WiredTiger write amplification, ticket starvation, and EBS IOPS exhaustion. | Keep profiler at level 0; ship mongod.log JSON slow queries instead. |
Unsampled Level 1 with Low slowms | Setting slowms: 5 when p95 exceeds 8 ms. | Latency spikes trigger continuous system.profile writes like Level 2. | Set slowms >= 100 and pair with sampleRate <= 0.05 only if needed. |
explain("allPlansExecution") on Primary | Executes all candidate plans concurrently on live data. | Multiplies cache page reads and triggers working-set eviction on primary. | Run explain("executionStats") only on hidden secondaries or staging. |
Unindexed system.profile Queries | Filtering system.profile without natural order. | Scans entire capped collection, holding read tickets and stalling I/O. | Query with sort({ $natural: -1 }) or eliminate system.profile usage. |
| Blocking Sort Over 100 MB | Unindexed sort exceeds internalQueryMaxBlockingSortMemoryUsageBytes. | Query aborts at 100 MB, or allowDiskUse: true spills to EBS disk. | Order compound indexes using ESR so IXSCAN provides sort order. |
| Plan Cache Poisoning via Skew | Low-selectivity parameter wins the 10,000-work trial. | Suboptimal plan stays cached for all executions of that planCacheKey. | Clear via db.coll.getPlanCache().clearPlansByQuery() or pin via setQuerySettings. |
| Unconstrained Log Shipper | Vector or Fluent Bit runs without cgroup CPU/RAM caps. | Agent competes with mongod for CPU cycles and EBS read bandwidth. | Enforce systemd CPUAffinity and MemoryMax on all log shippers. |
Sub-Second mongotop Loops | Polling mongotop continuously at < 1s intervals. | Generates frequent metadata lock requests and lock queue jitter. | Keep mongotop polling intervals at 5 seconds or longer. |
Key Takeaways
- Never use
db.setProfilingLevel(2)in production:system.profilewrites share WiredTiger write tickets, dirty-cache budgets, and EBS IOPS with application traffic. - Default to
mongod.logstructured JSON shipping: Settinglevel: 0withslowms: 100emits slow queries via OS-buffered I/O at zero WiredTiger write-ticket cost. - Measure selectivity with $E/R$ (
docsExamined / nreturned): A high ratio alongsidehasSortStage: truesignals a missing ESR-ordered compound index rather than a hardware bottleneck. - Know the 100 MB blocking sort ceiling: MongoDB 4.4+ aborts unindexed blocking sorts above 100 MB (
internalQueryMaxBlockingSortMemoryUsageBytes) unlessallowDiskUse: truespills to disk. - Isolate
explain("executionStats")to hidden secondaries: Never runallPlansExecutionagainst a primary serving live traffic, and pin log shippers withsystemdresource limits.
What to Do Next
- Problem: Production clusters lack a low-overhead pipeline to capture and rank slow query shapes without risking WiredTiger cache exhaustion.
- Solution: Keep the database profiler at level
0, ship structured JSON slow logs frommongod.logexternally, and aggregate byqueryHash. - Proof: Run
db.getProfilingStatus()to verifywas: 0and checkdb.serverStatus().metrics.queryExecutorforscannedvsscannedObjectsratios. - Action: Set
slowms: 100, deploy asystemd-constrained Vector or Fluent Bit shipper on a secondary first, and audit the top three high-$E/R$ query shapes viaexplain("executionStats")on a hidden secondary this week.