MongoDB replica sets are composed of a primary server and one or more secondaries that act as an hot stand by. In case the primary server of a replica set goes down due to a crash or a machine failure, an election takes place among the surviving nodes to decide who should be the new primary. The application can then start again writing against the primary after several tens of seconds, in the worst case.

To take advantage of the automated failover, the PHP driver should be configured accordingly:

try {
    $client = new MongoClient(
            'replicaSet' => 'myRSName',
            'connectTimeoutMS' => 5000,
    // use $client
} catch (MongoConnectionException $e) {
    // terminate or retry

For starters, the data source name should contain a seed list composed of the host names of all the nodes in the replica set that can become a primary; all these nodes should be identical. The driver will connect to all of the host names listed and ask each of them if they are the current primary: MongoDB itself guarantees that only a single primary can be active at any time.

Furthermore, the `replicaSet` name should be specified in the connection options.

The `connectTimeoutMS` option specifies the maximum amount of milliseconds that the driver should wait while connecting to each of the nodes. Since each node in the seed list can fail and stop responding, this value should be kept to a minimum of several seconds to quickly cut out dead nodes from the connection bootstrap process.

In case a MongoConnectionException is thrown, there is currently no reachable primary or an election is still taking place. You should wait and retry, or stop the current script.

Giorgio Sironi

Developer at Onebip , Website , Git home page , @giorgiosironi , Linkedin profile
I search for the harmony between form and context, which is a fancy way of saying I build software to fit in the world I'm in and its rapid changes. In the specific, my areas of expertise are testing, OOP design and distributed computing.

All articles by Giorgio Sironi


comments powered by Disqus


Follow Us