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 COLLSCAN queries hold WiredTiger read tickets (default 128 in 4.4–6.0) during physical EBS reads, queuing fast _id lookups and triggering upstream driver maxPoolSize socket storms that exhaust somaxconn and RAM.
  • Answer: Triage wiredTiger.concurrentTransactions and filtered db.currentOp() (secs_running >= 2, COLLSCAN), shed rogue queries with surgical killOp (or MongoDB 8.0 setQuerySettings reject: true) while excluding local.* and prepared transactions, and bound driver pools with waitQueueTimeoutMS.
  • Watch out: Never restart mongod or trigger an uncoordinated rs.stepDown() mid-cascade—restarting forces dirty-cache recovery, and failing over simply moves the same pathological query storm onto the newly elected primary.

Comparison of a concurrency collapse cascade against surgical load shedding and bounded driver pools

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.

Little's Law ticket exhaustion math, 200x200 driver socket amplification, and CPU context-switch thrashing

  1. Ticket Starvation Math: In MongoDB 4.4 through 6.0, WiredTiger defaults to 128 read tickets and 128 write 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—leaving 123 free. By contrast, if an unindexed COLLSCAN misses 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 the 128-ticket pool within a single second and forcing fast _id lookups into globalLock.currentQueue.readers. Notice that MongoDB’s logical lock manager (IS and IX database/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.
  2. Driver Connection Pool Amplification: Suppose 200 microservice pods each configure maxPoolSize: 200 without a tight waitQueueTimeoutMS. As query latency climbs, connection pools open new TCP sockets toward $200 \times 200 = 40,000$ connections. Each established TCP socket consumes kernel rmem/wmem buffers plus a mongod worker thread stack (on Linux, default pthread stack or mongod connection 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 to 128 on older Linux kernels before 4096 became standard on Linux 5.4+).
  3. 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 1 or mpstat, operators see high cs (context switches/sec) and elevated kernel sy CPU while iostat shows 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.

InterventionMechanismEffect on Tickets & CacheWhere It BreaksDecision
Restart mongodBounce the primary processDrops all connections and resets ticketsForces journal replay, wipes hot WiredTiger cache, and clients immediately reconnectRejected
Uncoordinated rs.stepDown()Force primary failover under loadAttempts to elect a fresh primaryStepdown lock queues behind blocked ops; apps replay the same COLLSCAN on the new primaryRejected
Surgical killOp + Pool BoundsTerminate matching COLLSCAN ops + throttle ingressFrees tickets in under 1s while preserving hot cacheRequires strict filters to avoid killing local.* replication or prepared 2PC txnsChosen

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.

Comparison of restarting mongod, uncoordinated stepDown, and surgical killOp with ingress throttling

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:

Inbound connection path from Linux somaxconn through epoll, logical locks, and WiredTiger's 128-ticket gate

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-running COLLSCAN queries periodically yield their locks and tickets so other operations can proceed, then re-acquire them. A high numYields count paired with secs_running >= 2 confirms the query is repeatedly re-entering the ticket queue and churning cache pages.
  • waitingForLock and lockStats: If waitingForLock is true and lockStats.timeAcquiringMicros is high on a specific collection in Exclusive (X) mode, you are dealing with a metadata/DDL lock (such as a drop or collMod) rather than pure WiredTiger ticket exhaustion.
  • writeConflicts: On write-heavy incidents, a high writeConflicts counter 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.

Four-phase triage flow: snapshot currentOp, shed COLLSCAN safely, bound driver pools, and deploy missing index

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 recurring killOp loops during an incident, MongoDB 8.0 introduces setQuerySettings with settings: { reject: true } (requiring $db in the query shape document) to block matching find, distinct, or aggregate shapes at planning time, inspectable via $querySettings and cleared via removeQuerySettings:
    db.adminCommand({
      setQuerySettings: { find: "orders", filter: { status: "PENDING" }, $db: "prod" },
      settings: { reject: true }
    });
    
    Because setQuerySettings persists 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 via explain("executionStats"), clear the rejection filter cleanly with db.adminCommand({ removeQuerySettings: ... }) rather than passing reject: false alone.
  • currentOp Wait Diagnostics: MongoDB’s currentOp command exposes waitingForLock, lockStats (acquireCount, acquireWaitCount, timeAcquiringMicros), writeConflicts, and numYields to isolate logical lock contention from storage-level yields. Combining these fields in a dry-run-first CLI script (pymongo admin.command("serverStatus") + admin.command("currentOp", ...) before killOp) gives on-call engineers a repeatable, auditable way to preview candidate opid values 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 $match stage that sort large result sets exceed MongoDB’s 100 MB in-memory sort ceiling. When allowDiskUse: true is enabled, mongod writes temporary sort files into _tmp inside dbPath, directly competing with WiredTiger checkpoint and journal writes on the same EBS volume. Routing heavy aggregations to dedicated analytics secondaries or adding covered $match + $sort compound 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

ConditionBreaks HowDetectMitigate
Killing prepared 2PC transactions or local.* opsAborts 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 > 128Admits 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 stormKernel 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 diskallowDiskUse: 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 waitQueueTimeoutMSBlocked 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.

Failure-path overlay showing unsafe killOp on prepared transactions, ticket inflation above 128, somaxconn SYN drops, and sort spills

Key Takeaways

  • Monitor concurrentTransactions and currentQueue, 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-second COLLSCAN queries per second require 150 concurrent tickets, saturating the 128-ticket pool and blocking sub-millisecond _id lookups.
  • Shed rogue queries surgically; never bounce or fail over mid-storm: Filtered killOp (or MongoDB 8.0 setQuerySettings reject: true) preserves hot cache and primary stability, whereas rs.stepDown() exports the same COLLSCAN storm to the new primary.
  • Exclude replication and prepared transactions from killOp: Always filter out ^local\., replCoord, and prepared lsid/txnNumber operations before issuing killOp.
  • Bound driver pools with maxPoolSize and waitQueueTimeoutMS: 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 COLLSCAN bursts exhaust WiredTiger’s 128 read tickets, queue fast queries in globalLock.currentQueue, and trigger upstream driver socket storms that consume host memory and saturate somaxconn.
  • Solution: Alert on concurrentTransactions.read.available < 20, isolate COLLSCAN ops via filtered db.currentOp(), shed them with killOp (or MongoDB 8.0 setQuerySettings reject: true with $db), and bound driver maxPoolSize + waitQueueTimeoutMS.
  • Proof: After shedding matching COLLSCAN ops in staging or production, confirm concurrentTransactions.read.available rebounds toward 128 and globalLock.currentQueue.readers drops to 0 within seconds without triggering a failover.
  • Action: Audit your microservice connection strings for waitQueueTimeoutMS, maxTimeMS, and maxPoolSize today, and add concurrentTransactions + currentQueue alerts to your MongoDB dashboard this week.