Skip to content

DOCSP-50220: Break up FAQ #276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion config/redirects
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,5 @@ raw: ${prefix}/stable -> ${base}/current/
[*-master]: ${prefix}/${version}/aggregation/vector-search/ -> ${base}/${version}/vector-search/
[*-master]: ${prefix}/${version}/monitoring/ -> ${base}/${version}/monitoring-logging/
[*-master]: ${prefix}/${version}/read/ -> ${base}/${version}/crud/
[*-master]: ${prefix}/${version}/write/ -> ${base}/${version}/crud/
[*-master]: ${prefix}/${version}/write/ -> ${base}/${version}/crud/
[*-master]: ${prefix}/${version}/faq/ -> ${base}/${version}/
61 changes: 61 additions & 0 deletions source/connect/client.txt
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,67 @@ This example constructs a client and passes the following parameters:
:language: php
:copyable: true

Client Persistence
------------------

The ``libmongoc`` library and the {+extension-short+} handle connections
to a MongoDB deployment. When you construct a :phpclass:`MongoDB\Client` instance, the
{+library-short+} creates a :php:`MongoDB\Driver\Manager <class.mongodb-driver-manager>` instance by using the
same connection string and options. The extension also uses those constructor
arguments to derive a hash key for persistent ``libmongoc`` clients. If
you previously persisted a ``libmongoc`` client by using a key, it is
reused. Otherwise, a new ``libmongoc`` client is created and persisted
for the lifetime of the PHP worker process. To learn more about
this process, see the :php:`{+extension-short+} documentation
<manual/en/mongodb.connection-handling.php>`.

Each ``libmongoc`` client maintains its own connections to the MongoDB deployment
and a view of its topology. When you reuse a persistent ``libmongoc`` client, the
{+library-short+} can avoid the overhead of establishing new connections and
rediscovering the topology. This approach generally improves performance and is
the driver's default behavior.

Persistent ``libmongoc`` clients are not freed until the PHP worker process
ends. As a result, connections to a MongoDB deployment might remain open
after a ``MongoDB\Driver\Manager`` object goes out of scope. While this is
typically not an issue for applications that connect to one MongoDB deployment,
it might cause errors in the following situations:

- PHP-FPM is configured with ``pm.max_requests=0`` so workers never respawn, and a
PHP application is deployed many times with small changes to its MongoDB
connection string or options. This could lead to an accumulation of ``libmongoc``
client objects in each worker process.

- An application occasionally connects to a separate MongoDB deployment in a
backend component where request latency is not the most important aspect.

In the first case, restarting PHP-FPM as part of the application deployment
allows the application to release any unused ``libmongoc`` clients and still use
a persistent client for the latest connection string.

The second case requires a different solution. Specifying ``true`` for the
``disableClientPersistence`` driver option instructs the {+library-short+} to
create a new ``libmongoc`` client and ensure it is freed when the corresponding
``MongoDB\Driver\Manager`` goes out of scope.

The following code demonstrates how to set the
``disableClientPersistence`` option to ``true`` when creating a client:

.. code-block:: php
:emphasize-lines: 5

<?php

$client = new MongoDB\Client(
uri: getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/',
driverOptions: ['disableClientPersistence' => true],
);

.. note::

If you disable client persistence, the {+library-short+} requires more
time to establish connections to the MongoDB deployment and discover its topology.

API Documentation
-----------------

Expand Down
82 changes: 82 additions & 0 deletions source/connect/connection-targets.txt
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,88 @@ DNS Service Discovery

$uri = 'mongodb+srv://<hostname>/';

Server Selection Errors
-----------------------

The following code shows possible server selection error
messages that your application might generate:

.. code-block:: none
:copyable: false

No suitable servers found (`serverSelectionTryOnce` set):
[connection refused calling hello on 'a.example.com:27017']
[connection refused calling hello on 'b.example.com:27017']

No suitable servers found: `serverSelectionTimeoutMS` expired:
[socket timeout calling hello on 'example.com:27017']

No suitable servers found: `serverSelectionTimeoutMS` expired:
[connection timeout calling hello on 'a.example.com:27017']
[connection timeout calling hello on 'b.example.com:27017']
[TLS handshake failed: -9806 calling hello on 'c.example.com:27017']

No suitable servers found: `serverselectiontimeoutms` timed out:
[TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'a.example.com:27017']
[TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'b.example.com:27017']

The {+extension-short+} usually represents these errors as
:php:`MongoDB\Driver\Exception\ConnectionTimeoutException <mongodb-driver-exception-connectiontimeoutexception>`
exceptions. However, the exception messages originate from
``libmongoc``, which is the underlying system library used by the extension. Since
these messages can take many forms, we recommend breaking down the structure of
the message so you can better diagnose errors in your application.

Messages typically start with "No suitable servers found". The next part of
the message indicates *how* server selection failed. The extension
avoids a server selection loop and makes a single attempt by default, according to
the ``serverSelectionTryOnce`` connection string option. If the extension is
configured to use a loop, a message that includes the phrase "serverSelectionTimeoutMS expired"
indicates that you exhausted its time limit.

The last component of the message tells us *why* server selection failed and
includes one or more errors directly from the topology scanner, which is the
service responsible for connecting to and monitoring each host. Any host that
previously experienced an error during monitoring will be included in this list. These
messages typically originate from low-level socket or TLS functions.

The following list describes the possible meanings of common phrases in the last error message
component:

- "Connection refused": The remote host might not be not listening on
the expected port.
- "Connection timeout": There might be a routing problem, a firewall error, or
a timeout due to latency.
- "Socket timeout": You likely established an initial connection that
was dropped or timed out due to latency.
- "TLS handshake failed": TLS or OCSP verification did not succeed, and you might
be using misconfigured TLS certificates.

In the case of a connection failure, you can use the ``connect`` tool for
more troubleshooting information. This tool tries to connect to each host in a
connection string by using socket functions, and then attempts to interact with
data. If you used Composer to install the library, you can use the following command
to start the ``connect`` tool:

.. code-block:: none

php vendor/mongodb/mongodb/tools/connect.php <connection URI>

If the server you are connecting to does not accept connections, the output
resembles the following code:

.. code-block:: none

Looking up MongoDB at <connection URI>
Found 1 host(s) in the URI. Will attempt to connect to each.

Could not connect to <host>:<port>: Connection refused

.. note::

The tool supports only the ``mongodb://`` URI schema. Using the
``mongodb+srv`` scheme is not supported.

API Documentation
-----------------

Expand Down
Loading
Loading