-
Notifications
You must be signed in to change notification settings - Fork 10
DOCSP-51347: Server Selection #118
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
mcmorisi
merged 7 commits into
mongodb:comp-cov
from
mcmorisi:DOCSP-51347-server-selection
Jul 25, 2025
Merged
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
.. _kotlin-sync-server-selection: | ||
|
||
========================== | ||
Customize Server Selection | ||
========================== | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 1 | ||
:class: singlecol | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: read preference, write, server selection | ||
|
||
Overview | ||
-------- | ||
|
||
All MongoDB drivers follow a defined algorithm when selecting a server to read or write | ||
from. By using the ``ClusterSettings`` property of a ``MongoClientSettings`` object, you can | ||
customize this algorithm to choose the server that works best for your application. | ||
|
||
.. important:: | ||
|
||
Customizing the server selection algorithm might have unintended consequences, | ||
such as degraded read or write performance. | ||
|
||
Default Algorithm | ||
----------------- | ||
|
||
When the {+driver-short+} executes a read operation, it performs the following steps, | ||
in order, to select a MongoDB deployment: | ||
|
||
1. Selects all servers that match the active read preference from the list of known servers. | ||
stIncMale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
#. If at least one readable server exists, calls the user-defined | ||
server-selector function and passes in the list from the previous step | ||
stIncMale marked this conversation as resolved.
Show resolved
Hide resolved
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
#. Applies the ``localThreshold`` connection setting to the list of | ||
servers returned from the function | ||
|
||
#. Selects a server at random from the servers still on the list and | ||
executes the operation against this server | ||
stIncMale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
When the {+driver-short+} executes a write operation, it begins by selecting all writeable | ||
servers from the list of known servers, not just those that match the active read preference. | ||
The remaining steps are identical to the preceding list. | ||
|
||
To learn more about the default server selection algorithm, which the driver follows | ||
when you don't specify any custom server selection logic, see | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
:manual:`Server Selection Algorithm </core/read-preference-mechanics/>` in the | ||
{+mdb-server+} manual. | ||
|
||
Implement Custom Server Selection Logic | ||
--------------------------------------- | ||
|
||
You can implement your own custom server selection logic by creating a class that | ||
implements the ``ServerSelector`` interface and overrides the ``select()`` method. The following | ||
mcmorisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
example shows a simple custom server selection class that selects servers with a ``type`` | ||
value of ``ServerType.REPLICA_SET_SECONDARY``: | ||
|
||
.. literalinclude:: /includes/connect/ServerSelection.kt | ||
:language: kotlin | ||
:copyable: true | ||
:start-after: // start-custom-selector | ||
:end-before: // end-custom-selector | ||
|
||
Use the ``applyToClusterSettings()`` method to pass an instance of this class to your | ||
``MongoClientSettings``. The following example shows how to create | ||
a ``MongoClient`` with an instance of the custom server selector class from the preceding example: | ||
|
||
.. literalinclude:: /includes/connect/ServerSelection.kt | ||
:language: kotlin | ||
:copyable: true | ||
:start-after: // start-selector | ||
:end-before: // end-selector | ||
|
||
Use Settings to Configure Server Selection | ||
------------------------------------------ | ||
|
||
You can specify the following server selection settings in your ``MongoClient`` object or | ||
in your connection URI: | ||
stIncMale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
.. list-table:: | ||
:widths: 30 70 | ||
:header-rows: 1 | ||
|
||
* - Setting | ||
- Description | ||
|
||
* - ``localThreshold`` | ||
- | The latency window for server eligibility. If a server's round trip takes longer | ||
| than the fastest server's round-trip time plus this value, the server isn't | ||
| eligible for selection. | ||
| | ||
| **Data Type**: ``Integer`` | ||
| **Default**: 15 milliseconds | ||
| **Connection URI Example**: ``localThresholdMS=0`` | ||
|
||
* - ``readPreference`` | ||
- | The client's default read-preference settings. For more information on read preference | ||
options, see :manual:`Read Preference </core/read-preference/>` in the {+mdb-server+} manual. | ||
| | ||
| **Data Type**: `ReadPreference <{+core-api+}/ReadPreference.html>`__ | ||
| **Default**: ``ReadPreference.primary()`` | ||
| **Connection URI Example**: | ||
|
||
.. code-block:: none | ||
:copyable: false | ||
|
||
readPreference=primaryPreferred | ||
&maxStalenessSeconds=90 | ||
&readPreferenceTags=dc:ny,rack:1 | ||
|
||
* - ``serverSelectionTimeout`` | ||
- | The length of time the driver tries to select a server before timing out. | ||
| | ||
| **Data Type**: ``Long`` | ||
| **Default**: 30 seconds | ||
| **Connection URI Example**: ``serverSelectionTimeoutMS=15000`` | ||
|
||
API Documentation | ||
----------------- | ||
|
||
To learn more about the classes and methods used in this guide, see the following API | ||
documentation: | ||
|
||
- `MongoClient <{+driver-api+}/-mongo-client/index.html>`__ | ||
- `MongoClientSettings <{+core-api+}/MongoClientSettings.html>`__ | ||
- `ServerSelector <{+core-api+}/selector/ServerSelector.html>`__ | ||
- `ReadPreference <{+core-api+}/ReadPreference.html>`__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package org.example | ||
import com.mongodb.ConnectionString | ||
import com.mongodb.MongoClientSettings | ||
import com.mongodb.connection.ClusterDescription | ||
import com.mongodb.connection.ServerDescription | ||
import com.mongodb.connection.ServerType | ||
import com.mongodb.kotlin.client.MongoClient | ||
import com.mongodb.selector.ServerSelector | ||
|
||
// start-custom-selector | ||
class CustomServerSelector : ServerSelector { | ||
override fun select(cluster: ClusterDescription): List<ServerDescription> { | ||
return cluster.serverDescriptions.filter { it.type == ServerType.REPLICA_SET_SECONDARY } | ||
} | ||
} | ||
// end-custom-selector | ||
|
||
fun main() { | ||
// start-selector | ||
val settings = MongoClientSettings.builder() | ||
.applyConnectionString(ConnectionString("<connection URI>")) | ||
.applyToClusterSettings { builder -> | ||
builder.serverSelector(CustomServerSelector()) | ||
} | ||
.build() | ||
|
||
val mongoClient = MongoClient.create(settings) | ||
// end-selector | ||
} | ||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.