Write Concern - writing to all Active nodes during temporary failures

Due to specific business rules, I need to write to all three nodes of my MongoDB cluster.

For this reason, I have set the write concern to 3 in the query.

Unfortunately, when one of the nodes goes down, for example during an update, the query fails because it cannot meet the write concern of 3.

How can I specify the intention to write to all active nodes in the cluster to handle the case of one or more nodes being temporarily down?

Thank you,
Luigi

Hi, welcome to the MongoDB Community!

The recommended solution for your use case is to use the “majority” write concern.

MongoDB does not have a native mechanism to handle “3 or majority”. Setting w: 3 requires all three nodes to be online, which increases the risk of write failures during maintenance or unexpected outages. With “majority”, MongoDB only needs two out of three nodes to confirm the write, which improves availability.

If you still want to attempt writing to all three nodes when they are healthy, you can implement a programmatic fallback. The example below first tries with w: 3. If it fails, it falls back to “majority”:

const query = { _id: dto._id };
const update = { $set: newUserDocument };

let writeConcern = { w: 3, wtimeout: 5000 };

try {
  await this.userModel.updateOne(query, update, { writeConcern });
  console.log("Write confirmed on 3 nodes.");
} catch (error) {
  console.warn("Write concern w: 3 failed, falling back to 'majority'...");
  
  writeConcern = { w: "majority", wtimeout: 5000 };

  try {
    await this.userModel.updateOne(query, update, { writeConcern });
    console.log("Write confirmed on the majority of nodes (2 out of 3).");
  } catch (fallbackError) {
    console.error("Write failed even with majority:", fallbackError.message);
    throw fallbackError;
  }
}

Using “majority” is the recommended solution, but if you want to try for all three nodes first, the fallback logic above can be applied.

1 Like