How to fix MaxTimeMSExpired: operation exceeded time limit in MongoDB

MongoDBINTERMEDIATEMEDIUMUpdated Dec 12, 2025ยท 136 views

The MaxTimeMSExpired error occurs when a MongoDB operation exceeds the maximum execution time limit specified by the maxTimeMS parameter. This server-side timeout mechanism prevents long-running queries from consuming excessive database resources and helps maintain overall system performance.

Quick fix

Fixes 50

// Run explain on your query to see execution stats
db.collection.find({ /* your query */ }).explain("executionStats")

// For aggregation pipelines
db.collection.aggregate([ /* your pipeline */ ]).explain("executionStats")
  1. Check and optimize your query performance
  2. Add appropriate indexes to support your queries
  3. Increase the maxTimeMS value appropriately
  4. Break large operations into smaller chunks
mongodb โ€” error
// Run explain on your query to see execution stats
db.collection.find({ /* your query */ }).explain("executionStats")
// For aggregation pipelines
db.collection.aggregate([ /* your pipeline */ ]).explain("executionStats")
MaxTimeMSExpired: operation exceeded time limit

What this error means

The MaxTimeMSExpired error (error code 50) is MongoDB's way of enforcing query execution time limits. When you set a maxTimeMS value on a query or operation, MongoDB monitors how long the operation takes to complete. If the operation exceeds this time limit, MongoDB terminates it and returns this error to prevent long-running operations from consuming excessive server resources. This is particularly important in production environments where database performance needs to be maintained for all users. The timeout applies to various operations including queries, aggregation pipelines, update operations, and other database commands that support the maxTimeMS parameter.

Typical symptoms

  • Queries or aggregation operations fail with "MaxTimeMSExpired: operation exceeded time limit" error
  • Database operations that previously worked suddenly start timing out
  • Application logs show error code 50 from MongoDB
  • Operations complete successfully when run with higher maxTimeMS values or without time limits
  • Performance degradation in the application when certain database operations are attempted

Common causes

  1. The query or operation is genuinely taking too long to execute due to data volume or complexity
  2. Missing or inefficient indexes causing full collection scans
  3. The maxTimeMS value is set too low for the operation being performed
  4. Database server is under heavy load, slowing down query execution
  5. Complex aggregation pipelines with multiple stages that process large amounts of data
  6. Network latency between application and database server adding to overall execution time

How to fix "MaxTimeMSExpired: operation exceeded time limit"

1Check and optimize your query performance

First, examine the query that's timing out. Use MongoDB's explain() method to analyze query performance:

javascript
// Run explain on your query to see execution stats
db.collection.find({ /* your query */ }).explain("executionStats")

// For aggregation pipelines
db.collection.aggregate([ /* your pipeline */ ]).explain("executionStats")

Look for:
- High "executionTimeMillis" values
- Large "totalDocsExamined" counts
- "COLLSCAN" operations (collection scans) instead of "IXSCAN" (index scans)
- Inefficient query patterns or missing indexes

2Add appropriate indexes to support your queries

If your query is doing collection scans, create indexes to improve performance:

javascript
// Create a single field index
db.collection.createIndex({ fieldName: 1 })

// Create a compound index for queries on multiple fields
db.collection.createIndex({ field1: 1, field2: -1 })

// Create a text index for text search queries
db.collection.createIndex({ description: "text" })

// Check existing indexes
db.collection.getIndexes()

Remember that indexes should match your query patterns. Too many indexes can slow down write operations, so find a balance.

3Increase the maxTimeMS value appropriately

If the operation genuinely needs more time, increase the maxTimeMS value:

javascript
// For find queries
db.collection.find({ /* query */ }).maxTimeMS(60000) // 60 seconds

// For aggregation pipelines
db.collection.aggregate(
  [ /* pipeline */ ],
  { maxTimeMS: 120000 } // 120 seconds
)

// For update operations
db.collection.updateMany(
  { /* filter */ },
  { /* update */ },
  { maxTimeMS: 30000 } // 30 seconds
)

Set reasonable timeouts based on your application requirements. Consider:
- 30 seconds for most user-facing queries
- 60-120 seconds for complex aggregations
- 300+ seconds for batch processing jobs

4Break large operations into smaller chunks

For operations that process large datasets, consider breaking them into smaller batches:

javascript
// Instead of updating all documents at once
// db.collection.updateMany({status: "old"}, {$set: {status: "new"}})

// Process in batches
const batchSize = 1000;
let processed = 0;
let hasMore = true;

while (hasMore) {
  const result = db.collection.updateMany(
    { status: "old" },
    { $set: { status: "new" } },
    { limit: batchSize, maxTimeMS: 10000 }
  );

  processed += result.modifiedCount;
  hasMore = result.modifiedCount === batchSize;

  print(`Processed ${processed} documents`);
}

This approach:
- Reduces lock contention
- Allows other operations to run concurrently
- Makes progress visible
- Can be resumed if interrupted

5Monitor and tune database performance

Use MongoDB's monitoring tools to identify performance bottlenecks:

javascript
// Check current operations
db.currentOp()

// Check database stats
db.stats()

// Check collection stats
db.collection.stats()

// Use MongoDB Atlas Performance Advisor or mongostat/mongotop

Common performance improvements:
- Add more RAM to increase working set
- Scale up your database instance
- Implement connection pooling
- Use read preferences to distribute load
- Consider sharding for very large datasets

Advanced notes

The maxTimeMS parameter is a server-side timeout that applies to the entire operation execution on the MongoDB server. It's different from client-side timeouts or network timeouts.

Important considerations:
1. Killop: Operations terminated by maxTimeMS can be viewed in db.currentOp() with "killop" status
2. Atomicity: For write operations, the timeout applies to the entire batch, not individual documents
3. Aggregation: For aggregation pipelines, the timeout applies to the entire pipeline execution
4. Transactions: In multi-document transactions, maxTimeMS applies to each operation within the transaction
5. Index builds: maxTimeMS does not apply to index creation operations

Best practices:
- Set maxTimeMS at the driver level for all operations
- Use different timeout values for different operation types
- Implement retry logic with exponential backoff for transient timeouts
- Log timeout occurrences to identify patterns and optimize proactively
- Consider using MongoDB's $out stage for complex aggregations that write to temporary collections

Frequently asked questions

What does "50" mean?
The MaxTimeMSExpired error (error code 50) is MongoDB's way of enforcing query execution time limits. When you set a maxTimeMS value on a query or operation, MongoDB monitors how long the operation takes to complete. If the operation exceeds this time limit, MongoDB terminates it and returns this error to prevent long-running operations from consuming excessive server resources.
How do I fix "50"?
The MaxTimeMSExpired error occurs when a MongoDB operation exceeds the maximum execution time limit specified by the maxTimeMS parameter. This server-side timeout mechanism prevents long-running queries from consuming excessive database resources and helps maintain overall system performance.
What causes "50"?
The query or operation is genuinely taking too long to execute due to data volume or complexity Missing or inefficient indexes causing full collection scans The maxTimeMS value is set too low for the operation being performed
Is the "50" error serious?
It is a medium-severity error โ€” more of a blocker than a risk. The steps above resolve it.

Official resources & further reading