title: Block until new replica set configuration is in place
body: <p>My Python web application has several connections registered to the same MongoDb server, but 3 different databases. The application is run under 4 Gunicorn workers.</p>
  
  <p>I am using a Replica Set.</p>
  
  <p>When the primary is down, the current query fails and a refresh is scheduled in MongoReplicaSetClient (2.8, but I guess in 3.2 it's the same). The next query might succeed if a new primary is selected by the time and MonitorThread gets info about it updating the client's connection. </p>
  
  <p>But the refresh affects only this client. Other clients connected the same MongoDB server are not affected -- the same story happens with each.
  This means that if each worker is connected to 3 databases on the same MongoDB server and I am repeating the same HTTP request which uses all 3 databases when a primary fails it takes indefinite time to update all the connected clients. If each HTTP request goes round-robin to each worker out of 4 we need 12 requests to update each Mongo client. But in reality the requests don't go round-robin.</p>
  
  <p>Looking into PyMongo code
  <a href="https://github.com/mongodb/mongo-python-driver/blob/4897c5109097c251abb0758e9cb1d109c52b6fd6/pymongo/mongo_replica_set_client.py#L1641" rel="nofollow"><code>MongoReplicaSetClient._send_message_with_response</code></a> I see that when the primary is down, <code>self.disconnect</code> is called which calls <a href="https://github.com/mongodb/mongo-python-driver/blob/4897c5109097c251abb0758e9cb1d109c52b6fd6/pymongo/mongo_replica_set_client.py#L1069" rel="nofollow"><code>self.__schedule_refresh</code></a>. This method has argument <code>sync</code>, which allows to "block until the refresh completes".</p>
  
  <p>My idea is to catch <code>AutoReconnect</code> exception and call <code>__schedule_refresh(sync=True)</code> on all clients which are connected to the failed primary and block until the new replica set configuration is in place. So HTTP requests will not be processed (resulting in 500) until the database is OK.</p>
  
  <p>But <code>__schedule_refresh</code> is a private method. Also I don't know if calling it sequentially on all clients will be fast -- looks <code>MonitorThread</code> does its work in intervals.</p>
  
  <p>Or maybe I could use <a href="https://github.com/mongodb/mongo-python-driver/blob/4897c5109097c251abb0758e9cb1d109c52b6fd6/pymongo/mongo_replica_set_client.py#L1107" rel="nofollow"><code>MongoReplicaSetClient.refresh</code></a>.</p>
  
  <p>What do you think about the idea? Does it have drawbacks?</p>
  
  <p>Would you help me with the implementation?</p>