Skip to content
LESSON 40 / 50Advancedaggregation

The 100MB RAM Stage Limit & allowDiskUse: true

Aggregation pipeline stages are constrained by a strict 100MB in-memory RAM limit; learn how to diagnose memory spillover and utilize allowDiskUse: true safely.

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

1. Formal Definition & Architecture Intent

MongoDB enforces a 100MB RAM ceiling per stage in an aggregation pipeline to prevent memory starvation and OOM crashes. If a blocking stage (such as $group, unindexed $sort, or $bucket) accumulates more than 100MB of data in RAM, MongoDB aborts the query with an error unless { allowDiskUse: true } is explicitly enabled.

2. Explain Like I'm 5 (Mental Model)

Each station on the assembly line is only given a 100MB workbench. If parts pile up past 100MB, the worker throws their hands up and stops the factory. Setting allowDiskUse gives the worker permission to stack overflow parts into temporary storage boxes on the warehouse floor.

3. Real-World Architecture Example

Sorting 5,000,000 unindexed audit log records in an aggregation pipeline.

Sample BSON Documents:
Collection: db.query_error
{
  "code": 16819,
  "errmsg": "Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting."
}

Unindexed sort breached 100MB (104,857,600 bytes), crashing the query.

4. MQL Implementation Steps

Step 1: Enable disk spillover in aggregation
db.audit_logs.aggregate(
  [
    { $match: { severity: "CRITICAL" } },
    { $sort: { timestamp: -1 } } // Unindexed sort
  ],
  { allowDiskUse: true } // Permits writing temp files to disk!
);
Allows stages to write temporary spill files in the _tmp directory.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Exact Limit104,857,600 bytes (100MB) per pipeline stage.
Performance Trade-offSpilling to disk avoids query abortion, but disk I/O degrades execution speed by 10x-50x.

6. Deep Dive: MongoDB 6.0+ Pipeline Spill Changes

In MongoDB 6.0+, pipeline stages that spill to disk write temporary files to the storageEngine directory. However, relying on allowDiskUse in user-facing online web applications is an architectural anti-pattern. If an API query hits disk spillover, customer response times jump from 50ms to 4,000ms. Disk use should be reserved for offline nightly ETL jobs.

// Check if query spilled to disk in explain():
const exp = db.orders.explain("executionStats").aggregate([...], { allowDiskUse: true });
// Look for "usedDisk": true in stage stats
Production Warning: Never use allowDiskUse: true as a substitute for creating a proper index on the sort field.

7. Architectural Trade-offs

Advantages
  • •Protects the mongod server from running out of memory (OOM) due to runaway analytical queries
  • •Enables massive multi-gigabyte analytical reporting jobs to complete without failure
  • •Spill files are cleaned up automatically upon pipeline termination
Disadvantages & Gotchas
  • •Writing and reading temporary files to disk severely degrades query execution speed
  • •Increases storage IOPS contention on active production primary nodes

8. Technical Interview Questions

Q1: What is the default RAM limit for an individual aggregation stage in MongoDB, and what happens when it is exceeded?

The default memory limit is 100MB (104,857,600 bytes) per stage. If a blocking stage (like $sort or $group) exceeds this limit, the query terminates with an error (code 16819: Sort exceeded memory limit). To allow the query to complete by writing temporary spillover files to disk, the client must pass { allowDiskUse: true }.

9. Staff-Level Ready Answer

"MongoDB limits each aggregation stage to 100MB of RAM to prevent OOM server failure. Blocking stages exceeding this threshold fail with error 16819 unless { allowDiskUse: true } is supplied, which writes temporary files to disk. In production, index the sort/match fields rather than relying on disk spill in user-facing APIs."

10. Quick Knowledge Check

What is the exact memory limit for a single aggregation pipeline stage in MongoDB before allowDiskUse is required?