Table of Contents

Class CosmosClientOptions

Namespace
Microsoft.Azure.Cosmos
Assembly
Microsoft.Azure.Cosmos.Client.dll

Defines all the configurable options that the CosmosClient requires.

public class CosmosClientOptions
Inheritance
CosmosClientOptions
Inherited Members
Extension Methods

Examples

An example on how to configure the serialization option to ignore null values.

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    SerializerOptions = new CosmosSerializationOptions(){
        IgnoreNullValues = true
    },
    ConnectionMode = ConnectionMode.Gateway,
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

Constructors

CosmosClientOptions()

Creates a new CosmosClientOptions

public CosmosClientOptions()

Properties

AccountInitializationCustomEndpoints

Gets and sets the custom endpoints to use for account initialization for geo-replicated database accounts in the Azure Cosmos DB service.

public IEnumerable<Uri> AccountInitializationCustomEndpoints { get; set; }

Property Value

IEnumerable<Uri>

Examples

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    AccountInitializationCustomEndpoints = new HashSet<Uri>()
    { 
        new Uri("custom.p-1.documents.azure.com"),
        new Uri("custom.p-2.documents.azure.com") 
    }
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

Remarks

During the CosmosClient initialization the account information, including the available regions, is obtained from the Endpoint. Should the global endpoint become inaccessible, the CosmosClient will attempt to obtain the account information issuing requests to the custom endpoints provided in AccountInitializationCustomEndpoints.

Nevertheless, this parameter remains optional and is recommended for implementation when a customer has configured an endpoint with a custom DNS hostname (instead of accountname-region.documents.azure.com) etc. for their Cosmos DB account.

See also Diagnose and troubleshoot the availability of Cosmos SDKs for more details.

See Also

AllowBulkExecution

Allows optimistic batching of requests to service. Setting this option might impact the latency of the operations. Hence this option is recommended for non-latency sensitive scenarios only.

public bool AllowBulkExecution { get; set; }

Property Value

bool

ApplicationName

Get or set user-agent suffix to include with every Azure Cosmos DB service interaction.

public string ApplicationName { get; set; }

Property Value

string

Remarks

Setting this property after sending any request won't have any effect.

ApplicationPreferredRegions

Gets and sets the preferred regions for geo-replicated database accounts in the Azure Cosmos DB service.

public IReadOnlyList<string> ApplicationPreferredRegions { get; set; }

Property Value

IReadOnlyList<string>

Examples

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    ApplicationPreferredRegions = new List<string>(){ Regions.EastUS, Regions.WestUS }
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

Remarks

During the CosmosClient initialization the account information, including the available regions, is obtained from the Endpoint. The CosmosClient will use the value of ApplicationPreferredRegions to populate the preferred list with the account available regions that intersect with its value. If the value of ApplicationPreferredRegions contains regions that are not an available region in the account, the values will be ignored. If the these invalid regions are added later to the account, the CosmosClient will use them if they are higher in the preference order.

If during CosmosClient initialization, the Endpoint is not reachable, the CosmosClient will attempt to recover and obtain the account information issuing requests to the regions in ApplicationPreferredRegions in the order that they are listed.

See also Diagnose and troubleshoot the availability of Cosmos SDKs for more details.

This configuration is an alternative to ApplicationRegion, either one can be set but not both.

See Also

ApplicationRegion

Gets or sets the location where the application is running. This will influence the SDK's choice for the Azure Cosmos DB service interaction.

public string ApplicationRegion { get; set; }

Property Value

string

Examples

If an account is configured with multiple regions including West US, East US, and West Europe, configuring a client like the below example would result in the CosmosClient generating a sorted preferred regions based on proximity to East US. The CosmosClient will send requests to East US, if that region becomes unavailable, it will fallback to West US (second in proximity), and finally to West Europe if West US becomes unavailable.

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    ApplicationRegion = Regions.EastUS
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

Remarks

During the CosmosClient initialization the account information, including the available regions, is obtained from the Endpoint. The CosmosClient will use the value of ApplicationRegion to populate the preferred list with the account available regions ordered by geographical proximity to the indicated region. If the value of ApplicationRegion is not an available region in the account, the preferred list is still populated following the same mechanism but would not include the indicated region.

If during CosmosClient initialization, the Endpoint is not reachable, the CosmosClient will attempt to recover and obtain the account information issuing requests to all Regions ordered by proximity to the ApplicationRegion. For more granular control over the selected regions or to define a list based on a custom criteria, use ApplicationPreferredRegions instead of ApplicationRegion.

See also Diagnose and troubleshoot the availability of Cosmos SDKs for more details.

This configuration is an alternative to ApplicationPreferredRegions, either one can be set but not both.

See Also

ConnectionMode

Get or set the connection mode used by the client when connecting to the Azure Cosmos DB service.

public ConnectionMode ConnectionMode { get; set; }

Property Value

ConnectionMode

Default value is Direct

Remarks

See Also

ConsistencyLevel

This can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests.

public ConsistencyLevel? ConsistencyLevel { get; set; }

Property Value

ConsistencyLevel?

CosmosClientTelemetryOptions

Gets or sets Client Telemetry Options like feature flags and corresponding options

public CosmosClientTelemetryOptions CosmosClientTelemetryOptions { get; set; }

Property Value

CosmosClientTelemetryOptions

CustomHandlers

Gets the handlers run before the process

public Collection<RequestHandler> CustomHandlers { get; }

Property Value

Collection<RequestHandler>
See Also

EnableContentResponseOnWrite

Gets or sets the boolean to only return the headers and status code in the Cosmos DB response for write item operation like Create, Upsert, Patch and Replace. Setting the option to false will cause the response to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client.

public bool? EnableContentResponseOnWrite { get; set; }

Property Value

bool?

Remarks

This is optimal for workloads where the returned resource is not used.

This option can be overriden by similar property in ItemRequestOptions and TransactionalBatchItemRequestOptions

See Also

EnableTcpConnectionEndpointRediscovery

Gets or sets the flag to enable address cache refresh on TCP connection reset notification.

public bool EnableTcpConnectionEndpointRediscovery { get; set; }

Property Value

bool

The default value is true

Remarks

Does not apply if Gateway is used.

GatewayModeMaxConnectionLimit

Get or set the maximum number of concurrent connections allowed for the target service endpoint in the Azure Cosmos DB service.

public int GatewayModeMaxConnectionLimit { get; set; }

Property Value

int

Default value is 50.

Remarks

This setting is only applicable in Gateway mode.

See Also

HttpClientFactory

Gets or sets a delegate to use to obtain an HttpClient instance to be used for HTTPS communication.

public Func<HttpClient> HttpClientFactory { get; set; }

Property Value

Func<HttpClient>

Remarks

HTTPS communication is used when ConnectionMode is set to Gateway for all operations and when ConnectionMode is Direct (default) for metadata operations.

Useful in scenarios where the application is using a pool of HttpClient instances to be shared, like ASP.NET Core applications with IHttpClientFactory or Blazor WebAssembly applications.

For .NET core applications the default GatewayConnectionLimit will be ignored. It must be set on the HttpClientHandler.MaxConnectionsPerServer to limit the number of connections

IdleTcpConnectionTimeout

(Direct/TCP) Controls the amount of idle time after which unused connections are closed.

public TimeSpan? IdleTcpConnectionTimeout { get; set; }

Property Value

TimeSpan?

By default, idle connections are kept open indefinitely. Value must be greater than or equal to 10 minutes. Recommended values are between 20 minutes and 24 hours.

Remarks

Mainly useful for sparse infrequent access to a large database account.

LimitToEndpoint

Limits the operations to the provided endpoint on the CosmosClient.

public bool LimitToEndpoint { get; set; }

Property Value

bool

Default value is false.

Remarks

When the value of this property is false, the SDK will automatically discover write and read regions, and use them when the configured application region is not available. When set to true, availability is limited to the endpoint specified on the CosmosClient constructor. Defining the ApplicationRegion or ApplicationPreferredRegions is not allowed when setting the value to true.

See Also

MaxRequestsPerTcpConnection

(Direct/TCP) Controls the number of requests allowed simultaneously over a single TCP connection. When more requests are in flight simultaneously, the direct/TCP client will open additional connections.

public int? MaxRequestsPerTcpConnection { get; set; }

Property Value

int?

The default settings allow 30 simultaneous requests per connection. Do not set this value lower than 4 requests per connection or higher than 50-100 requests per connection.
The former can lead to a large number of connections to be created. The latter can lead to head of line blocking, high latency and timeouts.

Remarks

Applications with a very high degree of parallelism per connection, with large requests or responses, or with very tight latency requirements might get better performance with 8-16 requests per connection.

MaxRetryAttemptsOnRateLimitedRequests

Gets or sets the maximum number of retries in the case where the request fails because the Azure Cosmos DB service has applied rate limiting on the client.

public int? MaxRetryAttemptsOnRateLimitedRequests { get; set; }

Property Value

int?

The default value is 9. This means in the case where the request is rate limited, the same request will be issued for a maximum of 10 times to the server before an error is returned to the application.

If the value of this property is set to 0, there will be no automatic retry on rate limiting requests from the client and the exception needs to be handled at the application level.

Remarks

When a client is sending requests faster than the allowed rate, the service will return HttpStatusCode 429 (Too Many Requests) to rate limit the client. The current implementation in the SDK will then wait for the amount of time the service tells it to wait and retry after the time has elapsed.

For more information, see Handle rate limiting/request rate too large.

See Also

MaxRetryWaitTimeOnRateLimitedRequests

Gets or sets the maximum retry time in seconds for the Azure Cosmos DB service.

public TimeSpan? MaxRetryWaitTimeOnRateLimitedRequests { get; set; }

Property Value

TimeSpan?

The default value is 30 seconds.

Remarks

The minimum interval is seconds. Any interval that is smaller will be ignored.

When a request fails due to a rate limiting error, the service sends back a response that contains a value indicating the client should not retry before the RetryAfter time period has elapsed.

This property allows the application to set a maximum wait time for all retry attempts. If the cumulative wait time exceeds the this value, the client will stop retrying and return the error to the application.

For more information, see Handle rate limiting/request rate too large.

See Also

MaxTcpConnectionsPerEndpoint

(Direct/TCP) Controls the maximum number of TCP connections that may be opened to each Cosmos DB back-end. Together with MaxRequestsPerTcpConnection, this setting limits the number of requests that are simultaneously sent to a single Cosmos DB back-end(MaxRequestsPerTcpConnection x MaxTcpConnectionPerEndpoint).

public int? MaxTcpConnectionsPerEndpoint { get; set; }

Property Value

int?

The default value is 65,535. Value must be greater than or equal to 16.

OpenTcpConnectionTimeout

(Direct/TCP) Controls the amount of time allowed for trying to establish a connection.

public TimeSpan? OpenTcpConnectionTimeout { get; set; }

Property Value

TimeSpan?

The default timeout is 5 seconds. For latency sensitive applications that prefer to retry faster, a recommended value of 1 second can be used.

Remarks

When the time elapses, the attempt is cancelled and an error is returned. Longer timeouts will delay retries and failures.

PortReuseMode

(Direct/TCP) Controls the client port reuse policy used by the transport stack.

public PortReuseMode? PortReuseMode { get; set; }

Property Value

PortReuseMode?

The default value is PortReuseMode.ReuseUnicastPort.

Remarks

ReuseUnicastPort and PrivatePortPool are not mutually exclusive. When PrivatePortPool is enabled, the client first tries to reuse a port it already has. It falls back to allocating a new port if the initial attempts failed. If this fails, too, the client then falls back to ReuseUnicastPort.

PriorityLevel

Sets the priority level for requests created using cosmos client.

public PriorityLevel? PriorityLevel { get; set; }

Property Value

PriorityLevel?

Remarks

If priority level is also set at request level in PriorityLevel, that priority is used. If AllowBulkExecution is set to true in CosmosClientOptions, priority level set on the CosmosClient is used.

See Also

RequestTimeout

Gets the request timeout in seconds when connecting to the Azure Cosmos DB service. The number specifies the time to wait for response to come back from network peer.

public TimeSpan RequestTimeout { get; set; }

Property Value

TimeSpan

Default value is 6 seconds.

See Also

Serializer

Get to set an optional JSON serializer. The client will use it to serialize or de-serialize user's cosmos request/responses. SDK owned types such as DatabaseProperties and ContainerProperties will always use the SDK default serializer.

public CosmosSerializer Serializer { get; set; }

Property Value

CosmosSerializer

Examples

An example on how to set a custom serializer. For basic serializer options look at CosmosSerializationOptions

CosmosSerializer ignoreNullSerializer = new MyCustomIgnoreNullSerializer();

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    Serializer = ignoreNullSerializer
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

SerializerOptions

Get to set optional serializer options.

public CosmosSerializationOptions SerializerOptions { get; set; }

Property Value

CosmosSerializationOptions

Examples

An example on how to configure the serialization option to ignore null values

CosmosClientOptions clientOptions = new CosmosClientOptions()
{
    SerializerOptions = new CosmosSerializationOptions(){
        IgnoreNullValues = true
    }
};

CosmosClient client = new CosmosClient("endpoint", "key", clientOptions);

ServerCertificateCustomValidationCallback

A callback delegate to do custom certificate validation for both HTTP and TCP.

public Func<X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get; set; }

Property Value

Func<X509Certificate2, X509Chain, SslPolicyErrors, bool>

Remarks

Emulator: To ignore SSL Certificate please suffix connectionstring with "DisableServerCertificateValidation=True;". When CosmosClientOptions.HttpClientFactory is used, SSL certificate needs to be handled appropriately. NOTE: DO NOT use the `DisableServerCertificateValidation` flag in production (only for emulator)

TokenCredentialBackgroundRefreshInterval

The SDK does a background refresh based on the time interval set to refresh the token credentials. This avoids latency issues because the old token is used until the new token is retrieved.

public TimeSpan? TokenCredentialBackgroundRefreshInterval { get; set; }

Property Value

TimeSpan?

Remarks

The recommended minimum value is 5 minutes. The default value is 50% of the token expire time.

WebProxy

(Gateway/Https) Get or set the proxy information used for web requests.

public IWebProxy WebProxy { get; set; }

Property Value

IWebProxy