A lock could not be acquired in the specified time
This error occurs when an operation cannot acquire a required lock on a resource (like a collection or document) within the allotted `maxTimeMS` period because another operation holds a conflicting lock. It is a sign of lock contention, often caused by long-running operations.
- 1A long-running write operation holding an exclusive (X) lock, blocking other writes and reads
- 2A schema modification (like building an index) holding a collection-level lock
- 3High levels of concurrent write operations targeting the same documents
- 4A slow storage subsystem that extends the time operations need to hold locks
Two clients attempt to acquire conflicting locks on the same document simultaneously.
// In one shell, start a long-running operation that holds a lock:
db.collection.updateOne({_id: 1}, {$set: {x: 1}, $setOnInsert: {}}, {upsert: true})
// This operation will hold a lock while it waits for a decision from a (hypothetical) slow transaction.
// In a second shell, another operation tries to access the same document and times out:
db.collection.updateOne({_id: 1}, {$set: {y: 1}}, {maxTimeMS: 1000})expected output
MongoServerError: Lock timeout
Fix 1
Optimize Long-Running Operations
WHEN Specific queries or updates are causing contention.
// Add an index to speed up the query part of the update.
db.collection.createIndex({ some_field: 1 });
// Then run the optimized update.
db.collection.updateOne({ some_field: "value" }, { $set: { updated: true } });Why this works
Identify and optimize the queries that hold locks for extended periods. Adding indexes is the most common way to reduce query time and, therefore, lock duration.
Fix 2
Retry the Operation
WHEN Contention is expected and transient.
try {
await collection.updateOne(...)
} catch (err) {
if (err.code === 24) {
// Wait and retry the operation
}
}Why this works
In systems with high concurrency, transient lock timeouts can be normal. Implement a retry mechanism with exponential backoff in your application code to handle these cases gracefully.
Fix 3
Reduce Document Contention
WHEN Many updates target a single document.
Why this works
If possible, revise your schema to distribute writes across more documents. For example, instead of a single document with a large array, consider using one document per array element.
✕ Drastically increase the `maxTimeMS` to a very large value
This does not solve the underlying contention issue; it only makes your application wait longer, potentially causing a backlog of requests and hiding the performance problem.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev