Customize Server Selection

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

Customize Server Selection

Overview

All MongoDB drivers follow a defined algorithm when selecting a server to read or write from. By using the ClusterConfigurator property of a MongoClient 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 .NET/C# Driver 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.

  2. If at least one readable server exists, the driver calls the user-defined server-selector function and passes in the list from the previous step.

  3. Applies the LocalThreshold connection setting to the list of servers returned from the function.

  4. Selects a server at random from the servers still on the list and executes the operation against this server.

When the .NET/C# Driver executes a write operation, it begins by selecting all writeable servers, not just those that match the active read preference. The remaining steps are identical.

To learn more about the default server selection algorithm, which the driver follows when you don't specify any custom server selection logic, see Server Selection Algorithm in the MongoDB Server manual.

Specifying Other Server Selection Algorithms

You can specify different server selection logic by passing an instance of a server selector class to the PreServerSelector or PostServerSelector property of the ClusterConfigurator. The PreServerSelector property specifies a server selector that runs before the standard server selection logic runs, while the PostServerSelector property specifies a server selector that runs after standard server selection logic runs. You can then pass your ClusterConfigurator instance to the MongoClientSettings object when you create a MongoClient instance to apply your custom server selection logic.

The following table lists the different types of server selectors you can pass to the ClusterConfigurator property:

Server Selector Description
CompositeServerSelector Selects servers based on multiple partial selectors
DelegateServerSelector Wraps a delegate server selector
EndPointServerSelector Selects servers based on their endpoint
LatencyLimitingServerSelector Selects servers within an acceptable latency range
PriorityServerSelector Selects a server based on a collection of servers to deprioritize
RandomServerSelector Selects a random server
ReadPreferenceServerSelector Selects servers based on a specified read preference

The following example instructs a MongoClient to use the RandomServerSelector class to select a server at random before the standard server selection logic runs:

var settings = MongoClientSettings.FromConnectionString("<connection string>");
var clusterConfigurator = builder =>
{
    builder.ConfigureCluster(c =>
        c.With(PreServerSelector: new RandomServerSelector()));
};

settings.ClusterConfigurator = clusterConfigurator;
var client = new MongoClient(settings);

To learn more about the different server selector classes, see the ServerSelectors API documentation.

Implementing Custom Server Selection Logic

You can implement your own custom server selection logic by creating a class that inherits from the IServerSelector interface and overrides the SelectServers() method. The following example shows a simple custom server selection class that selects servers with a ServerType of ServerType.ReplicaSetSecondary:

public class CustomServerSelector : IServerSelector
{
    public IEnumerable<ServerDescription> SelectServers(ClusterDescription cluster,
        IEnumerable<ServerDescription> servers)
    {
        return servers.Where(server => server.Type == ServerType.ReplicaSetSecondary);
    }
}

You can then pass an instance of this class to the PreServerSelector or PostServerSelector property of a ClusterConfigurator instance, as shown in the [Specifying Other Server Selection Algorithms](https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options/server-selection.md#std-label-csharp-server-selection-algorithm section.

Using Settings to Configure Server Selection

You can specify the following server selection settings in your MongoClient object or in your connection URI:

Setting Description
LocalThreshold The latency window for server eligibility. If a server's round trip takes longerthan the fastest server's round-trip time plus this value, the server isn'teligible for selection.Data Type: TimeSpanDefault: 15 millisecondsConnection URI Example: localThresholdMS=0
ReadPreference The client's default read-preference settings. MaxStaleness represents thelongest replication lag (in real time) that a secondary can experience andstill be eligible for server selection. Specifying -1 means no maximum.See [read preference](https://www.mongodb.com/docs/manual/core/read-preference.md#std-label-read-preference for more information.Data Type: ReadPreferenceDefault: ReadPreference.PrimaryConnection URI Example: `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: TimeSpanDefault: 30 secondsConnection URI Example: serverSelectionTimeoutMS=15000

Troubleshooting

Driver Throws a Timeout During Server Selection

Each driver operation requires that you choose a server that satisfies the server selection criteria. If you do not select an appropriate server within the server selection timeout, the driver throws a server selection timeout exception. The exception looks similar to the following:

A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }.
Client view of cluster state is
{
    ClusterId : "1",
    Type : "Unknown",
    State : "Disconnected",
    Servers :
    [{
        ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }",
        EndPoint: "Unspecified/localhost:27017",
        ReasonChanged: "Heartbeat",
        State: "Disconnected",
        ServerVersion: ,
        TopologyVersion: ,
        Type: "Unknown",
        HeartbeatException: "<exception details>"
    }]
}.

The error message consists of multiple parts:

  1. The server selection timeout (30000 ms).

  2. The server selectors considered (CompositeServerSelector containing AreSessionsSupportedServerSelector, LatencyLimitingServerSelector, and OperationsCountServerSelector).

  3. The driver’s current view of the cluster topology. The list of servers that the driver is aware of is a key part of this view. Each server description contains an exhaustive description of its current state including information about an endpoint, a server version, a server type, and its current health state. If the server encounters issues in reporting its health, HeartbeatException contains the exception from the last failed heartbeat. Analyzing the HeartbeatException on each cluster node can assist in diagnosing most server selection issues. The following heartbeat exceptions are common:

  4. No connection could be made because the target machine actively refused it: The driver cannot see this cluster node. This might be because the cluster node has crashed, a firewall is preventing network traffic from reaching the cluster node or port, or some other network error is preventing traffic from being successfully routed to the cluster node.

  5. Attempted to read past the end of the stream: This error happens when the driver cannot connect to the cluster nodes due to a network error, misconfigured firewall, or other network issue. To address this exception, ensure that all cluster nodes are reachable. This error commonly occurs when the client machine’s IP address is not configured in the Atlas IPs Access List, which you can find under the Network Access tab for your Atlas Project.

  6. The remote certificate is invalid according to the validation procedure: This error typically indicates a TLS/SSL-related problem such as an expired/invalid certificate or an untrusted root CA. You can use tools like openssl s_client to debug TLS/SSL-related certificate problems.

API Documentation

To learn more about the classes and methods used in this guide, see the following API documentation: