It looks like your issue is caused by how the MongoDB driver handles elections. Even with retryWrites=true, writes that fail during an election are not retried automatically.
-
Increase serverSelectionTimeoutMS
- Ensure the driver waits for a new primary instead of failing immediately:
const options = {
retryWrites: true,
retryReads: true,
serverSelectionTimeoutMS: 5000, // Wait 5 sec for primary socketTimeoutMS: 30000,
connectTimeoutMS: 30000,
heartbeatFrequencyMS: 1000
};
-
Implement a Retry Mechanism in Code
- MongoDB doesn’t automatically retry writes during an election, so you need to handle retries manually:
async function safeWriteOperation() {
let retries = 3;
while (retries > 0) {
try {
await client.db("test").collection("data").insertOne({ name: "MongoDB" });
console.log("Write successful");
break;
} catch (err) {
if (err.message.includes("closed") || err.message.includes("NotPrimary")) {
console.log("Write failed, retrying...", retries);
retries--;
await new Promise(res => setTimeout(res, 2000));
} else {
throw err;
}
}
}
}
-
Ensure wtimeoutMS is Set for Write Concern
- This ensures that writes wait for a new primary to be elected:
const url = 'mongodb://psmdb1:27017,psmdb2:27017,psmdb3:27017/?replicaSet=rs0&retryWrites=true&w=majority&wtimeoutMS=5000';
Some related docs…