Andrew M
Andrew M

Reputation: 9459

How to set WriteConcern for very safe writes to MongoDB replica set in Java

We have a requirement to write one particular bit of data to a mongo replica set, and be really sure that it's safe (this is a legal requirement). Is there a standard WriteConcern that encapsulates a write to disk on a majority of nodes? Something like MAJORITY_FSYNCED.

The best I've come up with is the following - is this valid? WriteConcern replicaSetFsyscToMajority = new WriteConcern.Majority(0, true, false);

Looking at the pre-defined levels in the Java driver's WriteConcern class, none of the existing levels seem to be quite what I'm after, as far as I can tell:

FSYNCED means a secure write to disk on the primary only. (So a meltdown on the primary node could result in the write being lost)

REPLICAS_SAFE seems to represent that the write has been acknowledged by at least 2 replicas, and written to memory, not necessarily to disk (so a power cut to the whole mongo replica set could lose the write). MAJORITY is similar - but to ((n/2) + 1) replicas.

Supplementary notes/comments

* for a given definition of better!


EDIT: What we've tried so far...

We've tried using:

new WriteConcern.Majority(0, true, false)

and I can say that it doesn't throw any errors, (we can read and write, and all our tests pass), I have no idea if it is verifying writes to any great degree, and I haven't performance profiled it.

Upvotes: 1

Views: 5227

Answers (2)

Max
Max

Reputation: 1563

You are right that the write concern relating to the secondaries only assures acknowledgement, not that the data has been written to disk.

I'm not familiar with the Java driver but you should be able to set Journaling and WriteConcern separately. But bear in mind, even with J=1 and W=Majority there is also a possibility of roll-back as described in this SO question: Can rollback still occur on a MongoDB replica set with J=1 and W=Majority?

J=1 will ensure that the data is safe on the primary node, the secondaries will also give some protection in the form of replication.

To add extra confidence consider using RAID or similar on the primary's hard disk.

Upvotes: 1

evanchooly
evanchooly

Reputation: 6233

From the javadoc in WriteConcern:

/**
 * Exceptions are raised for network issues, and server errors; waits for at least 2 servers for the write operation.
 */
public final static WriteConcern REPLICA_ACKNOWLEDGED= new WriteConcern(2);

/**
 * Exceptions are raised for network issues, and server errors; waits for at least 2 servers for the write operation.
 * <p>
 * This field has been superseded by {@code WriteConcern.REPLICA_ACKNOWLEDGED}, and may be deprecated in a future release.
 * @see WriteConcern#REPLICA_ACKNOWLEDGED
 */
public final static WriteConcern REPLICAS_SAFE = new WriteConcern(2);

So I think REPLICAS_SAFE or REPLICA_ACKNOWLEDGED is what you'll need.

Upvotes: 0

Related Questions