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 into system.profile on the hot WiredTiger write path, draining concurrent write tickets and pushing dirty cache past the 20% eviction trigger.
  • Answer: Keep the profiler at level 0 in steady state, emit slow operations exceeding slowms as structured JSON to mongod.log, ship and group them by queryHash externally, triage live pressure with mongostat and mongotop, and run explain("executionStats") only on hidden secondaries.
  • Watch out: Log shippers running without systemd CPU and memory limits compete with mongod for EBS read bandwidth, and blocking sorts above 100 MB abort unless covered by an ESR-ordered index or allowDiskUse: true.

Decouple slow-query telemetry from WiredTiger writes

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:

  1. The Profiler Level 2 Write Amplification: Executing db.setProfilingLevel(2) instructs mongod to insert a full BSON execution document into the system.profile capped collection for every read, write, and command. Consider the arithmetic on an r6g.2xlarge instance backed by a baseline EBS gp3 volume (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,000 system.profile inserts 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.
  2. WiredTiger Concurrent Ticket Exhaustion: In MongoDB 6.0 and earlier, WiredTiger enforces a static ceiling of 128 concurrent write tickets (wiredTigerConcurrentWriteTransactions). Every system.profile insert 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 heavy system.profile contention still reduces available admission capacity under overload.)
  3. The 20% Dirty Cache Trigger: WiredTiger background eviction threads work to keep dirty cache below eviction_dirty_trigger (default 20%) and total cache usage below eviction_target (80%) and eviction_trigger (95%). When system.profile writes saturate provisioned EBS gp3 IOPS, background eviction falls behind, crossing the 20% dirty threshold and conscripting application client threads into synchronous page eviction.
  4. Blocking Sort Memory Ceiling (100 MB): Queries without an index that satisfies both filter and sort predicates must run a blocking SORT stage in RAM. Since MongoDB 4.4, internalQueryMaxBlockingSortMemoryUsageBytes caps this at 100 MB (104,857,600 bytes; older 4.2 and earlier releases capped it at 32 MB). Crossing 100 MB aborts find queries outright, while allowDiskUse: true on aggregations spills temporary sort files to the same saturated EBS volume.

Profiler Level 2 turns diagnostics into a write-ticket outage

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

OptionWrite Ticket ImpactDirty Cache ImpactVisibility ScopeDecision
Profiler Level 2Consumes 1 write ticket per operationHigh; forces continuous B-tree dirtying100% of reads, writes, and commandsRejected: Indistinguishable from a self-inflicted write flood at high QPS
Level 1 Unsampled (slowms too low)Unbounded during latency stormsSpikes when baseline p95 exceeds slowmsAll operations exceeding slowmsRejected: Latency degradation turns slow-query logging into Level 2
Level 1 + sampleRate (e.g., 0.05)Bounded to 5% of slow operationsLow when slowms >= 250Sampled slow queries and pipelinesFallback: Acceptable only for short-lived debugging when logs lack detail
JSON Slow Logs (mongod.log) + CLIZero WiredTiger tickets consumedZero WiredTiger dirty pagesAll operations exceeding slowmsChosen: 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.

Only filesystem slow logs avoid WiredTiger write contention

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.

Layered telemetry separates hot query path from analysis

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 alongside dirty%, used%, and qrw (queued read/write operations). Climbing qrw paired with dirty% approaching 20% confirms WiredTiger eviction backpressure; used% crossing 95% 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.
  • $currentOp for In-Flight Stalls: Because mongod.log emits slow-query records only after an operation completes, queries stuck behind a lock or running a multi-minute COLLSCAN will not appear in logs yet. Querying db.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.

Multi-planner trial execution and the 100 MB sort boundary

  1. Plan Cache Lookup: On query arrival, mongod hashes the query shape (filter, sort, projection, collation) to planCacheKey. Cache hits reuse the winning plan directly.
  2. Multi-Planner Trial Race: On a cache miss, the optimizer identifies candidate indexes and races them in parallel up to internalQueryPlanEvaluationWorks (default 10000 work units). A work unit corresponds to an index key scan, document fetch, or filter evaluation.
  3. 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.
  4. Blocking Sort Enforcement: If no index covers the sort specification, mongod inserts a blocking SORT stage. Crossing the 100 MB internalQueryMaxBlockingSortMemoryUsageBytes limit aborts find operations: 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 near 1.0 indicate tight index selectivity; ratios in the thousands indicate wasted document fetches.
  • hasSortStage: true: Confirms the chosen index ({ merchant_id: 1 }) did not satisfy sort({ created_at: -1 }), forcing an in-memory SORT.
  • 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:

  1. Phase 1 — Verify Profiler Off & Baseline slowms: Run db.getProfilingStatus() across all members to confirm was: 0. Set slowms above baseline p95 latency (minimum 100 ms) via db.setProfilingLevel(0, { slowms: 100 }) so slow queries emit only to mongod.log. Rollback: restore prior slowms.
  2. Phase 2 — Deploy Constrained Log Shipper: Roll out Vector or Fluent Bit on one secondary first, pinned via systemd CPUAffinity and MemoryMax, shipping id: 51803 (Slow query) records. Verify zero rise in mongostat qrw or host iowait. Rollback: systemctl stop vector.
  3. Phase 3 — Aggregate by queryHash and Validate Off-Primary: Rank top offenders by durationMillis * count and er_ratio. Reproduce candidate shapes with explain("executionStats") on a hidden secondary node.
  4. Phase 4 — Remediate via ESR Index or setQuerySettings: Deploy compound indexes ordered by Equality, Sort, Range (ESR), or apply MongoDB 8.0 setQuerySettings (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 IXSCAN satisfy both filtering and ordering directly from the B-tree. For a query filtering on merchant_id and status while sorting by created_at with limit(50), an index on { merchant_id: 1, created_at: -1 } forces mongod to fetch every document matching merchant_id to evaluate status, inflating totalDocsExamined. Reordering to { merchant_id: 1, status: 1, created_at: -1 } eliminates document fetches for non-matching statuses and removes the blocking SORT stage.
  • Query Shape Grouping (queryHash vs. planCacheKey): MongoDB computes queryHash from the structural shape of a query (filter fields, sort, projection) while planCacheKey incorporates available indexes and collation. Grouping mongod.log slow queries by queryHash aggregates 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.profile is 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, whereas mongod.log writes 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 planCacheSetFilter with persistent, cluster-wide setQuerySettings:
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

Four diagnostic failure paths that degrade healthy clusters

Diagnostic ApproachPhysical Failure MechanismArchitectural ConsequenceSafe Mitigation Protocol
Profiler Level 2 in ProductionInserts 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 slowmsSetting 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 PrimaryExecutes 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 QueriesFiltering 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 MBUnindexed 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 SkewLow-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 ShipperVector 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 LoopsPolling 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.profile writes share WiredTiger write tickets, dirty-cache budgets, and EBS IOPS with application traffic.
  • Default to mongod.log structured JSON shipping: Setting level: 0 with slowms: 100 emits slow queries via OS-buffered I/O at zero WiredTiger write-ticket cost.
  • Measure selectivity with $E/R$ (docsExamined / nreturned): A high ratio alongside hasSortStage: true signals 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) unless allowDiskUse: true spills to disk.
  • Isolate explain("executionStats") to hidden secondaries: Never run allPlansExecution against a primary serving live traffic, and pin log shippers with systemd resource 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 from mongod.log externally, and aggregate by queryHash.
  • Proof: Run db.getProfilingStatus() to verify was: 0 and check db.serverStatus().metrics.queryExecutor for scanned vs scannedObjects ratios.
  • Action: Set slowms: 100, deploy a systemd-constrained Vector or Fluent Bit shipper on a secondary first, and audit the top three high-$E/R$ query shapes via explain("executionStats") on a hidden secondary this week.