Replica Set Semantics

The MongoDB Java driver handles failover in replicated setups with tunable levels of transparency to the user.  By default, a Mongo connection object will ignore failures of secondaries, and only reads will throw MongoExceptions when the primary node is unreachable.

The level of exception reporting is tunable however, using a specific WriteConcern; you can set this on the Mongo/DB/Collection/Method level. Several levels are included as static options:

  • WriteConcern.NONE : No exceptions thrown.
  • WriteConcern.NORMAL : Exceptions are only thrown when the primary node is unreachable for a read, or the full replica set is unreachable.
  • WriteConcern.SAFE : Same as the above, but exceptions thrown when there is a server error on writes or reads.  Calls getLastError().
  • WriteConcern.REPLICAS_SAFE : Tries to write to two separate nodes.  Same as the above, but will throw an exception if two writes are not possible.
  • WriteConcern.FSYNC_SAFE : Same as WriteConcern.SAFE, but also waits for write to be written to disk.
Additional errors may appear in the log files, these are for reporting purposes and logged based on the logging settings.

Sample code is provided which illustrates some of these options. To quickly initialize a sample replica set, you can use the mongo shell:

> var rst = new ReplSetTest({ nodes : 3 })
> rst.startSet() // wait for processes to start
> rst.initiate() // wait for replica set initialization

Java client code demonstrating error handling is available :

Follow @mongodb

MongoDB Pittsburgh - May 15
MongoNYC - May 23
MongoDB Paris - Jun 14
MongoDB UK - Jun 20
MongoDC - June 26


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus