MongoDB Performance Troubleshooting Playbook: Triage, WiredTiger Tickets, and Cascading Connection Pool Failures
When a MongoDB cluster degrades under load, host CPU utilization is a lagging illusion—WiredTiger admission ticket exhaustion and globalLock.currentQueue depths are the true leading indicators of a cascading connection-pool collapse.
TL;DR
- Problem: Unindexed
COLLSCANqueries hold WiredTiger read tickets (default128in 4.4–6.0) during physical EBS reads, queuing fast_idlookups and triggering upstream drivermaxPoolSizesocket storms that exhaustsomaxconnand RAM.- Answer: Triage
wiredTiger.concurrentTransactionsand filtereddb.currentOp()(secs_running >= 2,COLLSCAN), shed rogue queries with surgicalkillOp(or MongoDB 8.0setQuerySettingsreject: true) while excludinglocal.*and prepared transactions, and bound driver pools withwaitQueueTimeoutMS.- Watch out: Never restart
mongodor trigger an uncoordinatedrs.stepDown()mid-cascade—restarting forces dirty-cache recovery, and failing over simply moves the same pathological query storm onto the newly elected primary.
Situation
Production MongoDB replica sets on AWS EC2 (r6i or r7g instances with gp3 EBS volumes) routinely serve hundreds of containerized microservice pods. Under normal operation, indexed queries complete from WiredTiger’s cache in sub-millisecond time, ticket queues stay near zero, and connection pools remain steady.
When a release introduces an unindexed query filter or an ad-hoc analytical scan hits a cold collection, teams receive generalized latency alerts: microservices log socket timeouts, open TCP connections surge, and host CPU climbs toward 90%–100%. Under pressure, operators often bounce mongod or call rs.stepDown(). Both actions worsen the outage: restarting forces checkpoint and journal recovery on a cold cache, while failing over shifts the exact same unindexed traffic onto the newly elected primary. Worse still, an uncoordinated rs.stepDown() triggers a brief election blackout where all in-flight writes fail or retry simultaneously, compounding the driver reconnect storm.
The Problem
A concurrency collapse follows a deterministic Little’s Law cascade across the storage gate and driver pools:
$$L = \lambda \times W$$
Here $L$ is concurrent WiredTiger read tickets in use (wiredTiger.concurrentTransactions.read.out), $\lambda$ is the query arrival rate, and $W$ is the average ticket hold time.
- Ticket Starvation Math: In MongoDB 4.4 through 6.0, WiredTiger defaults to
128read tickets and128write tickets (wiredTigerConcurrentReadTransactions/WriteTransactions). Under cache-resident indexed traffic ($\lambda = 10,000$ queries/s, $W = 0.5$ ms), $L = 10,000 \times 0.0005 = 5$ tickets—leaving123free. By contrast, if an unindexedCOLLSCANmisses cache and reads cold pages from EBS such that $W = 10$ seconds, just $\lambda = 15$ queries/s demands $L = 15 \times 10 = 150$ tickets, saturating the128-ticket pool within a single second and forcing fast_idlookups intoglobalLock.currentQueue.readers. Notice that MongoDB’s logical lock manager (ISandIXdatabase/collection intent locks) is not the bottleneck here: intent locks allow concurrent access, so every query sails past the logical lock manager and piles up directly at WiredTiger’s semaphore gate. - Driver Connection Pool Amplification: Suppose 200 microservice pods each configure
maxPoolSize: 200without a tightwaitQueueTimeoutMS. As query latency climbs, connection pools open new TCP sockets toward $200 \times 200 = 40,000$ connections. Each established TCP socket consumes kernelrmem/wmembuffers plus amongodworker thread stack (on Linux, defaultpthreadstack ormongodconnection overhead adds ~1 MB per idle/active connection), consuming tens of gigabytes of non-cache RAM, starving WiredTiger and the OS page cache, and flooding the Linux TCP listen queue (net.core.somaxconn, which defaulted to128on older Linux kernels before4096became standard on Linux 5.4+). - CPU Context-Switch Illusion: Thousands of blocked threads waking up to contend for freed tickets burn CPU on kernel context switching and mutex contention while disk I/O throughput stays flat. On
vmstat 1ormpstat, operators see highcs(context switches/sec) and elevated kernelsyCPU whileiostatshows the EBS volume is nowhere near its provisioned IOPS ceiling—confirming that the cluster is scheduler-bound rather than compute-bound.
How should platform engineers triage an active ticket-exhaustion cascade, shed rogue COLLSCAN load safely without harming replication or transactions, and prevent drivers from amplifying the outage?
Options Considered
During an active ticket-exhaustion incident, operators generally weigh three interventions.
| Intervention | Mechanism | Effect on Tickets & Cache | Where It Breaks | Decision |
|---|---|---|---|---|
Restart mongod | Bounce the primary process | Drops all connections and resets tickets | Forces journal replay, wipes hot WiredTiger cache, and clients immediately reconnect | Rejected |
Uncoordinated rs.stepDown() | Force primary failover under load | Attempts to elect a fresh primary | Stepdown lock queues behind blocked ops; apps replay the same COLLSCAN on the new primary | Rejected |
Surgical killOp + Pool Bounds | Terminate matching COLLSCAN ops + throttle ingress | Frees tickets in under 1s while preserving hot cache | Requires strict filters to avoid killing local.* replication or prepared 2PC txns | Chosen |
Restarting mongod or forcing a failover treats a query-shape problem as a host problem. Surgical killOp (or setQuerySettings reject: true in MongoDB 8.0+) removes the blocking table scans in place while preserving the warm WiredTiger cache and primary leadership.
The Triage Architecture
Every incoming query traverses Linux socket queues, MongoDB’s logical intent locks (IS/IX), and WiredTiger’s admission ticket gate before touching B-tree pages:
When wiredTiger.concurrentTransactions.read.available approaches 0 and globalLock.currentQueue.readers climbs, run a targeted serverStatus() and currentOp() snapshot to separate ticket starvation from hardware limits:
// 1. Atomic concurrency snapshot
const ss = db.serverStatus();
printjson({
readAvail: ss.wiredTiger.concurrentTransactions.read.available,
queuedReaders: ss.globalLock.currentQueue.readers,
connCurrent: ss.connections.current
});
// 2. Isolate active non-local operations running >= 2s
db.currentOp({
active: true,
secs_running: { $gte: 2 },
op: { $in: ["query", "command", "getmore"] },
ns: { $not: /^local\./ }
}).inprog.map(op => ({
opid: op.opid, secs: op.secs_running, ns: op.ns,
plan: op.planSummary, waitingForLock: op.waitingForLock
}));
For post-incident forensics, MongoDB’s Full Time Diagnostic Data Capture (FTDC) files under /var/log/mongodb/diagnostic.data/metrics.* record 1-second snapshots of concurrentTransactions, currentQueue, and connections.current that can be extracted with bsondump and jq. Correlating wiredTiger.concurrentTransactions.read.out against connections.current and opcounters.query in FTDC proves the exact second the ticket pool saturated—usually minutes before application HTTP 504 alerts or CPU saturation alarms fired.
When inspecting db.currentOp() output during triage, pay close attention to three diagnostic fields beyond secs_running and planSummary:
numYields: Long-runningCOLLSCANqueries periodically yield their locks and tickets so other operations can proceed, then re-acquire them. A highnumYieldscount paired withsecs_running >= 2confirms the query is repeatedly re-entering the ticket queue and churning cache pages.waitingForLockandlockStats: IfwaitingForLockistrueandlockStats.timeAcquiringMicrosis high on a specific collection in Exclusive (X) mode, you are dealing with a metadata/DDL lock (such as adroporcollMod) rather than pure WiredTiger ticket exhaustion.writeConflicts: On write-heavy incidents, a highwriteConflictscounter indicates multiple threads mutating the exact same document concurrently under WiredTiger’s optimistic concurrency control, triggering internal retries that hold write tickets longer than normal.
How It Rolls Out
Execute load shedding and permanent remediation in four ordered phases with explicit safety guards.
Phase 1: Surgical Load Shedding via Filtered killOp
Target only active COLLSCAN operations on the offending collection that have exceeded a runtime threshold (such as 3 seconds), and never terminate internal replication (ns matching ^local\. or desc containing replCoord/rsBackgroundSync) or prepared multi-document transactions (lsid + txnNumber in prepared state):
db.currentOp({
active: true,
secs_running: { $gte: 3 },
ns: /\.orders$/,
planSummary: { $regex: /^COLLSCAN/ }
}).inprog.forEach(op => db.killOp(op.opid));
Validation gate: Re-check db.serverStatus().wiredTiger.concurrentTransactions.read.available within 1 second; available tickets should rebound toward 128 as currentQueue.readers drains.
Phase 2: Ingress Throttling, Server-Side maxTimeMS, and Driver Pool Bounds
If upstream pods immediately re-issue the same COLLSCAN queries, tickets will re-exhaust. Apply temporary rate limiting at the API gateway or service mesh for the offending route, and standardize driver pools with bounded maxPoolSize (for example, 50 instead of 500, sized to match actual concurrent worker threads per pod rather than worst-case burst guesses), maxIdleTimeMS: 60000, and waitQueueTimeoutMS: 2000 so blocked app threads fail fast instead of opening thousands of extra sockets. Note that maxPoolSize applies per MongoClient instance per pod—if a pod instantiates multiple MongoClient objects (one per module or tenant), total sockets multiply accordingly.
In addition to pool bounds, enforce maxTimeMS on non-critical read queries (or set defaultMaxTimeMS on read-only analytical workloads) so MongoDB automatically aborts any query whose server-side execution time exceeds its SLA budget. Without maxTimeMS, a client HTTP request timeout (for example, 5 seconds at the API gateway) drops the caller’s response while the orphaned COLLSCAN continues running inside mongod for minutes, holding WiredTiger tickets for a dead caller.
Phase 3: Prometheus Early-Warning Alerts
Alert on ticket depletion, queue depth, and connection influx rate before CPU alarms fire:
# Metric names depend on exporter version and casing; confirm them against your exporter's /metrics output
- alert: MongoWiredTigerReadTicketsNearExhaustion
expr: mongodb_ss_wiredtiger_concurrenttransactions_read_available < 20
for: 30s
labels: { severity: critical }
- alert: MongoQueuedOperationsElevated
expr: mongodb_ss_globallock_currentqueue_readers > 50
for: 1m
labels: { severity: critical }
Phase 4: Rolling or Off-Peak Index Deployment
Create the missing index to eliminate the COLLSCAN permanently. While MongoDB 4.4+ builds indexes in a hybrid non-blocking mode (using a brief lock at start and commit while sorting keys concurrently in the background), sorting keys on collections with tens or hundreds of millions of documents consumes substantial CPU, WiredTiger cache, and temporary disk I/O (maxIndexBuildMemoryUsageMegabytes, default 200 MB). Schedule large builds off-peak, or execute a rolling index build—taking one secondary out of the replica set into standalone mode, building the index locally, rejoining it, repeating on the second secondary, stepping down the primary, and building on the retired primary—to keep production write latency unaffected. Rollback: dropIndex() if an index causes write-amplification regressions.
In Practice
The triage sequence above aligns with documented MongoDB concurrency and query-control behavior across versions:
- Dynamic Admission Control (MongoDB 7.0+): Starting in MongoDB 7.0, MongoDB replaced the fixed 128-ticket ceiling with dynamic ticket allocation that modulates concurrent storage execution tickets (up to
128) based on workload contention and storage latency, reducing scheduler thrashing under saturation. - MongoDB 8.0 Operation Rejection (
setQuerySettings): Rather than running recurringkillOploops during an incident, MongoDB 8.0 introducessetQuerySettingswithsettings: { reject: true }(requiring$dbin the query shape document) to block matchingfind,distinct, oraggregateshapes at planning time, inspectable via$querySettingsand cleared viaremoveQuerySettings:
Becausedb.adminCommand({ setQuerySettings: { find: "orders", filter: { status: "PENDING" }, $db: "prod" }, settings: { reject: true } });setQuerySettingspersists cluster-wide across replica set members (and sharded routers), it survives primary stepdowns and prevents re-issued rogue queries from consuming a single WiredTiger ticket on any node. Once the missing index finishes building and is verified viaexplain("executionStats"), clear the rejection filter cleanly withdb.adminCommand({ removeQuerySettings: ... })rather than passingreject: falsealone. currentOpWait Diagnostics: MongoDB’scurrentOpcommand exposeswaitingForLock,lockStats(acquireCount,acquireWaitCount,timeAcquiringMicros),writeConflicts, andnumYieldsto isolate logical lock contention from storage-level yields. Combining these fields in a dry-run-first CLI script (pymongoadmin.command("serverStatus")+admin.command("currentOp", ...)beforekillOp) gives on-call engineers a repeatable, auditable way to preview candidateopidvalues and client IP addresses before terminating a single query.- Why Failover Fails Mid-Cascade: Calling
rs.stepDown()during ticket exhaustion is doubly harmful: first, the primary must acquire an exclusive replication lock to step down, which can itself queue behind active operations; second, once a secondary wins the election, every microservice connection pool reconnects simultaneously and immediately replays the exact same unindexed query shape against the new primary’s colder cache, recreating the 128-ticket collapse within seconds. - Aggregation Disk Spills (
allowDiskUse): Aggregation pipelines without a leading indexed$matchstage that sort large result sets exceed MongoDB’s 100 MB in-memory sort ceiling. WhenallowDiskUse: trueis enabled,mongodwrites temporary sort files into_tmpinsidedbPath, directly competing with WiredTiger checkpoint and journal writes on the same EBS volume. Routing heavy aggregations to dedicated analytics secondaries or adding covered$match+$sortcompound indexes prevents analytical spills from starving OLTP tickets.
I have not run controlled r6i.4xlarge ticket-saturation benchmarks personally; the Little’s Law cascade, currentOp filtering rules, and MongoDB 7.0/8.0 controls above reflect documented MongoDB storage engine and driver behavior.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Killing prepared 2PC transactions or local.* ops | Aborts replication sync or leaves prepared transactions holding locks until coordinator recovery. | Replication lag spike or prepared txns stuck in currentOp. | Exclude ^local\., replCoord, and prepared lsid/txnNumber ops in killOp filters. |
Inflating wiredTigerConcurrentReadTransactions > 128 | Admits too many threads into WiredTiger, increasing CPU context switching and L3 cache thrashing. | Higher CPU sy time with lower query throughput after setParameter. | Keep the 128 default (or 7.0+ dynamic admission) and eliminate the underlying COLLSCAN. |
Linux somaxconn = 128 during reconnect storm | Kernel silently drops incoming TCP SYN packets when the accept queue fills. | Client connection timeouts with no corresponding mongod log entries. | Ensure net.core.somaxconn >= 4096 and bound driver maxPoolSize + waitQueueTimeoutMS. |
Unindexed $sort spilling > 100 MB to disk | allowDiskUse: true writes temporary sort files to the EBS volume, competing with journal I/O. | High EBS write throughput paired with hasSortStage in slow query logs. | Add indexes covering $match + $sort or route heavy aggregations to secondaries. |
Driver pools without waitQueueTimeoutMS | Blocked worker threads trigger unbounded socket creation up to maxPoolSize across pods. | connections.current spikes alongside currentQueue.readers. | Set waitQueueTimeoutMS: 2000 and maxPoolSize: 50 in all microservice URIs. |
Key Takeaways
- Monitor
concurrentTransactionsandcurrentQueue, not just CPU: High CPU during a MongoDB outage is often kernel context-switch thrashing while threads wait on exhausted storage tickets. - Apply Little’s Law (
L = lambda x W) to spot ticket starvation: Even 15 slow 10-secondCOLLSCANqueries per second require 150 concurrent tickets, saturating the 128-ticket pool and blocking sub-millisecond_idlookups. - Shed rogue queries surgically; never bounce or fail over mid-storm: Filtered
killOp(or MongoDB 8.0setQuerySettingsreject: true) preserves hot cache and primary stability, whereasrs.stepDown()exports the sameCOLLSCANstorm to the new primary. - Exclude replication and prepared transactions from
killOp: Always filter out^local\.,replCoord, andpreparedlsid/txnNumberoperations before issuingkillOp. - Bound driver pools with
maxPoolSizeandwaitQueueTimeoutMS: Failing fast at 2 seconds in the application tier prevents 200 pods from opening tens of thousands of kernel socket buffers.
What to Do Next
- Problem: Unindexed
COLLSCANbursts exhaust WiredTiger’s128read tickets, queue fast queries inglobalLock.currentQueue, and trigger upstream driver socket storms that consume host memory and saturatesomaxconn. - Solution: Alert on
concurrentTransactions.read.available < 20, isolateCOLLSCANops via filtereddb.currentOp(), shed them withkillOp(or MongoDB 8.0setQuerySettingsreject: truewith$db), and bound drivermaxPoolSize+waitQueueTimeoutMS. - Proof: After shedding matching
COLLSCANops in staging or production, confirmconcurrentTransactions.read.availablerebounds toward128andglobalLock.currentQueue.readersdrops to0within seconds without triggering a failover. - Action: Audit your microservice connection strings for
waitQueueTimeoutMS,maxTimeMS, andmaxPoolSizetoday, and addconcurrentTransactions+currentQueuealerts to your MongoDB dashboard this week.