Max Benson Max Benson - 1 year ago 91
PHP Question

Persistent connections with new Mongo PHP driver

For a project I am using the new MongoDB driver for PHP with the library (see:, not the legacy one.

We are running PHP 7 as FPM.

I recently did some profiling with XDEBUG and realized that the first database query is significantly slower than the second one, for example

Session::validate -> Account::find 38ms
getProfile -> Account::find 2ms

would execute the query to obtain one document by its
and both calls look up different documents.

My two questions that arise

  1. It is my understanding that the first query is so much slower than the second one, because the driver has to establish a connection with the database server and in our case also has to authenticate. This connection is not persisted between script executions. Is that correct?

  2. If (1) is true, is there any way to persist that connection with the new driver? From my understanding, with the old driver connections to the database could be stored in between request. (

Answer Source

Someone on github pointed me towards this site, so I can now answer my own question. To quote:

All versions of the driver since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.


Versions of the PHP driver before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the driver persists individual database connections but not authentication state or topology information. This means that the driver needs to issue commands at the start of each request to authenticate and » discover the server topology.

Since the latest stable driver version as of writing this is 1.1.9, the authentication information are not persisted. However you can upgrade to 1.2.0 alpha releases, which can seriously speed up the process of connecting, as I discovered in some tests on my system. There are a few known bugs with the 1.2.0 alphas currently, so I will be sticking with the slower 1.1.9 for now.

This reponse will soon be outdated...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download