Error
Error Code:
64
MongoDB Error 64: Write Concern Failure
Description
This error indicates that a MongoDB write operation failed to meet the specified write concern requirements. This typically happens when the database cannot achieve the desired level of data durability or availability across its replica set members, preventing the write from being acknowledged successfully.
Error Message
Write Concern Failed
Known Causes
4 known causesInsufficient Replica Set Members
The write operation could not be acknowledged by the required number of replica set members because too few members were available or healthy.
Network Connectivity Issues
Network problems, such as partitions or firewalls, prevented replica set members from communicating to acknowledge the write.
Misconfigured Write Concern
The application requested a write concern level (e.g., 'majority') that the current replica set configuration or health state could not satisfy.
Primary Node Unavailability
The primary node, responsible for all write operations, was unavailable or undergoing an election during the write attempt.
Solutions
4 solutions available1. Verify Replica Set Health and Status easy
Ensure all members of the replica set are healthy and reachable.
1
Connect to your MongoDB primary node using the mongo shell.
mongo
2
Run the `rs.status()` command to get the replica set status.
rs.status()
3
Examine the output for any members that are not in an 'PRIMARY' or 'SECONDARY' state. Look for 'stateStr' fields that indicate issues like 'STARTUP', 'RECOVERING', 'ARBITER', or 'DOWN'.
/* Example output snippet to look for: */
{
...,
"members" : [
{
"_id" : 0,
"name" : "mongo1.example.com:27017",
"stateStr" : "PRIMARY",
"health" : 1,
...
},
{
"_id" : 1,
"name" : "mongo2.example.com:27017",
"stateStr" : "SECONDARY",
"health" : 1,
...
},
{
"_id" : 2,
"name" : "mongo3.example.com:27017",
"stateStr" : "RECOVERING", /* This is a potential issue */
"health" : 1,
...
}
],
...
4
If any members are not healthy or are in a problematic state, investigate those specific nodes. Check their logs for errors, network connectivity, and ensure they are properly configured and running.
/* On the problematic server, check logs like: */
/var/log/mongodb/mongod.log
2. Adjust Write Concern Level easy
Lower the write concern to reduce the strictness of write acknowledgments.
1
When performing write operations (insert, update, delete), specify a lower write concern. For example, to use a write concern of 'majority' (which is often the default and can cause this error under certain conditions), you can change it to '1' or 'w: 1'.
db.collection.insertOne({ item: 'book', qty: 10 }, { writeConcern: { w: 1 } });
db.collection.updateOne({ item: 'book' }, { $set: { qty: 20 } }, { writeConcern: { w: 1 } });
db.collection.deleteOne({ item: 'book' }, { writeConcern: { w: 1 } });
2
Alternatively, set a default write concern for your database or collection if this is a persistent issue and a lower strictness is acceptable. This is typically done during application startup or via `mongod` configuration.
/* Example for setting default write concern in application (e.g., Node.js driver) */
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
await client.connect();
const db = client.db('mydatabase');
// Set default write concern for all operations on this db object
db.setWriteConcern({ w: 1 });
// ... perform operations ...
} finally {
await client.close();
}
}
run().catch(console.dir);
3
Consider the trade-offs: A lower write concern means faster writes but a slightly higher risk of data loss if a primary node fails before writes are replicated to a majority.
/* No code, conceptual explanation */
3. Investigate Network Connectivity Issues medium
Ensure consistent and reliable network communication between replica set members.
1
From each MongoDB server in the replica set, try to ping or establish a TCP connection to all other members of the replica set on their MongoDB port (default 27017).
/* On mongo1, test connectivity to mongo2 */
ping mongo2.example.com
telnet mongo2.example.com 27017
/* On mongo2, test connectivity to mongo1 */
ping mongo1.example.com
telnet mongo1.example.com 27017
2
Check firewall rules on all servers and any network devices between them to ensure that MongoDB traffic is allowed. MongoDB typically uses port 27017.
/* Example using iptables on Linux */
sudo iptables -L -n | grep 27017
3
Examine MongoDB logs on each node for network-related errors, such as connection refused, timeouts, or host unreachable messages. These logs often pinpoint the source of network problems.
/* Example log entries to look for: */
ERROR: network error while attempting to connect to ...
WARNING: socket error: ...
4
If the replica set spans multiple data centers or cloud availability zones, ensure that inter-AZ/region network latency and bandwidth are sufficient for the replica set's operations. High latency can lead to write concern failures.
/* No code, conceptual explanation */
4. Review and Optimize Long-Running Operations medium
Identify and address slow queries or operations that might be blocking writes.
1
Connect to your MongoDB primary node and examine the slow query log. Enable slow query logging in your MongoDB configuration if it's not already active.
/* In mongod.conf: */
operationProfiling:
mode: "slowOperation"
slowms: 100 # Log operations slower than 100ms
2
Use the `$currentOp` aggregation to inspect currently running operations, paying attention to any that are taking an unusually long time or holding locks.
db.currentOp(true)
3
Analyze the output of `db.currentOp(true)` for operations marked as 'waitingForLock'. If you see many operations waiting, it indicates contention. Identify the queries causing these locks and optimize them.
/* Example output snippet to look for: */
{
...,
"waitingForLock" : true,
"lockType" : "write",
"op" : "...",
"secs_running" : 120,
...
}
4
For identified slow queries, consider adding appropriate indexes, rewriting the query for better performance, or breaking down large operations into smaller, more manageable ones. Ensure that indexes are being used effectively.
/* Example: Ensure an index exists for a common query */
db.collection.createIndex({ fieldName: 1 })
/* Use explain() to check query plans */
db.collection.find({ fieldName: 'value' }).explain('executionStats')