Skip to content

Instantly share code, notes, and snippets.

@analogrelay
Last active February 25, 2026 18:36
Show Gist options
  • Select an option

  • Save analogrelay/8d209ee7aecb6796dea725c29f0f6ca9 to your computer and use it in GitHub Desktop.

Select an option

Save analogrelay/8d209ee7aecb6796dea725c29f0f6ca9 to your computer and use it in GitHub Desktop.
Cosmos DB Cross SDK Options Analysis

Azure Cosmos DB — Cross-SDK Configuration Options Summary

This document maps every major Cosmos DB client configuration option across all five SDKs. Each table groups a category of options; rows represent a particular customization and columns show how each SDK exposes it. Cells contain concise option names; numbered notes below each table provide additional detail.

SDKs covered: .NET v3 · Java v4 · Go (azcosmos) · Python (azure-cosmos) · Rust (azure_data_cosmos)


Table of Contents

  1. Authentication
  2. Connection & Networking
  3. Consistency
  4. Retry & Timeout
  5. Region & Availability
  6. Performance & Write Behavior
  7. Serialization
  8. Telemetry & Diagnostics
  9. Item CRUD Request Options
  10. Query Request Options
  11. Change Feed Options
  12. Transactional Batch / Bulk Options
  13. Throughput Configuration
  14. Dedicated Gateway / Integrated Cache
  15. Container Properties
  16. Indexing Policy
  17. Vector Embedding & Search
  18. Full-Text Search
  19. Patch Operations
  20. Change Feed Processor
  21. Cascading / Layering Behavior

1. Authentication

Customization .NET Java Go Python Rust
Account key CosmosClient(endpoint, key) key(String) NewClientWithKey() CosmosClient(url, key) CosmosClient::with_key() ¹
Connection string CosmosClient(connStr) (parse manually) NewClientFromConnectionString() from_connection_string() with_connection_string() ¹
AAD / Entra ID token CosmosClient(endpoint, TokenCredential) credential(TokenCredential) NewClient(endpoint, cred) CosmosClient(url, TokenCredential) CosmosClient::new()
Rotatable key AzureKeyCredential AzureKeyCredential
Resource token Constructor param ² resourceToken(String) credential dict ³
Permission-based Via resource token permissions(List) credential as iterable ³
Custom token resolver authorizationTokenResolver()

Notes:

  1. Rust requires the key_auth feature flag for key-based and connection-string constructors.
  2. .NET accepts a resource token as the second parameter in the (endpoint, authKeyOrResourceToken) overload.
  3. Python detects credential type at runtime: str → master key; dict → resource tokens; iterable of mappings → permission feed; TokenCredential → AAD.

2. Connection & Networking

Customization .NET Java Go Python Rust
Connection mode ConnectionMode ¹ directMode() / gatewayMode() Gateway only connection_mode ² Gateway only
Request timeout RequestTimeout DirectConnectionConfig.setNetworkRequestTimeout() Retry.TryTimeout connection_timeout request_timeout
Max connections GatewayModeMaxConnectionLimit / MaxTcpConnectionsPerEndpoint setMaxConnectionsPerEndpoint() / setMaxConnectionPoolSize() (azcore transport) (ConnectionPolicy) (transport)
Idle connection timeout IdleTcpConnectionTimeout setIdleConnectionTimeout() / setIdleEndpointTimeout()
TCP open timeout OpenTcpConnectionTimeout setConnectTimeout()
Max requests per connection MaxRequestsPerTcpConnection setMaxRequestsPerConnection()
Port reuse PortReuseMode
Endpoint rediscovery on reset EnableTcpConnectionEndpointRediscovery setConnectionEndpointRediscoveryEnabled()
HTTP proxy WebProxy GatewayConnectionConfig.setProxy() proxy_config / proxies
Custom HTTP transport HttpClientFactory Transport ³ transport client_options.transport
Custom pipeline policies CustomHandlers addOperationPolicy() PerCallPolicies / PerRetryPolicies per_call_policies / per_try_policies
User-Agent suffix ApplicationName userAgentSuffix() Telemetry.ApplicationID user_agent_suffix application_name
TLS cert validation ServerCertificateCustomValidationCallback connection_verify / ssl_config
Connection sharing across clients connectionSharingAcrossClientsEnabled()
HTTP/2 Http2ConnectionConfig

Notes:

  1. .NET supports Direct (TCP) and Gateway (HTTPS). Direct is the default.
  2. Python only supports Gateway mode; the field exists but only Gateway is implemented.
  3. Go inherits transport configuration from azcore.ClientOptions.
  4. Java HTTP/2 support is a Beta feature nested inside GatewayConnectionConfig.

3. Consistency

Customization .NET Java Go Python Rust
Client-level default CosmosClientOptions.ConsistencyLevel consistencyLevel() (account default) ¹ consistency_level consistency_level
Per-request override *RequestOptions.ConsistencyLevel setConsistencyLevel() ² *.ConsistencyLevel ³ consistency_level kwarg ItemOptions.consistency_level / QueryOptions.consistency_level
Read consistency strategy readConsistencyStrategy()
Session token (per-request) *.SessionToken setSessionToken() *.SessionToken session_token session_token
Auto session capture override sessionCapturingOverrideEnabled()

Notes:

  1. Go has no client-level consistency option; it always uses the account default. Override is only at the per-request level.
  2. Java supports per-request consistency override on item, query, batch, readMany, and stored procedure request options.
  3. Go supports per-request override on ItemOptions, QueryOptions, TransactionalBatchOptions, and ReadManyOptions.
  4. Java's ReadConsistencyStrategy is a Beta feature that provides additional strategies (LATEST_COMMITTED, GLOBAL_STRONG) and overrides ConsistencyLevel when set.

All SDKs enforce the rule that consistency can only be weakened (relaxed) at the request level, never strengthened beyond the account setting.


4. Retry & Timeout

Customization .NET Java Go Python Rust
429 max retry attempts MaxRetryAttemptsOnRateLimitedRequests (9) setMaxRetryAttemptsOnThrottledRequests() (9) (azcore) Retry.MaxRetries (3) retry_total (9) RetryOptions::none() ¹
429 max wait time MaxRetryWaitTimeOnRateLimitedRequests (30 s) setMaxRetryWaitTime() (30 s) Retry.MaxRetryDelay (60 s) retry_backoff_max (30 s) (internal)
Retry delay / backoff (internal: 1 s initial) (internal) Retry.RetryDelay (800 ms) retry_backoff_factor / retry_fixed_interval (N/A)
Retryable status codes (internal) (internal) Retry.StatusCodes retry_on_status_codes (internal)
Custom retry predicate Retry.ShouldRetry
Session retry options SessionRetryOptions ² SessionRetryOptions ³ (internal) session_retry_options
Non-idempotent write retry NonIdempotentWriteRetryOptions retry_write
End-to-end latency policy CosmosEndToEndOperationLatencyPolicyConfig
Per-request timeout RequestTimeout (6 s) setNetworkRequestTimeout() (5 s) Retry.TryTimeout (0) timeout kwarg request_timeout

Notes:

  1. Rust sets RetryOptions::none() on the Azure Core pipeline and handles retries internally within its own Cosmos-specific retry policy.
  2. .NET SessionRetryOptions controls MinInRegionRetryTime, MaxInRegionRetryCount, and RemoteRegionPreferred for 404/1002 errors.
  3. Java SessionRetryOptions adds regionSwitchHint (LOCAL_REGION_PREFERRED / REMOTE_REGION_PREFERRED), minTimeoutPerRegion, and maxRetriesPerRegion.
  4. Java's end-to-end latency policy wraps a total operation timeout plus an optional availability strategy for cross-region hedging.

5. Region & Availability

Customization .NET Java Go Python Rust
Preferred regions ApplicationPreferredRegions preferredRegions() PreferredRegions preferred_locations application_preferred_regions
Application region ApplicationRegion ¹ application_region
Excluded regions (client) — ² excludedRegionsSupplier() excluded_locations excluded_regions
Excluded regions (per-request) RequestOptions.ExcludeRegions setExcludedRegions() excluded_locations kwarg ItemOptions.excluded_regions
Endpoint discovery (always on unless LimitToEndpoint) endpointDiscoveryEnabled() enable_endpoint_discovery
Multi-write regions — ³ multipleWriteRegionsEnabled() multiple_write_locations
Limit to single endpoint LimitToEndpoint
Custom init endpoints AccountInitializationCustomEndpoints account_initialization_custom_endpoints
Cross-region hedging AvailabilityStrategy ThresholdBasedAvailabilityStrategy availability_strategy_config
Read fallback readRequestsFallbackEnabled()

Notes:

  1. ApplicationRegion specifies where the application itself is running, allowing the SDK and backend to negotiate the optimal region order from that location. Mutually exclusive with ApplicationPreferredRegions.
  2. .NET has no client-level excluded regions; it uses per-request ExcludeRegions which subtracts from the preferred list.
  3. .NET auto-detects multi-write; Java exposes explicit multipleWriteRegionsEnabled().
  4. .NET CrossRegionHedgingStrategy accepts threshold, thresholdStep, and enableMultiWriteRegionHedge. Can be set per-request or disabled with DisabledStrategy().
  5. Java hedging is configured via ThresholdBasedAvailabilityStrategy (threshold 500 ms, step 100 ms) nested inside the end-to-end latency policy.
  6. Python hedging uses a dict with threshold_ms (default 500) and threshold_steps_ms (default 100). Per-request override with None disables hedging.

6. Performance & Write Behavior

Customization .NET Java Go Python Rust
Content response on write (client) EnableContentResponseOnWrite contentResponseOnWriteEnabled() EnableContentResponseOnWrite no_response_on_write ¹
Content response on write (request) ItemRequestOptions.EnableContentResponseOnWrite setContentResponseOnWriteEnabled() ItemOptions.EnableContentResponseOnWrite no_response kwarg content_response_on_write_enabled
Bulk execution mode AllowBulkExecution CosmosBulkExecutionOptions ²
Priority level (client) PriorityLevel ThroughputControlGroupConfig.priorityLevel() priority priority
Priority level (request) RequestOptions.PriorityLevel (via throughput control group) priority kwarg ItemOptions.priority / QueryOptions.priority
Throughput bucket (client) ThroughputControlGroupConfig.throughputBucket() throughput_bucket throughput_bucket
Throughput bucket (request) throughput_bucket kwarg ItemOptions.throughput_bucket / QueryOptions.throughput_bucket
Proactive connection warm-up CreateAndInitializeAsync() ³ openConnectionsAndInitCaches()

Notes:

  1. Python inverts the polarity: no_response_on_write=True disables the response body (equivalent to .NET/Java/Go EnableContentResponseOnWrite=false).
  2. Java bulk execution is configured via CosmosBulkExecutionOptions with initialMicroBatchSize, maxMicroBatchSize, and maxMicroBatchConcurrency.
  3. .NET CreateAndInitializeAsync accepts a list of (databaseId, containerId) pairs and warms caches/connections before returning the client.
  4. Java CosmosContainerProactiveInitConfig supports proactiveConnectionRegionsCount (max 5) and aggressiveWarmupDuration.

7. Serialization

Customization .NET Java Go Python Rust
Custom serializer Serializer / CosmosSerializer customItemSerializer() ¹
Serializer options SerializerOptions ²
System.Text.Json UseSystemTextJsonSerializerWithOptions
LINQ naming policy CosmosLinqSerializerOptions
Per-request serializer setCustomItemSerializer() ¹

Notes:

  1. Java's CosmosItemSerializer is abstract; the per-request override is available on item, query, change feed, batch, bulk, and readMany options.
  2. .NET CosmosSerializationOptions provides IgnoreNullValues, Indented, and PropertyNamingPolicy (Default or CamelCase). All three serializer settings are mutually exclusive.

8. Telemetry & Diagnostics

Customization .NET Java Go Python Rust
Distributed tracing DisableDistributedTracing tracingOptions() / enableTransportLevelTracing() TracingProvider instrumentation
Metrics IsClientMetricsEnabled / OperationMetricsOptions ¹ CosmosMicrometerMetricsOptions ²
Diagnostics thresholds (client) CosmosThresholdOptions CosmosDiagnosticsThresholds
Diagnostics thresholds (request) RequestOptions.CosmosThresholdOptions setDiagnosticsThresholds()
Query text in traces QueryTextMode ³ showQueryMode() ³
Logging options Logging enable_diagnostics_logging / logger logging
Client telemetry to service DisableSendingMetricsToService
Client correlation ID clientCorrelationId()
Diagnostics handler diagnosticsHandler()
Response hook response_hook

Notes:

  1. .NET metrics are a Preview feature with OperationMetricsOptions and NetworkMetricsOptions.
  2. Java provides fine-grained Micrometer integration: per-meter options, tag suppression, histogram toggles, metric categories, and sampling rates.
  3. Both .NET and Java expose three modes: None, ParameterizedOnly/PARAMETERIZED, All/ALL.
  4. Go logging is via azcore LogOptions: IncludeBody, AllowedHeaders, AllowedQueryParams.
  5. Rust logging is via azure_core LoggingOptions, with Cosmos-specific allowed headers automatically configured.

9. Item CRUD Request Options

Customization .NET Java Go Python Rust
Partition key ItemRequestOptions (implicit) setPartitionKey() (method param) partition_key (method param)
ETag / If-Match IfMatchEtag setIfMatchETag() IfMatchEtag etag + match_condition if_match_etag
If-None-Match IfNoneMatchEtag setIfNoneMatchETag() etag + match_condition ¹
Pre-triggers PreTriggers setPreTriggerInclude() PreTriggers pre_trigger_include pre_triggers
Post-triggers PostTriggers setPostTriggerInclude() PostTriggers post_trigger_include post_triggers
Indexing directive IndexingDirective setIndexingDirective() IndexingDirective indexing_directive indexing_directive
Session token SessionToken setSessionToken() SessionToken session_token session_token
Consistency override ConsistencyLevel setConsistencyLevel() ConsistencyLevel — ² consistency_level
Content on write EnableContentResponseOnWrite setContentResponseOnWriteEnabled() EnableContentResponseOnWrite no_response content_response_on_write_enabled
Dedicated gateway cache DedicatedGatewayRequestOptions setDedicatedGatewayRequestOptions() DedicatedGatewayRequestOptions max_integrated_cache_staleness_in_ms
Priority PriorityLevel (via throughput control) priority priority
Excluded regions ExcludeRegions setExcludedRegions() excluded_locations excluded_regions
Custom headers AddRequestHeaders initial_headers custom_headers
Auto-ID generation enable_automatic_id_generation
Filter predicate (patch) PatchItemRequestOptions.FilterPredicate setFilterPredicate() filter_predicate PatchDocument.condition
Availability strategy AvailabilityStrategy setCosmosEndToEndOperationLatencyPolicyConfig() availability_strategy_config
Throughput control group setThroughputControlGroupName() throughput_bucket throughput_bucket

Notes:

  1. Python uses match_condition (from azure.core) paired with etag to express both If-Match and If-None-Match.
  2. Python does not expose per-item-write consistency override; it's available on read/query operations via consistency_level.

10. Query Request Options

Customization .NET Java Go Python Rust
Max items per page MaxItemCount setMaxItemCount() ¹ PageSizeHint max_item_count
Partition key PartitionKey setPartitionKey() (method param) partition_key (method param)
Feed range setFeedRange() feed_range
Cross-partition query (automatic) (automatic) EnableCrossPartitionQuery enable_cross_partition_query (automatic)
Scan in query EnableScanInQuery setScanInQueryEnabled() EnableScanInQuery enable_scan_in_query
Index metrics PopulateIndexMetrics setIndexMetricsEnabled() PopulateIndexMetrics populate_index_metrics
Query metrics setQueryMetricsEnabled() populate_query_metrics
Continuation token limit ResponseContinuationTokenLimitInKb setResponseContinuationTokenLimitInKb() ResponseContinuationTokenLimitInKB continuation_token_limit
Max parallelism MaxConcurrency setMaxDegreeOfParallelism()
Max buffered items MaxBufferedItemCount setMaxBufferedItemCount()
Query parameters (LINQ / SQL param) (SQL param) QueryParameters parameters — ²
Session token SessionToken setSessionToken() SessionToken session_token session_token
Consistency override ConsistencyLevel setConsistencyLevel() ConsistencyLevel consistency_level consistency_level
Dedicated gateway cache DedicatedGatewayRequestOptions setDedicatedGatewayRequestOptions() DedicatedGatewayRequestOptions max_integrated_cache_staleness_in_ms
Optimistic direct execution EnableOptimisticDirectExecution
Low-precision ORDER BY EnableLowPrecisionOrderBy
Full-text score scope FullTextScoreScope
Query name (telemetry) setQueryName()
External query engine QueryEngine ³

Notes:

  1. Java uses setMaxItemCount() on CosmosChangeFeedRequestOptions; for queries it's set via CosmosQueryRequestOptions or the unified CosmosRequestOptions.
  2. Rust passes query parameters directly in the query method call, not via options.
  3. Go's QueryEngine is a Preview feature for client-side cross-partition query processing.

11. Change Feed Options

Customization .NET Java Go Python Rust
Feed mode ChangeFeedMode.LatestVersion / .AllVersionsAndDeletes Factory method ¹ mode ²
Start from beginning Via ChangeFeedStartFrom createForProcessingFromBeginning() start_time="Beginning"
Start from now Via ChangeFeedStartFrom createForProcessingFromNow() start_time="Now"
Start from time Via ChangeFeedStartFrom createForProcessingFromPointInTime() StartFrom start_time=datetime
Resume from continuation Via ChangeFeedStartFrom createForProcessingFromContinuation() Continuation continuation
Max items per page PageSizeHint setMaxItemCount() MaxItemCount max_item_count
Feed range Via ChangeFeedStartFrom Factory param FeedRange feed_range
Partition key Via ChangeFeedStartFrom PartitionKey partition_key
Priority priority
Prefetch pages setMaxPrefetchPageCount()

Notes:

  1. Java change feed options are created via factory methods that determine the mode and starting point: createForProcessingFromBeginning(FeedRange), createForProcessingFromNow(FeedRange), createForProcessingFromContinuation(String), createForProcessingFromPointInTime(Instant, FeedRange).
  2. Python supports "LatestVersion" and "AllVersionsAndDeletes" via the mode keyword argument.

12. Transactional Batch / Bulk Options

Customization .NET Java Go Python Rust
Batch consistency TransactionalBatchRequestOptions.ConsistencyLevel CosmosBatchRequestOptions.setConsistencyLevel() TransactionalBatchOptions.ConsistencyLevel
Batch session token TransactionalBatchRequestOptions.SessionToken CosmosBatchRequestOptions.setSessionToken() TransactionalBatchOptions.SessionToken
Batch content on write (inherits from client) TransactionalBatchOptions.EnableContentResponseOnWrite
Per-batch-item ETag TransactionalBatchItemRequestOptions.IfMatchEtag CosmosBatchItemRequestOptions.setIfMatchETag() TransactionalBatchItemOptions.IfMatchETag
Per-batch-item indexing TransactionalBatchItemRequestOptions.IndexingDirective
Per-batch-item content on write TransactionalBatchItemRequestOptions.EnableContentResponseOnWrite
Batch patch filter TransactionalBatchPatchItemRequestOptions.FilterPredicate CosmosBatchPatchItemRequestOptions.setFilterPredicate()
Bulk micro-batch size setInitialMicroBatchSize() / setMaxMicroBatchSize()
Bulk concurrency setMaxMicroBatchConcurrency()
Bulk item content on write CosmosBulkItemRequestOptions.setContentResponseOnWriteEnabled()

13. Throughput Configuration

Customization .NET Java Go Python Rust
Manual throughput ThroughputProperties.CreateManualThroughput() ThroughputProperties.createManualThroughput() NewManualThroughputProperties() offer_throughput (int) ThroughputProperties::manual()
Autoscale throughput ThroughputProperties.CreateAutoscaleThroughput() ThroughputProperties.createAutoscaledThroughput() NewAutoscaleThroughputProperties() ThroughputProperties(auto_scale_max_throughput=) ThroughputProperties::autoscale()
Autoscale increment NewAutoscaleThroughputPropertiesWithIncrement() auto_scale_increment_percent increment_percent param
Throughput control groups ThroughputControlGroupConfig ¹
Global throughput control GlobalThroughputControlConfig ²
ETag (conditional update) ThroughputProperties.ETag (read-only) ThroughputOptions.IfMatchEtag

Notes:

  1. Java throughput control groups allow setting per-group targetThroughput, targetThroughputThreshold, priorityLevel, and throughputBucket.
  2. Java global throughput control coordinates across clients using a lease container with configurable controlItemRenewInterval and controlItemExpireInterval.

14. Dedicated Gateway / Integrated Cache

Customization .NET Java Go Python Rust
Max cache staleness MaxIntegratedCacheStaleness setMaxIntegratedCacheStaleness() MaxIntegratedCacheStaleness max_integrated_cache_staleness_in_ms (via custom headers) ¹
Bypass cache BypassIntegratedCache setIntegratedCacheBypassed() BypassIntegratedCache (via custom headers) ¹
Shard key setShardKey()
Scope Per-request ² Per-request Per-request ³ Per-request

Notes:

  1. Rust does not have a dedicated gateway options struct; dedicated gateway headers can be set via custom_headers on CosmosClientOptions or per-request options.
  2. .NET DedicatedGatewayRequestOptions is available on ItemRequestOptions and QueryRequestOptions.
  3. Go DedicatedGatewayRequestOptions is available on ItemOptions, QueryOptions, and ReadManyOptions.

15. Container Properties

Customization .NET Java Go Python Rust
Container ID Id setId() ID id id
Partition key definition PartitionKeyPath / PartitionKeyPaths setPartitionKeyDefinition() PartitionKeyDefinition partition_key=PartitionKey(path=) partition_key: PartitionKeyDefinition
Hierarchical partition keys PartitionKeyPaths (list) PartitionKeyDefinition (multi-path) MultiHash kind PartitionKey(path=[...], kind="MultiHash") PartitionKeyDefinition::from(tuple)
Default TTL DefaultTimeToLive setDefaultTimeToLiveInSeconds() DefaultTimeToLive default_ttl default_ttl
Analytical store TTL AnalyticalStoreTimeToLiveInSeconds setAnalyticalStoreTimeToLiveInSeconds() AnalyticalStoreTimeToLiveInSeconds analytical_storage_ttl analytical_storage_ttl
Indexing policy IndexingPolicy setIndexingPolicy() IndexingPolicy indexing_policy indexing_policy
Unique key policy UniqueKeyPolicy setUniqueKeyPolicy() UniqueKeyPolicy unique_key_policy unique_key_policy
Conflict resolution ConflictResolutionPolicy setConflictResolutionPolicy() ConflictResolutionPolicy conflict_resolution_policy conflict_resolution_policy
Vector embedding policy VectorEmbeddingPolicy setVectorEmbeddingPolicy() VectorEmbeddingPolicy vector_embedding_policy vector_embedding_policy
Full-text policy FullTextPolicy setFullTextPolicy() FullTextPolicy full_text_policy
Change feed policy ChangeFeedPolicy setChangeFeedPolicy() change_feed_policy
Client encryption policy ClientEncryptionPolicy setClientEncryptionPolicy()
Computed properties ComputedProperties setComputedProperties() computed_properties
Geospatial config GeospatialConfig

16. Indexing Policy

Customization .NET Java Go Python Rust
Automatic indexing Automatic setAutomatic() Automatic (via dict) automatic
Indexing mode IndexingMode ¹ setIndexingMode() ¹ IndexingMode ² (via dict) indexing_mode ²
Included paths IncludedPaths setIncludedPaths() IncludedPaths (via dict) included_paths
Excluded paths ExcludedPaths setExcludedPaths() ExcludedPaths (via dict) excluded_paths
Composite indexes CompositeIndexes setCompositeIndexes() CompositeIndexes (via dict) composite_indexes
Spatial indexes SpatialIndexes setSpatialIndexes() SpatialIndexes (via dict) spatial_indexes
Vector indexes VectorIndexes setVectorIndexes() VectorIndexes (via dict) vector_indexes
Full-text indexes FullTextIndexes setCosmosFullTextIndexes() FullTextIndexes (via dict)

Notes:

  1. .NET and Java support Consistent, Lazy (deprecated), and None.
  2. Go and Rust support Consistent and None only (no Lazy).

17. Vector Embedding & Search

Customization .NET Java Go Python Rust
Embedding path Embedding.Path setPath() VectorEmbedding.Path path (dict) VectorEmbedding.path
Data type VectorDataType ¹ CosmosVectorDataType ¹ VectorDataType ² (dict value) VectorDataType ³
Dimensions Embedding.Dimensions setEmbeddingDimensions() VectorEmbedding.Dimensions (dict value) VectorEmbedding.dimensions
Distance function DistanceFunction CosmosVectorDistanceFunction VectorDistanceFunction (dict value) VectorDistanceFunction
Index type VectorIndexType CosmosVectorIndexSpec.setType() VectorIndex.Type (dict value) VectorIndexType
Quantizer type VectorIndexPath.QuantizerType setQuantizerType()
Quantization byte size VectorIndexPath.QuantizationByteSize setQuantizationSizeInBytes()
Search list size VectorIndexPath.IndexingSearchListSize setIndexingSearchListSize()
Shard key VectorIndexPath.VectorIndexShardKey setVectorIndexShardKeys()

Notes:

  1. .NET: Float32, Float16, Uint8, Int8. Java: UINT8, INT8, FLOAT16, FLOAT32.
  2. Go: float32, int8, uint8.
  3. Rust: Float16, Float32, Uint8, Int8.
  4. All SDKs support Cosine, Euclidean, and DotProduct.
  5. All SDKs support Flat, QuantizedFlat, and DiskANN index types.

18. Full-Text Search

Customization .NET Java Go Python Rust
Default language FullTextPolicy.DefaultLanguage setDefaultLanguage() FullTextPolicy.DefaultLanguage (dict value)
Per-path language FullTextPath.Language CosmosFullTextPath.setLanguage() FullTextPath.Language (dict value)
Full-text indexes FullTextIndexPath CosmosFullTextIndex FullTextIndex (dict value)
Full-text score scope FullTextScoreScope ¹

Notes:

  1. .NET-only: FullTextScoreScope controls BM25 statistics scope (Global across all partitions or Local per partition).

19. Patch Operations

Operation .NET Java Go Python Rust
Add PatchOperation.Add<T>() CosmosPatchOperations.add() (via body) PatchOperation::Add
Remove PatchOperation.Remove() CosmosPatchOperations.remove() (via body) PatchOperation::Remove
Replace PatchOperation.Replace<T>() CosmosPatchOperations.replace() (via body) PatchOperation::Replace
Set PatchOperation.Set<T>() CosmosPatchOperations.set() (via body) PatchOperation::Set
Increment PatchOperation.Increment() CosmosPatchOperations.increment() (via body) PatchOperation::Increment
Move PatchOperation.Move() CosmosPatchOperations.move() (via body) PatchOperation::Move
Conditional filter PatchItemRequestOptions.FilterPredicate setFilterPredicate() filter_predicate PatchDocument.condition

20. Change Feed Processor

Customization .NET Java Go Python Rust
Instance / host name WithInstanceName() hostName()
Lease container WithLeaseContainer() leaseContainer()
In-memory lease WithInMemoryLeaseContainer()
Max items per poll WithMaxItems() setMaxItemCount()
Poll interval WithPollInterval() (5 s) setFeedPollDelay() (5 s)
Start time WithStartTime() setStartTime()
Lease renew interval WithLeaseConfiguration() (17 s) setLeaseRenewInterval() (17 s)
Lease acquire interval WithLeaseConfiguration() (13 s) setLeaseAcquireInterval() (13 s)
Lease expiration WithLeaseConfiguration() (60 s) setLeaseExpirationInterval() (60 s)
Error notification WithErrorNotification()
Lease prefix setLeasePrefix()
Min/max scale count setMinScaleCount() / setMaxScaleCount()
Scheduler setScheduler()

Note: Change Feed Processor is a high-level abstraction only available in .NET and Java. Go, Python, and Rust provide lower-level change feed iteration but not the processor pattern.


21. Cascading / Layering Behavior

The table below summarizes which options support cascading (setting a default at a broad level that can be overridden at a narrower level) across all SDKs.

Option .NET Java Go Python Rust
Consistency level Client → Request ¹ Client → Request ¹ Account → Request ¹ Client → Operation ¹ Client → Request ¹
Content response on write Client → Request Client → Request Client → Request Client → Operation (request only)
Priority level Client → Request (via throughput control) Client → Operation Client → Request
Throughput bucket (via throughput control) Client → Operation Client → Request
Excluded regions (request only) ² Client → Request Client → Operation Client → Request ³
Availability / hedging strategy Client → Request ⁴ Client → Request ⁵ Client → Operation ⁶
Session token (auto + request override) (auto + request override) (auto + request override) (auto + request override) (request only)
Diagnostics thresholds Client → Request Client → Request
Serializer (client only) Client → Request
Indexing directive Container → Request ⁷ Container → Request ⁷ Container → Request ⁷ Container → Request ⁷ Container → Request ⁷
Custom headers (request only) (context-based) (request only) Client → Request ⁸

Notes:

  1. All SDKs enforce the rule that consistency can only be weakened at a lower level. The override chain is: Account default → Client override → Per-request override.
  2. .NET does not have client-level excluded regions; ExcludeRegions on RequestOptions subtracts from the preferred region list.
  3. Rust: ItemOptions.excluded_regions = None inherits from client; Some(vec![]) explicitly clears exclusions for that request.
  4. .NET: RequestOptions.AvailabilityStrategy overrides client; set DisabledStrategy() to opt out per-request.
  5. Java: end-to-end latency policy (which wraps the availability strategy) can be overridden per-request.
  6. Python: availability_strategy_config=None at the operation level explicitly disables hedging for that request.
  7. All SDKs: the container's IndexingPolicy defines the default; per-item IndexingDirective (Include/Exclude) overrides it for individual writes.
  8. Rust: custom_headers at the client level fill in gaps; request-level custom_headers take priority per header name.

Cascade Flow (All SDKs)

┌────────────────────────────────────────────────────────┐
│  Account Level (server-side)                           │
│  • Default consistency level                           │
│  • Regions & multi-write configuration                 │
├────────────────────────────────────────────────────────┤
│  Client Level                                          │
│  • Consistency level (weaken only)                     │
│  • Preferred/excluded regions                          │
│  • Content response on write                           │
│  • Priority level, throughput bucket                   │
│  • Retry & timeout policies                            │
│  • Serialization, telemetry, diagnostics thresholds    │
│  • Connection mode & transport settings                │
│  • Hedging / availability strategy                     │
│  • Custom headers (Rust, Python, .NET)                 │
├────────────────────────────────────────────────────────┤
│  Database / Container Level                            │
│  • Throughput (manual / autoscale)                     │
│  • Container schema: partition key, TTL, indexing,     │
│    unique keys, vector, full-text, conflict resolution │
├────────────────────────────────────────────────────────┤
│  Request Level (per-operation)                         │
│  • Consistency level (weaken only)                     │
│  • Session token                                       │
│  • Content response on write                           │
│  • Priority, throughput bucket                         │
│  • Excluded regions                                    │
│  • Indexing directive (overrides container policy)      │
│  • ETag / conditional access                           │
│  • Pre/post triggers                                   │
│  • Dedicated gateway cache options                     │
│  • Diagnostics thresholds (.NET, Java)                 │
│  • Serializer (Java only)                              │
│  • Custom headers                                      │
│  • Availability strategy override (.NET, Java, Python) │
└────────────────────────────────────────────────────────┘

Generated from analysis of individual SDK reports: .NET · Java · Go · Python · Rust

Azure Cosmos DB .NET SDK v3 — Comprehensive Configuration Reference

This document catalogs every configurable option in the Azure Cosmos DB .NET SDK v3 (Microsoft.Azure.Cosmos), organized by purpose. Options span four levels:

Level Scope
Client Set once on CosmosClientOptions / CosmosClientBuilder; applies to all operations through that client instance.
Database Properties on DatabaseProperties; set at database create/replace time.
Container Properties on ContainerProperties and sub-policies; set at container create/replace time.
Request Set per-operation via *RequestOptions classes; can override certain client-level defaults.

Table of Contents

  1. Authentication & Endpoint
  2. Connection & Networking
  3. Retry & Timeout
  4. Consistency
  5. Serialization
  6. Performance & Bulk Execution
  7. Region & Availability
  8. Telemetry & Diagnostics
  9. Request-Level Options (Base)
  10. Item Request Options
  11. Patch Item Request Options
  12. Query Request Options
  13. Change Feed Request Options
  14. Change Feed Processor Options
  15. ReadMany Request Options
  16. Stored Procedure Request Options
  17. Transactional Batch Options
  18. Container Request Options
  19. Dedicated Gateway Options
  20. Container Properties & Policies
  21. Indexing Policy
  22. Vector Embedding & Search
  23. Full-Text Search
  24. Conflict Resolution Policy
  25. Client Encryption Policy
  26. Change Feed Policy
  27. Database Properties
  28. Throughput Configuration
  29. Patch Operations
  30. Environment Variables
  31. Key Enumerations
  32. Cascading & Layering Behavior

1. Authentication & Endpoint

These are set via CosmosClient constructor parameters or CosmosClientBuilder.

CosmosClient Constructors

Constructor Signature Description
CosmosClient(string connectionString, CosmosClientOptions?) Connection string containing endpoint + key.
CosmosClient(string endpoint, string authKeyOrResourceToken, CosmosClientOptions?) Endpoint + master key or resource token.
CosmosClient(string endpoint, AzureKeyCredential, CosmosClientOptions?) Endpoint + rotatable AzureKeyCredential.
CosmosClient(string endpoint, TokenCredential, CosmosClientOptions?) Endpoint + AAD TokenCredential (e.g. DefaultAzureCredential).

Static Factory Methods — CreateAndInitializeAsync

All four authentication variants above are also available as async factory methods that accept IReadOnlyList<(string databaseId, string containerId)> to warm up caches and connections for the specified containers before returning the client.

Client-Level Auth Options

Option Type Default Builder Method Description
TokenCredentialBackgroundRefreshInterval TimeSpan? null (set directly on options) Interval for background refresh of AAD token credentials.
AccountInitializationCustomEndpoints IEnumerable<Uri> null WithCustomAccountEndpoints() Custom private endpoints for account initialization in geo-replicated setups.
LimitToEndpoint bool false WithLimitToEndpoint() When true, all operations are routed only to the endpoint provided in the constructor (disables region discovery).
ServerCertificateCustomValidationCallback Func<X509Certificate2, X509Chain, SslPolicyErrors, bool> null (set directly) Custom TLS certificate validation for both HTTP and TCP connections.

2. Connection & Networking

Set on CosmosClientOptions or via CosmosClientBuilder.

Option Type Default Builder Method Description
ConnectionMode ConnectionMode Direct WithConnectionModeDirect() / WithConnectionModeGateway() Direct (TCP) for lower latency or Gateway (HTTPS) for firewall-friendly routing.
GatewayModeMaxConnectionLimit int 50 WithConnectionModeGateway(maxConnectionLimit) Max concurrent HTTPS connections to the gateway endpoint.
IdleTcpConnectionTimeout TimeSpan? null (indefinite) WithConnectionModeDirect(idleTcpConnectionTimeout) Time after which idle Direct/TCP connections are closed.
OpenTcpConnectionTimeout TimeSpan? 5 seconds WithConnectionModeDirect(openTcpConnectionTimeout) Timeout for establishing a new TCP connection.
MaxRequestsPerTcpConnection int? 30 WithConnectionModeDirect(maxRequestsPerTcpConnection) Max simultaneous requests multiplexed over a single TCP connection.
MaxTcpConnectionsPerEndpoint int? 65535 WithConnectionModeDirect(maxTcpConnectionsPerEndpoint) Max TCP connections opened to each backend replica.
PortReuseMode PortReuseMode? ReuseUnicastPort WithConnectionModeDirect(portReuseMode) Client port reuse policy: ReuseUnicastPort (OS-managed) or PrivatePortPool (SDK-managed).
EnableTcpConnectionEndpointRediscovery bool true WithConnectionModeDirect(enableTcpConnectionEndpointRediscovery) Refresh address cache when TCP connection-reset is detected.
WebProxy IWebProxy null WithConnectionModeGateway(webProxy:) HTTP proxy for Gateway mode connections.
HttpClientFactory Func<HttpClient> null WithHttpClientFactory() Factory delegate supplying a custom HttpClient for HTTPS calls.
ApplicationName string null WithApplicationName() Suffix appended to the SDK user-agent string sent with every request.
CustomHandlers Collection<RequestHandler> empty AddCustomHandlers() Pipeline handlers inserted before the transport layer (middleware pattern).

3. Retry & Timeout

Option Type Default Builder Method Description
RequestTimeout TimeSpan 6 seconds WithRequestTimeout() Per-request timeout for service calls.
MaxRetryAttemptsOnRateLimitedRequests int? 9 WithThrottlingRetryOptions(maxRetryAttempts) Max retries when a request is throttled (HTTP 429).
MaxRetryWaitTimeOnRateLimitedRequests TimeSpan? 30 seconds WithThrottlingRetryOptions(maxRetryWaitTime) Cumulative max wait time across all 429-retry attempts.

Internal Retry Details (RetryOptions — not publicly settable)

Internal Property Default Description
InitialRetryForRetryWithMilliseconds 1000 ms Initial back-off for RetryWith (449) responses.
MaximumRetryForRetryWithMilliseconds 30000 ms Cap for exponential back-off on 449 responses.
TotalWaitTimeForRetryWithMilliseconds 30000 ms Total budget for 449 retry wait.

SessionRetryOptions (Internal)

Internal Property Default Description
MinInRegionRetryTime 500 ms Minimum retry time for 404/1002 (read-session-not-available) within a region.
MaxInRegionRetryCount env-configurable Max retries within a single region for session-consistency errors.
RemoteRegionPreferred false Hint to prefer a remote region for session retries.

4. Consistency

Option Type Default Level Description
CosmosClientOptions.ConsistencyLevel ConsistencyLevel? null (account default) Client Weakens the account-level consistency for all reads through this client.
ItemRequestOptions.ConsistencyLevel ConsistencyLevel? null Request Per-request override for point reads/writes.
QueryRequestOptions.ConsistencyLevel ConsistencyLevel? null Request Per-query override.
StoredProcedureRequestOptions.ConsistencyLevel ConsistencyLevel? null Request Per-stored-procedure-execution override.
ReadManyRequestOptions.ConsistencyLevel ConsistencyLevel? null Request Per-ReadMany override.
TransactionalBatchRequestOptions.ConsistencyLevel ConsistencyLevel? null Request Per-batch override.

ConsistencyLevel enum values: Strong, BoundedStaleness, Session, Eventual, ConsistentPrefix.

Rule: You can only weaken consistency (e.g., from StrongSession), never strengthen it beyond the account level.


5. Serialization

CosmosClientOptions Serialization Properties

Option Type Default Builder Method Description
SerializerOptions CosmosSerializationOptions null WithSerializerOptions() Simple serializer knobs (see below).
Serializer CosmosSerializer null WithCustomSerializer() Provide a fully custom CosmosSerializer implementation.
UseSystemTextJsonSerializerWithOptions JsonSerializerOptions null WithSystemTextJsonSerializerOptions() Use System.Text.Json with the given options instead of the default Newtonsoft.Json.

Note: SerializerOptions, Serializer, and UseSystemTextJsonSerializerWithOptions are mutually exclusive — set only one.

CosmosSerializationOptions Properties

Property Type Default Description
IgnoreNullValues bool false Omit properties with null values during serialization.
Indented bool false Pretty-print JSON output.
PropertyNamingPolicy CosmosPropertyNamingPolicy Default Default (unchanged) or CamelCase.

CosmosLinqSerializerOptions

Property Type Default Description
PropertyNamingPolicy CosmosPropertyNamingPolicy Default Naming convention used when LINQ expressions are translated to Cosmos SQL.

6. Performance & Bulk Execution

Option Type Default Builder Method Level Description
AllowBulkExecution bool false WithBulkExecution(true) Client Enables optimistic batching — groups concurrent point operations into fewer service calls for higher throughput.
EnableContentResponseOnWrite bool? null WithContentResponseOnWrite() Client When false, write responses (Create/Upsert/Replace/Patch) return only headers (no body), saving bandwidth.
PriorityLevel PriorityLevel? null WithPriorityLevel() Client Sets default priority (High or Low) for Priority-Based Execution; Low requests are throttled first.

7. Region & Availability

Option Type Default Builder Method Description
ApplicationRegion string null WithApplicationRegion() Single preferred region (use Regions.* constants). Mutually exclusive with ApplicationPreferredRegions.
ApplicationPreferredRegions IReadOnlyList<string> null WithApplicationPreferredRegions() Ordered list of preferred regions for geo-replicated accounts.
LimitToEndpoint bool false WithLimitToEndpoint() Restrict all traffic to the single endpoint provided in the constructor.
AccountInitializationCustomEndpoints IEnumerable<Uri> null WithCustomAccountEndpoints() Custom private/VNET endpoints for account bootstrapping.
AvailabilityStrategy AvailabilityStrategy null WithAvailabilityStrategy() Cross-region hedging strategy for high-latency mitigation.

AvailabilityStrategy Factory Methods

Method Description
AvailabilityStrategy.CrossRegionHedgingStrategy(threshold, thresholdStep?, enableMultiWriteRegionHedge?) Creates a parallel-hedging strategy that sends the request to the next preferred region after threshold elapses.
AvailabilityStrategy.DisabledStrategy() Explicitly disables any availability strategy (useful as a per-request override).

CrossRegionHedgingAvailabilityStrategy Properties

Property Type Default Description
Threshold TimeSpan (required) Latency threshold that triggers the first hedge request.
ThresholdStep TimeSpan Threshold Interval between subsequent hedge attempts to additional regions.
EnableMultiWriteRegionHedge bool false Also hedge write operations (only effective on multi-write accounts).

8. Telemetry & Diagnostics

CosmosClientTelemetryOptions

Set via CosmosClientOptions.CosmosClientTelemetryOptions or WithClientTelemetryOptions().

Property Type Default Description
DisableSendingMetricsToService bool true When false, sends client telemetry metrics to the Cosmos DB service.
DisableDistributedTracing bool true (GA) / false (Preview) When false, the SDK emits System.Diagnostics.Activity traces for every operation.
CosmosThresholdOptions CosmosThresholdOptions new CosmosThresholdOptions() Threshold values that control when detailed diagnostics are attached to traces.
QueryTextMode QueryTextMode None Controls whether query text appears in traces: None, ParameterizedOnly, or All.
IsClientMetricsEnabled bool (unset) (Preview) Enable client-side metrics collection.
OperationMetricsOptions OperationMetricsOptions (unset) (Preview) Operation-level metrics dimensions.
NetworkMetricsOptions NetworkMetricsOptions (unset) (Preview) Network-level metrics dimensions.

CosmosThresholdOptions

Can be set at the client level (via telemetry options) or per-request (via RequestOptions.CosmosThresholdOptions).

Property Type Default Description
PointOperationLatencyThreshold TimeSpan 1 second Point operations exceeding this latency get full diagnostics in traces.
NonPointOperationLatencyThreshold TimeSpan 3 seconds Non-point operations (queries, feeds) exceeding this threshold get full diagnostics.
RequestChargeThreshold double? null Operations exceeding this RU charge get full diagnostics.
PayloadSizeThresholdInBytes int? null Operations exceeding this payload size get full diagnostics.

OperationMetricsOptions (Preview)

Property Type Default Description
IncludeRegion bool? null Include region as a dimension in operation metrics.
CustomDimensions IDictionary<string, string> null Additional custom dimensions for operation metrics.

NetworkMetricsOptions (Preview)

Property Type Default Description
IncludeRoutingId bool? null Include routing ID as a dimension in network metrics.
CustomDimensions IDictionary<string, string> null Additional custom dimensions for network metrics.

9. Request-Level Options (Base)

RequestOptions is the abstract base class inherited by all per-operation option types.

Property Type Default Description
IfMatchEtag string null Optimistic concurrency: operation succeeds only if the resource ETag matches.
IfNoneMatchEtag string null Conditional read: returns 304 Not Modified if ETag matches, or "*" to fail-create-if-exists.
Properties IReadOnlyDictionary<string, object> null Application context dictionary flowing through the request pipeline.
AddRequestHeaders Action<Headers> null Delegate to inject custom HTTP headers per request.
PriorityLevel PriorityLevel? null Per-request priority override (High / Low).
CosmosThresholdOptions CosmosThresholdOptions null Per-request diagnostics threshold override.
ExcludeRegions List<string> null Regions to exclude from routing for this specific request.
AvailabilityStrategy AvailabilityStrategy null Per-request availability strategy override (set DisabledStrategy() to opt out).

10. Item Request Options

ItemRequestOptions : RequestOptions — used for point CRUD operations (CreateItemAsync, ReadItemAsync, ReplaceItemAsync, DeleteItemAsync, UpsertItemAsync).

Property Type Default Description
ConsistencyLevel ConsistencyLevel? null Per-request consistency override.
SessionToken string null Explicit session token for session consistency.
IndexingDirective IndexingDirective? null Include, Exclude, or Default — controls whether this document is indexed.
PreTriggers IEnumerable<string> null Server-side triggers to run before the operation.
PostTriggers IEnumerable<string> null Server-side triggers to run after the operation.
EnableContentResponseOnWrite bool? null Override the client-level setting; false = headers-only response.
DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions null Integrated cache options (see §19).
(+ all base RequestOptions properties)

11. Patch Item Request Options

PatchItemRequestOptions : ItemRequestOptions — used for PatchItemAsync.

Property Type Default Description
FilterPredicate string null SQL-like condition (FROM root clause) evaluated before applying the patch; the patch is skipped if the predicate is false.
(+ all ItemRequestOptions properties)

12. Query Request Options

QueryRequestOptions : RequestOptions — used for GetItemQueryIterator, GetItemQueryStreamIterator, and LINQ queries.

Property Type Default Description
ConsistencyLevel ConsistencyLevel? null Per-query consistency override.
SessionToken string null Explicit session token.
MaxItemCount int? null Max items per page; -1 = server decides dynamically.
MaxBufferedItemCount int? null Max items buffered client-side during parallel query execution.
MaxConcurrency int? null Degree of parallelism; < 0 = system-determined.
PartitionKey PartitionKey? null Target a single logical partition (avoids cross-partition fan-out).
EnableScanInQuery bool? null Allow scans on paths not covered by an index.
EnableLowPrecisionOrderBy bool? null Use low-precision number comparison for ORDER BY.
EnableOptimisticDirectExecution bool false Skip query-plan step for simple single-partition queries.
PopulateIndexMetrics bool? null Return index utilization metrics in the response for query tuning.
PopulateQueryAdvice bool? null Return query optimization suggestions in the response.
ResponseContinuationTokenLimitInKb int? null Limit on continuation token size (≥ 0 KB).
DedicatedGatewayRequestOptions DedicatedGatewayRequestOptions null Integrated cache options (see §19).
QueryTextMode QueryTextMode None Whether query text is included in diagnostics/traces.
FullTextScoreScope FullTextScoreScope Global BM25 scoring scope: Global (across all partitions) or Local (per-partition).
(+ all base RequestOptions properties)

13. Change Feed Request Options

ChangeFeedRequestOptions : RequestOptions — used for GetChangeFeedIterator.

Property Type Default Description
PageSizeHint int? null Hint for max items per page (must be positive).
(+ all base RequestOptions properties except IfMatchEtag/IfNoneMatchEtag which throw NotSupportedException)

ChangeFeedMode (Static Properties)

Mode Description
ChangeFeedMode.LatestVersion (alias: Incremental) Receives item creations and updates only.
ChangeFeedMode.AllVersionsAndDeletes (Preview) Receives all versions, intermediate snapshots, and deletes. Requires ChangeFeedPolicy.FullFidelityRetention configured on the container.

ChangeFeedOperationType Enum

Value Description
Create Item was created.
Replace Item was replaced/updated.
Delete Item was deleted (AllVersionsAndDeletes mode only).

14. Change Feed Processor Options

Configured via Container.GetChangeFeedProcessorBuilder() and the fluent ChangeFeedProcessorBuilder API.

Builder Method Type / Parameters Default Description
WithInstanceName(string) string (required) Unique name for this processor instance (host identity).
WithLeaseContainer(Container) Container (required unless in-memory) Cosmos container that stores lease state.
WithInMemoryLeaseContainer() Use in-memory lease store (testing/dev only).
WithMaxItems(int) int null (server decides) Max items delivered per change feed poll batch.
WithPollInterval(TimeSpan) TimeSpan 5 seconds Delay between polls when no new changes are available.
WithStartTime(DateTime) DateTime (beginning) Exclusive start time for change feed processing.
WithLeaseConfiguration(acquireInterval, expirationInterval, renewInterval) TimeSpan × 3 13s / 60s / 17s Lease acquire interval, lease expiration, and lease renew interval.
WithErrorNotification(delegate) ChangeFeedMonitorErrorDelegate null Callback for unhandled errors.
WithLeaseAcquireNotification(delegate) ChangeFeedMonitorLeaseAcquireDelegate null Callback when a lease is acquired.
WithLeaseReleaseNotification(delegate) ChangeFeedMonitorLeaseReleaseDelegate null Callback when a lease is released.

ChangeFeedEstimatorRequestOptions

Used by the Change Feed Estimator (lag estimation).

Property Type Default Description
MaxItemCount int? null Max estimations per page.

15. ReadMany Request Options

ReadManyRequestOptions : RequestOptions — used for Container.ReadManyItemsAsync.

Property Type Default Description
ConsistencyLevel ConsistencyLevel? null Per-request consistency override.
SessionToken string null Explicit session token.
(+ all base RequestOptions properties)

16. Stored Procedure Request Options

StoredProcedureRequestOptions : RequestOptions — used for Scripts.ExecuteStoredProcedureAsync.

Property Type Default Description
ConsistencyLevel ConsistencyLevel? null Per-request consistency override.
SessionToken string null Explicit session token.
EnableScriptLogging bool false Capture console.log() output from the stored procedure.
(+ all base RequestOptions properties)

17. Transactional Batch Options

TransactionalBatchRequestOptions : RequestOptions

Used for Container.CreateTransactionalBatch().ExecuteAsync().

Property Type Default Description
ConsistencyLevel ConsistencyLevel? null Per-batch consistency override.
SessionToken string null Explicit session token.
(+ all base RequestOptions properties)

TransactionalBatchItemRequestOptions : RequestOptions

Per-item options within a batch.

Property Type Default Description
IndexingDirective IndexingDirective? null Per-item indexing override.
EnableContentResponseOnWrite bool? null Per-item content-on-write override.
(+ all base RequestOptions properties)

TransactionalBatchPatchItemRequestOptions : TransactionalBatchItemRequestOptions

Per-item options for patch operations within a batch.

Property Type Default Description
FilterPredicate string null SQL predicate evaluated before applying the patch.
(+ all TransactionalBatchItemRequestOptions properties)

18. Container Request Options

ContainerRequestOptions : RequestOptions — used for Container.ReadContainerAsync, DeleteContainerAsync, etc.

Property Type Default Description
PopulateQuotaInfo bool false Include storage/count quota information in the response headers.
(+ all base RequestOptions properties)

19. Dedicated Gateway Options

DedicatedGatewayRequestOptions — configures the integrated cache on dedicated gateway tier.

Property Type Default Description
MaxIntegratedCacheStaleness TimeSpan? null Maximum allowed staleness for cached results (millisecond granularity).
BypassIntegratedCache bool? null When true, bypass the integrated cache and always read from the backend.

20. Container Properties & Policies

ContainerProperties — set at container creation or replacement time.

Property Type Default Description
Id string (required) Container identifier.
PartitionKeyPath string (required) JSON path used for partitioning (e.g., "/tenantId").
PartitionKeyPaths IReadOnlyList<string> null Multiple paths for hierarchical (sub-)partitioning.
PartitionKeyDefinitionVersion PartitionKeyDefinitionVersion? null V1 (100-byte hash) or V2 (2 KB hash, recommended).
DefaultTimeToLive int? null Default TTL in seconds. null = TTL disabled. -1 = items never expire but TTL is enabled. Positive = default expiry.
AnalyticalStoreTimeToLiveInSeconds int? null Retention for analytical store (Synapse Link). -1 = infinite.
IndexingPolicy IndexingPolicy (new default) See §21.
UniqueKeyPolicy UniqueKeyPolicy (empty) Unique constraints (set of UniqueKey objects, each with paths).
ConflictResolutionPolicy ConflictResolutionPolicy LastWriterWins See §24.
ClientEncryptionPolicy ClientEncryptionPolicy null See §25.
VectorEmbeddingPolicy VectorEmbeddingPolicy null See §22.
ComputedProperties Collection<ComputedProperty> (empty) Computed properties derived via SQL expressions.
FullTextPolicy FullTextPolicy null See §23.
ChangeFeedPolicy ChangeFeedPolicy (new default) See §26.
GeospatialConfig GeospatialConfig Geography Geography (round-earth WGS-84) or Geometry (Euclidean).
ETag string (read-only) Concurrency ETag.
LastModified DateTime? (read-only) Last modification time.
SelfLink string (read-only) Addressable URI.

ComputedProperty

Property Type Description
Name string Computed property name (must not collide with stored properties).
Query string SQL expression, e.g. "SELECT VALUE LOWER(c.name) FROM c".

21. Indexing Policy

IndexingPolicy — set via ContainerProperties.IndexingPolicy.

Property Type Default Description
Automatic bool true Automatically index all document properties.
IndexingMode IndexingMode Consistent Consistent (synchronous), Lazy (async, deprecated), or None (no indexing).
IncludedPaths Collection<IncludedPath> (empty) JSON paths to include in the index (default includes /*).
ExcludedPaths Collection<ExcludedPath> (empty) JSON paths to exclude from the index.
CompositeIndexes Collection<Collection<CompositePath>> (empty) Composite indexes for multi-property ORDER BY / filters.
SpatialIndexes Collection<SpatialPath> (empty) Spatial index definitions (geography/geometry).
VectorIndexes Collection<VectorIndexPath> (empty) Vector indexes for similarity search.
FullTextIndexes Collection<FullTextIndexPath> (empty) Full-text search indexes.

CompositePath

Property Type Description
Path string JSON path.
Order CompositePathSortOrder Ascending or Descending.

VectorIndexPath

Property Type Description
Path string JSON path to the vector property.
Type VectorIndexType Flat, DiskANN, or QuantizedFlat.
QuantizerType string Quantizer type (for QuantizedFlat/DiskANN).
QuantizationByteSize int? Quantization byte size.
IndexingSearchListSize int? Search list size used during index build.
VectorIndexShardKey string Shard key for vector index.

FullTextIndexPath

Property Type Description
Path string JSON path for full-text indexing.

22. Vector Embedding & Search

VectorEmbeddingPolicy

Property Type Description
Embeddings Collection<Embedding> Collection of vector embedding definitions.

Embedding

Property Type Description
Path string JSON path to the embedding property.
DataType VectorDataType Float32, Float16, Uint8, or Int8.
Dimensions int Number of dimensions.
DistanceFunction DistanceFunction Cosine, Euclidean, or DotProduct.

23. Full-Text Search

FullTextPolicy

Property Type Default Description
DefaultLanguage string null Default language for text analysis (e.g. "en-US").
FullTextPaths Collection<FullTextPath> (empty) Paths configured for full-text search.

FullTextPath

Property Type Description
Path string JSON path.
Language string Language override for this path.

24. Conflict Resolution Policy

Property Type Default Description
Mode ConflictResolutionMode LastWriterWins LastWriterWins or Custom.
ResolutionPath string null JSON path for LWW comparison (must be a numeric _ts-like property).
ResolutionProcedure string null Stored procedure path for Custom mode.

25. Client Encryption Policy

Property Type Default Description
PolicyFormatVersion int 1 1 = standard; 2 = required if encrypting partition key or id.
IncludedPaths IEnumerable<ClientEncryptionIncludedPath> (required) Paths to encrypt along with encryption settings.

EncryptionKeyWrapMetadata

Property Type Description
Type string Key resolver identifier.
Name string Customer managed key name.
Value string Key path / URL.
Algorithm string Wrap/unwrap algorithm name.

26. Change Feed Policy

Property Type Default Description
FullFidelityRetention TimeSpan TimeSpan.Zero (disabled) Retention window for AllVersionsAndDeletes change feed (minute granularity). TimeSpan.Zero = full-fidelity disabled.

27. Database Properties

DatabaseProperties — set at database creation time.

Property Type Default Description
Id string (required) Database identifier.
ETag string (read-only) Concurrency ETag.
LastModified DateTime? (read-only) Last modification time.
SelfLink string (read-only) Addressable URI.

28. Throughput Configuration

Throughput is set at database or container level via ThroughputProperties.

Factory Methods

Method Description
ThroughputProperties.CreateManualThroughput(int throughput) Fixed provisioned RU/s.
ThroughputProperties.CreateAutoscaleThroughput(int autoscaleMaxThroughput) Autoscale with a max RU/s ceiling (scales down to 10% of max).

ThroughputProperties (Read Properties)

Property Type Description
Throughput int? Current provisioned RU/s (manual mode).
AutoscaleMaxThroughput int? Max RU/s ceiling (autoscale mode).
ETag string Concurrency ETag for throughput offers.
LastModified DateTime? Last modification time.

29. Patch Operations

PatchOperation static factory methods for building patch specifications:

Method Description
PatchOperation.Add<T>(string path, T value) Add a new property or array element.
PatchOperation.Remove(string path) Remove a property.
PatchOperation.Replace<T>(string path, T value) Replace an existing property (fails if absent).
PatchOperation.Set<T>(string path, T value) Set a property (creates if absent, replaces if present).
PatchOperation.Increment(string path, long value) Atomically increment by a long.
PatchOperation.Increment(string path, double value) Atomically increment by a double.
PatchOperation.Move(string from, string path) Move a value from one path to another.

30. Environment Variables

The SDK reads several environment variables via its internal ConfigurationManager for advanced tuning:

Environment Variable Default Description
AZURE_COSMOS_REPLICA_VALIDATION_ENABLED false Enable advanced replica selection/validation for TCP.
AZURE_COSMOS_PARTITION_LEVEL_FAILOVER_ENABLED false Enable partition-level failover.
AZURE_COSMOS_CIRCUIT_BREAKER_ENABLED false Enable partition-level circuit breaker.
AZURE_COSMOS_PPCB_STALE_PARTITION_UNAVAILABILITY_REFRESH_INTERVAL_IN_SECONDS (internal) Refresh interval for stale partition unavailability data.
AZURE_COSMOS_PPCB_ALLOWED_PARTITION_UNAVAILABILITY_DURATION_IN_SECONDS (internal) Allowed duration before a partition is marked unavailable.
AZURE_COSMOS_PPCB_CONSECUTIVE_FAILURE_COUNT_FOR_READS (internal) Consecutive read failures to trip the circuit breaker.
AZURE_COSMOS_PPCB_CONSECUTIVE_FAILURE_COUNT_FOR_WRITES (internal) Consecutive write failures to trip the circuit breaker.
AZURE_COSMOS_PPCB_TIMEOUT_COUNTER_RESET_WINDOW_IN_MINUTES (internal) Window after which timeout counters reset.
AZURE_COSMOS_THIN_CLIENT_ENABLED false Enable thin client mode.
AZURE_COSMOS_AAD_SCOPE_OVERRIDE null Override the default AAD scope for token acquisition.
AZURE_COSMOS_OPTIMISTIC_DIRECT_EXECUTION_ENABLED false Enable optimistic direct execution for queries by default.
AZURE_COSMOS_HYBRID_SEARCH_QUERYPLAN_OPTIMIZATION_DISABLED false Disable hybrid search query plan optimization.
AZURE_COSMOS_DISTRIBUTED_QUERY_GATEWAY_ENABLED false Enable distributed query gateway mode.
AZURE_COSMOS_BINARY_ENCODING_ENABLED false Enable binary encoding for responses.
AZURE_COSMOS_TCP_CHANNEL_MULTIPLEX_ENABLED false Enable TCP channel multiplexing.
AZURE_COSMOS_BYPASS_QUERY_PARSING false Bypass client-side query parsing.

31. Key Enumerations

ConsistencyLevel

Value Description
Strong Linearizable reads; always returns the latest committed write.
BoundedStaleness Reads lag behind writes by at most K versions or T time.
Session Monotonic reads/writes within a single session (default for most accounts).
Eventual No ordering guarantee; highest availability and lowest latency.
ConsistentPrefix Reads never see out-of-order writes.

ConnectionMode

Value Description
Gateway Routes through HTTPS gateway on port 443.
Direct Connects directly to backend replicas via TCP.

PriorityLevel

Value Description
High (1) Default priority.
Low (2) Throttled first when throughput budget is exceeded.

IndexingMode

Value Description
Consistent Index updated synchronously with writes.
Lazy Index updated asynchronously (deprecated).
None No indexing.

IndexingDirective

Value Description
Default Use the container's indexing policy.
Include Force-index this document.
Exclude Skip indexing for this document.

PortReuseMode

Value Description
ReuseUnicastPort OS-managed port reuse (Windows Server 2016+).
PrivatePortPool SDK tracks and reuses a private pool of client ports.

VectorIndexType

Value Description
Flat Brute-force exact search.
DiskANN Disk-based approximate nearest neighbor.
QuantizedFlat Quantized flat index for reduced memory.

VectorDataType

Value Description
Float32 32-bit floating point.
Float16 16-bit floating point.
Uint8 Unsigned 8-bit integer.
Int8 Signed 8-bit integer.

DistanceFunction

Value Description
Cosine Cosine similarity (most common for text embeddings).
Euclidean L2 distance.
DotProduct Inner product.

GeospatialType

Value Description
Geography Round-earth (WGS-84) coordinate system.
Geometry Flat / Euclidean coordinate system.

CompositePathSortOrder

Value Description
Ascending Ascending sort.
Descending Descending sort.

ConflictResolutionMode

Value Description
LastWriterWins Highest _ts (or custom path) wins.
Custom Delegate to a user-defined stored procedure.

QueryTextMode

Value Description
None (0) Do not include query text in traces.
ParameterizedOnly (1) Include parameterized query text only.
All (2) Include all query text (may contain PII).

FullTextScoreScope

Value Description
Global BM25 statistics computed across all partitions.
Local BM25 statistics scoped to the partition key value.

ChangeFeedMode

Value Description
LatestVersion (alias: Incremental) Creations and last version of updates.
AllVersionsAndDeletes (Preview) All intermediate versions and deletes.

32. Cascading & Layering Behavior

The Cosmos DB .NET SDK employs a layered configuration model where certain options set at a higher level serve as defaults that can be overridden at lower levels.

Consistency Level

Account Level (Azure Portal)
  └─► CosmosClientOptions.ConsistencyLevel        (client-level weakening)
        └─► ItemRequestOptions.ConsistencyLevel    (per-request override)
        └─► QueryRequestOptions.ConsistencyLevel   (per-query override)
        └─► StoredProcedureRequestOptions.ConsistencyLevel
        └─► ReadManyRequestOptions.ConsistencyLevel
        └─► TransactionalBatchRequestOptions.ConsistencyLevel
  • Direction: Can only weaken (e.g., StrongSession), never strengthen beyond the account setting.
  • Inheritance: If the request-level option is null, the client-level option is used. If that is also null, the account-level default applies.

Priority Level

CosmosClientOptions.PriorityLevel          (client default)
  └─► RequestOptions.PriorityLevel         (per-request override on any operation)
  • Any request-level PriorityLevel takes precedence over the client default.

Content Response on Write

CosmosClientOptions.EnableContentResponseOnWrite     (client default)
  └─► ItemRequestOptions.EnableContentResponseOnWrite         (per-request)
  └─► TransactionalBatchItemRequestOptions.EnableContentResponseOnWrite  (per-batch-item)
  • Per-request setting overrides client default. null at any level means "use the level above."

Availability Strategy

CosmosClientOptions.AvailabilityStrategy    (client default)
  └─► RequestOptions.AvailabilityStrategy   (per-request override)
  • Set AvailabilityStrategy.DisabledStrategy() at request level to opt out of a client-level strategy.

Diagnostics Thresholds

CosmosClientTelemetryOptions.CosmosThresholdOptions    (client default)
  └─► RequestOptions.CosmosThresholdOptions              (per-request override)
  • Per-request thresholds fully replace the client-level thresholds for that operation.

Region Exclusion

CosmosClientOptions.ApplicationPreferredRegions    (client-level region list)
  └─► RequestOptions.ExcludeRegions                 (per-request exclusion from that list)
  • ExcludeRegions removes specific regions from the preferred list for a single request.

Session Token

SDK manages session tokens automatically
  └─► ItemRequestOptions.SessionToken               (explicit override)
  └─► QueryRequestOptions.SessionToken
  └─► StoredProcedureRequestOptions.SessionToken
  └─► ReadManyRequestOptions.SessionToken
  └─► TransactionalBatchRequestOptions.SessionToken
  • Normally the SDK tracks session tokens internally. Explicit tokens are useful for cross-client session continuity.

Serialization

CosmosClientOptions (one of):
  ├── SerializerOptions (simple knobs)
  ├── Serializer (full custom)
  └── UseSystemTextJsonSerializerWithOptions (STJ)
  • Serialization is client-wide; there is no per-request override. The three options are mutually exclusive.

Indexing Directive

ContainerProperties.IndexingPolicy          (container default)
  └─► ItemRequestOptions.IndexingDirective  (per-document override)
  └─► TransactionalBatchItemRequestOptions.IndexingDirective
  • Include / Exclude on a request overrides the container's automatic indexing for that specific document.

Summary Table

Option Client Request Direction
ConsistencyLevel Request overrides client (weaken only)
PriorityLevel Request overrides client
EnableContentResponseOnWrite Request overrides client
AvailabilityStrategy Request overrides client
CosmosThresholdOptions Request replaces client
ExcludeRegions Request-only (subtracts from client regions)
SessionToken Request-only (SDK manages automatically)
IndexingDirective Request-only (overrides container policy per-doc)
Serialization Client-only (no per-request override)
ConnectionMode / TCP settings Client-only
Retry / Timeout Client-only
Bulk Execution Client-only
Telemetry options Client-only (thresholds cascade to request)

Generated from source analysis of Microsoft.Azure.Cosmos SDK v3 in azure-cosmos-dotnet-v3.

Azure Cosmos DB Go SDK — Comprehensive Options & Settings Reference

This document catalogs every configurable option in the azcosmos Go SDK package (sdk/data/azcosmos), grouped by purpose. It covers client-level, database-level, container-level, and request-level settings, including options inherited from the Azure Core (azcore) library.


Table of Contents

  1. Client-Level Options (ClientOptions)
  2. Inherited Azure Core Options (embedded azcore.ClientOptions)
  3. Consistency Level
  4. Item Operation Options (ItemOptions)
  5. Query Options (QueryOptions)
  6. Change Feed Options (ChangeFeedOptions)
  7. Transactional Batch Options
  8. Read Many Options (ReadManyOptions)
  9. Dedicated Gateway Options (DedicatedGatewayRequestOptions)
  10. Database Operation Options
  11. Container Operation Options
  12. Throughput Configuration
  13. Change Feed Range Options (ChangeFeedRangeOptions)
  14. Container Properties (Schema Configuration)
  15. Cosmos-Level Retry Policy (Internal)
  16. Authentication Options
  17. Cascading / Layering Behavior

1. Client-Level Options (ClientOptions)

Passed to NewClient, NewClientWithKey, or NewClientFromConnectionString. These settings apply to all operations performed by that client instance.

Field Type Default Description
EnableContentResponseOnWrite bool false When false, write responses contain a null resource body, reducing network/CPU load.
PreferredRegions []string nil (empty) Ordered list of Azure regions for failover. The client tries these in order if the default region is unavailable.

Struct definition: cosmos_client_options.go


2. Inherited Azure Core Options (embedded azcore.ClientOptions)

ClientOptions embeds azcore.ClientOptions (from sdk/azcore/policy), providing access to all standard Azure SDK pipeline configuration. These are set at the client level.

2.1 Top-Level Fields

Field Type Default Description
APIVersion string SDK-defined Overrides the default service API version. Use with caution.
Cloud cloud.Configuration Azure Public Cloud Cloud environment configuration (authority host, service endpoints).
InsecureAllowCredentialWithHTTP bool false Allows authenticated requests over plain HTTP. WARNING: sends credentials in clear text.
TracingProvider tracing.Provider No-op tracer Distributed tracing provider for OpenTelemetry or similar.
Transport policy.Transporter Default HTTP client Custom HTTP transport / client implementation.
PerCallPolicies []policy.Policy nil Custom pipeline policies executed once per request.
PerRetryPolicies []policy.Policy nil Custom pipeline policies executed once per request and for each retry attempt.

2.2 Logging Options (Logging field — policy.LogOptions)

Field Type Default Description
IncludeBody bool false Include request/response bodies in logs. WARNING: may disclose sensitive data.
AllowedHeaders []string nil HTTP headers whose values are logged un-redacted. All others are redacted.
AllowedQueryParams []string nil URL query parameters whose values are logged un-redacted. All others are redacted.

2.3 Retry Options (Retry field — policy.RetryOptions)

These control the Azure Core-level HTTP retry policy (distinct from the Cosmos-level cross-region retry; see Section 15).

Field Type Default Description
MaxRetries int32 3 Maximum number of retry attempts for a failed HTTP request. Negative values mean no retries.
TryTimeout time.Duration Disabled (0) Maximum time allowed for a single HTTP try. Set > 0 to enable.
RetryDelay time.Duration 800ms Initial delay before retrying. Increases exponentially up to MaxRetryDelay.
MaxRetryDelay time.Duration 60s Maximum delay between retries. Negative means no cap.
StatusCodes []int [408, 429, 500, 502, 503, 504] HTTP status codes that trigger a retry. Setting nil uses defaults; empty slice disables.
ShouldRetry func(*http.Response, error) bool nil Custom function to override default retry decision logic.

2.4 Telemetry Options (Telemetry field — policy.TelemetryOptions)

Field Type Default Description
ApplicationID string "" Application-specific string appended to User-Agent. Max 24 chars, no spaces.
Disabled bool false Disables all telemetry data in the User-Agent header.

3. Consistency Level

The ConsistencyLevel type (string) defines the data consistency guarantee for operations.

Constant Value Description
ConsistencyLevelStrong "Strong" Linearizable reads; highest consistency.
ConsistencyLevelBoundedStaleness "BoundedStaleness" Reads lag behind writes by at most a configured interval.
ConsistencyLevelSession "Session" Reads within a session are consistent with that session's writes (default for most accounts).
ConsistencyLevelEventual "Eventual" No ordering guarantee; lowest latency.
ConsistencyLevelConsistentPrefix "ConsistentPrefix" Reads never see out-of-order writes.

Consistency can be overridden at the request level (see Sections 4, 5, 7, 8) but can only be relaxed (never strengthened) from the account default.


4. Item Operation Options (ItemOptions)

Used for CRUD operations on individual items: CreateItem, ReadItem, ReplaceItem, UpsertItem, DeleteItem, PatchItem.

Field Type Default Description Level
PreTriggers []string nil Server-side triggers to invoke before the operation. Request
PostTriggers []string nil Server-side triggers to invoke after the operation. Request
SessionToken *string nil Explicit session token for session consistency. Required when distributing reads across nodes. Request
ConsistencyLevel *ConsistencyLevel nil (account default) Overrides account consistency level. Can only be relaxed. Request
IndexingDirective *IndexingDirective nil (Default) Controls whether the item is indexed. Values: Default, Include, Exclude. Request
EnableContentResponseOnWrite bool false When false, write responses contain a null resource body. Request
IfMatchEtag *azcore.ETag nil ETag for optimistic concurrency control. Operation fails if the resource's current ETag doesn't match. Request
DedicatedGatewayRequestOptions *DedicatedGatewayRequestOptions nil Options for the dedicated gateway integrated cache. See Section 9. Request

Struct definition: cosmos_item_request_options.go


5. Query Options (QueryOptions)

Used for NewQueryItemsPager on containers.

Field Type Default Description Level
SessionToken *string nil Explicit session token for session consistency. Request
ConsistencyLevel *ConsistencyLevel nil (account default) Overrides account consistency level. Can only be relaxed. Request
PopulateIndexMetrics bool false Returns index utilization metrics for query debugging. Incurs overhead; use only for diagnostics. Request
ResponseContinuationTokenLimitInKB int32 0 (no limit) Limits continuation token size in the response. Valid values: >= 0. Request
PageSizeHint int32 0 (service default) Maximum items per result page. Set to -1 for dynamic page sizing. The service may return fewer items. Request
EnableScanInQuery bool false Allows table scans when no suitable index exists for the query. Request
ContinuationToken *string nil Resumes a previous query from the given continuation token. Request
QueryParameters []QueryParameter nil Named parameters for parameterized SQL queries. Each has Name (string) and Value (any). Request
DedicatedGatewayRequestOptions *DedicatedGatewayRequestOptions nil Dedicated gateway integrated cache options. Request
EnableCrossPartitionQuery *bool nil (defaults to true) When true (or nil), enables cross-partition fan-out queries. Set to false to reject cross-partition queries. Request
QueryEngine queryengine.QueryEngine nil External query engine for cross-partition query processing. Preview feature — not production-supported. Request

Struct definition: cosmos_query_request_options.go


6. Change Feed Options (ChangeFeedOptions)

Used for NewChangeFeedPager on containers.

Field Type Default Description Level
MaxItemCount int32 0 (service default) Maximum items per page. Valid values: > 0. The service may return fewer. Request
StartFrom *time.Time nil Start reading changes from the specified UTC time. Sets the If-Modified-Since header. Request
PartitionKey *PartitionKey nil Read changes for a specific logical partition only. Request
FeedRange *FeedRange nil Read changes from a specific range of partition key values. Request
Continuation *string nil Resume change feed processing from a composite continuation token. Request

Struct definition: cosmos_change_feed_request_options.go


7. Transactional Batch Options

7.1 TransactionalBatchOptions

Used for ExecuteTransactionalBatch on containers.

Field Type Default Description Level
SessionToken string "" Explicit session token for session consistency. (Note: string, not *string.) Request
ConsistencyLevel *ConsistencyLevel nil (account default) Overrides account consistency level. Can only be relaxed. Request
EnableContentResponseOnWrite bool false When false, write operation results in the batch response have no body (reads still return bodies). Request

7.2 TransactionalBatchItemOptions

Per-item options within a transactional batch.

Field Type Default Description Level
IfMatchETag *azcore.ETag nil ETag for optimistic concurrency on this specific batch item. Request (per-item)

Struct definition: cosmos_transactional_batch_options.go


8. Read Many Options (ReadManyOptions)

Used for ReadManyItems on containers.

Field Type Default Description Level
SessionToken *string nil Explicit session token for session consistency. Request
ConsistencyLevel *ConsistencyLevel nil (account default) Overrides account consistency level. Can only be relaxed. Request
DedicatedGatewayRequestOptions *DedicatedGatewayRequestOptions nil Dedicated gateway integrated cache options. Request
QueryEngine queryengine.QueryEngine nil External query engine for processing. Preview — not production-supported. Request
MaxConcurrency *int32 nil (SDK auto-tunes) Maximum concurrent operations when reading many items. If unset, the SDK chooses an optimal value. Request

Struct definition: cosmos_read_many_request_options.go


9. Dedicated Gateway Options (DedicatedGatewayRequestOptions)

Configures behavior for the dedicated gateway integrated cache. Embedded in ItemOptions, QueryOptions, and ReadManyOptions.

Field Type Default Description Level
MaxIntegratedCacheStaleness *time.Duration nil (no staleness limit) Maximum acceptable staleness for cached responses. Applies to Eventual and Session consistency. Granularity: milliseconds (sub-ms values are ignored). Request
BypassIntegratedCache bool false When true, the request bypasses the integrated cache entirely (no cache reads or writes). Request

Struct definition: cosmos_dedicated_gateway_request_options.go


10. Database Operation Options

10.1 CreateDatabaseOptions

Field Type Default Description Level
ThroughputProperties *ThroughputProperties nil Optional throughput configuration for the new database. See Section 12. Database

10.2 ReadDatabaseOptions

Field Type Default Description Level
IfMatchEtag *azcore.ETag nil ETag for conditional read (If-Match). Request
IfNoneMatchEtag *azcore.ETag nil ETag for conditional read (If-None-Match). Returns 304 if unchanged. Request

10.3 DeleteDatabaseOptions

Field Type Default Description Level
IfMatchEtag *azcore.ETag nil ETag for conditional delete (If-Match). Request
IfNoneMatchEtag *azcore.ETag nil ETag for conditional delete (If-None-Match). Request

10.4 QueryDatabasesOptions

Field Type Default Description Level
ContinuationToken *string nil Resume a previous query from the given continuation token. Request
QueryParameters []QueryParameter nil Named parameters for parameterized queries. Request

Struct definition: cosmos_database_request_options.go


11. Container Operation Options

11.1 CreateContainerOptions

Field Type Default Description Level
ThroughputProperties *ThroughputProperties nil Optional throughput configuration for the new container. Container

11.2 ReadContainerOptions

Field Type Default Description Level
PopulateQuotaInfo bool false When true, the response headers include quota and usage information. Request

11.3 ReplaceContainerOptions

Empty struct — no configurable options.

11.4 DeleteContainerOptions

Empty struct — no configurable options.

11.5 QueryContainersOptions

Field Type Default Description Level
ContinuationToken *string nil Resume a previous query from the given continuation token. Request
QueryParameters []QueryParameter nil Named parameters for parameterized queries. Request

Struct definition: cosmos_container_request_options.go


12. Throughput Configuration

Throughput is configured via ThroughputProperties, which is set on CreateDatabaseOptions, CreateContainerOptions, or through ReadThroughput / ReplaceThroughput operations.

12.1 Throughput Constructors

Constructor Parameters Description
NewManualThroughputProperties(throughput int32) throughput — RU/s Fixed (manual) provisioned throughput.
NewAutoscaleThroughputProperties(startingMaxThroughput int32) startingMaxThroughput — max RU/s Autoscale mode with a maximum RU/s cap.
NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput, incrementPercentage int32) startingMaxThroughput — max RU/s, incrementPercentage — auto-upgrade % Autoscale with automatic max-throughput increase by a percentage.

12.2 ThroughputProperties Fields (read-only from responses)

Field Type Description
ETag *azcore.ETag Entity tag for concurrency control.
LastModified time.Time Last modification timestamp.

12.3 ThroughputOptions (for Read/Replace Throughput)

Field Type Default Description Level
IfMatchEtag *azcore.ETag nil ETag for conditional operation (If-Match). Request
IfNoneMatchEtag *azcore.ETag nil ETag for conditional operation (If-None-Match). Request

Struct definition: throughput_request_options.go, throughput_properties.go


13. Change Feed Range Options (ChangeFeedRangeOptions)

Used internally when constructing change feed ranges. Primarily for internal use.

Field Type Default Description Level
ContinuationToken *azcore.ETag nil Continue reading from a specific point in the change feed. Internal
EpkMinHeader *string nil Minimum inclusive partition key range header (effective partition key). Internal
EpkMaxHeader *string nil Maximum exclusive partition key range header (effective partition key). Internal

Struct definition: cosmos_change_feed_range.go


14. Container Properties (Schema Configuration)

When creating or replacing a container, the ContainerProperties struct defines the schema and policies. These are not "options structs" per se but are essential configuration.

14.1 ContainerProperties

Field Type Description
ID string Container identifier.
PartitionKeyDefinition PartitionKeyDefinition Partition key paths and kind (Hash or MultiHash).
DefaultTimeToLive *int32 Default TTL in seconds for items. nil = disabled, -1 = no expiry by default, > 0 = TTL value.
AnalyticalStoreTimeToLiveInSeconds *int32 TTL for the analytical store. nil = disabled, -1 = no expiry.
IndexingPolicy *IndexingPolicy Controls automatic indexing, included/excluded paths, spatial/composite/vector/full-text indexes.
UniqueKeyPolicy *UniqueKeyPolicy Enforces uniqueness constraints on specified paths within a logical partition.
ConflictResolutionPolicy *ConflictResolutionPolicy Conflict resolution mode (LastWriterWins or Custom) and resolution path/procedure.
VectorEmbeddingPolicy *VectorEmbeddingPolicy Defines vector embeddings (path, data type, distance function, dimensions) for vector search.
FullTextPolicy *FullTextPolicy Configures full-text search (default language, full-text paths).

14.2 IndexingPolicy

Field Type Description
Automatic bool Whether items are automatically indexed.
IndexingMode IndexingMode Consistent (synchronous) or None (no indexing).
IncludedPaths []IncludedPath Paths to include in indexing.
ExcludedPaths []ExcludedPath Paths to exclude from indexing.
SpatialIndexes []SpatialIndex Spatial index definitions (path + spatial types).
CompositeIndexes [][]CompositeIndex Composite index definitions (path + order: ascending/descending).
VectorIndexes []VectorIndex Vector index definitions (path + type: flat/quantizedFlat/diskANN).
FullTextIndexes []FullTextIndex Full-text index definitions (path).

14.3 VectorEmbedding

Field Type Values
Path string JSON path to the vector field.
DataType VectorDataType float32, int8, uint8
DistanceFunction VectorDistanceFunction cosine, dotproduct, euclidean
Dimensions int32 Number of dimensions in the vector.

14.4 FullTextPolicy

Field Type Description
DefaultLanguage string Language for full-text search (e.g., en-US, de-DE, es-ES, fr-FR).
FullTextPaths []FullTextPath Paths to index for full-text search, each with its own language override.

15. Cosmos-Level Retry Policy (Internal)

The SDK implements a Cosmos-specific cross-region retry policy that operates independently of (and in addition to) the Azure Core HTTP retry policy (Section 2.3). This is not directly configurable by users.

Constant / Behavior Value Description
maxRetryCount 120 Maximum cross-region retry attempts.
defaultBackoff 1 second Sleep duration between cross-region retries.
HTTP 403 + sub-status (write forbidden / account not found) Triggers endpoint failure retry; marks endpoint unavailable.
HTTP 404 + sub-status (read session not available) Triggers session unavailable retry; tries write endpoint or next available location.
HTTP 503 (Service Unavailable) Triggers preferred location retry; advances to next preferred region.
DNS resolution errors Triggers cross-region retry; marks both read and write endpoints unavailable.

Cross-region retries are only enabled when the location cache has enableCrossRegionRetries set to true (controlled by the number of available locations).


16. Authentication Options

Authentication is chosen at client construction time. The SDK does not expose a separate "authentication options" struct; instead, the constructor signature determines the auth mode.

Constructor Auth Type Credential Parameter
NewClient(endpoint, cred, opts) Azure AD (Token) azcore.TokenCredential — e.g., azidentity.DefaultAzureCredential
NewClientWithKey(endpoint, cred, opts) Shared Key KeyCredential — constructed via NewKeyCredential(key string)
NewClientFromConnectionString(connStr, opts) Shared Key (from connection string) Parses AccountEndpoint and AccountKey from the connection string

The Cloud field in ClientOptions (inherited from azcore.ClientOptions) determines the AAD authority host and service endpoint for token acquisition.


17. Cascading / Layering Behavior

The Cosmos DB Go SDK implements a layered configuration model where certain settings can be defined at a higher level and overridden at a lower level.

17.1 Option Inheritance Hierarchy

Account (server-side)
  └── ClientOptions (client-level)
       └── Per-Operation Options (request-level)

17.2 Cascading Rules

Setting Client-Level Request-Level Behavior
EnableContentResponseOnWrite ClientOptions.EnableContentResponseOnWrite ItemOptions.EnableContentResponseOnWrite, TransactionalBatchOptions.EnableContentResponseOnWrite Request-level overrides client-level. Both default to false. The client-level value is used if the request-level value is not explicitly set.
ConsistencyLevel Set on the Cosmos DB account (server-side) ItemOptions.ConsistencyLevel, QueryOptions.ConsistencyLevel, TransactionalBatchOptions.ConsistencyLevel, ReadManyOptions.ConsistencyLevel Request-level can only relax (weaken) the account-level consistency. E.g., an account with Strong can request Session or Eventual, but not the reverse.
SessionToken Managed internally by the client ItemOptions.SessionToken, QueryOptions.SessionToken, TransactionalBatchOptions.SessionToken, ReadManyOptions.SessionToken The client manages session tokens automatically. Override at the request level only when manually distributing sessions across nodes (e.g., behind a load balancer).
PreferredRegions ClientOptions.PreferredRegions Not overridable per-request Set once at client creation. Controls failover order for all operations.
DedicatedGatewayRequestOptions Not available at client level ItemOptions, QueryOptions, ReadManyOptions Must be set per-request. No client-level default.
Retry (Azure Core) ClientOptions.Retry Override per-call via policy.WithRetryOptions(ctx, opts) Azure Core allows per-call retry overrides through the context.
Throughput N/A CreateDatabaseOptions.ThroughputProperties, CreateContainerOptions.ThroughputProperties Set at database or container creation time. Modified later via ReplaceThroughput.
IndexingDirective Not available at client level ItemOptions.IndexingDirective Per-item control over whether the item participates in indexing.
Custom HTTP Headers N/A Via policy.WithHTTPHeader(ctx, headers) Azure Core allows injecting custom HTTP headers per-call through the context.

17.3 Context-Based Per-Call Overrides (from Azure Core)

Azure Core provides context-based mechanisms to override pipeline behavior on individual API calls:

Function Description
policy.WithRetryOptions(ctx, RetryOptions) Override retry settings for a single call.
policy.WithHTTPHeader(ctx, http.Header) Inject custom HTTP headers for a single call.
policy.WithCaptureResponse(ctx, **http.Response) Capture the raw HTTP response for inspection.

17.4 Summary Diagram

┌─────────────────────────────────────────────────────────┐
│  Account Level (Server-Side)                            │
│  • Default ConsistencyLevel                             │
│  • Regions & multi-write configuration                  │
├─────────────────────────────────────────────────────────┤
│  Client Level (ClientOptions)                           │
│  • EnableContentResponseOnWrite (default for all ops)   │
│  • PreferredRegions (failover order)                    │
│  • Azure Core: Retry, Logging, Telemetry, Transport     │
│  • Azure Core: Cloud, TracingProvider, Custom Policies   │
├─────────────────────────────────────────────────────────┤
│  Database / Container Level                             │
│  • ThroughputProperties (at creation or replace)        │
│  • ContainerProperties (schema, indexing, TTL, etc.)    │
├─────────────────────────────────────────────────────────┤
│  Request Level (per-operation Options structs)          │
│  • ConsistencyLevel (relaxation only)                   │
│  • SessionToken                                         │
│  • EnableContentResponseOnWrite (overrides client)      │
│  • DedicatedGatewayRequestOptions                       │
│  • IndexingDirective, ETag conditions, triggers         │
│  • Query-specific: PageSizeHint, parameters, etc.       │
│  • Context overrides: WithRetryOptions, WithHTTPHeader  │
└─────────────────────────────────────────────────────────┘

Azure Cosmos DB Java SDK — Comprehensive Configuration Reference

This document catalogs every user-configurable option exposed by the Azure Cosmos DB Java SDK v4 (com.azure:azure-cosmos). Options are grouped by purpose and annotated with the level at which they can be set (client, database, container, request) and their default values.

Source: sdk/cosmos/azure-cosmos in azure-sdk-for-java


Table of Contents

  1. Authentication
  2. Connection — General
  3. Connection — Direct Mode (DirectConnectionConfig)
  4. Connection — Gateway Mode (GatewayConnectionConfig)
  5. Connection — HTTP/2 (Http2ConnectionConfig)
  6. Region & Endpoint Configuration
  7. Consistency
  8. Retry & Timeout Policies
  9. Throttling Retry (ThrottlingRetryOptions)
  10. End-to-End Latency Policy
  11. Availability Strategy
  12. Session Retry (SessionRetryOptions)
  13. Non-Idempotent Write Retry
  14. Throughput / RU Configuration
  15. Throughput Control Groups
  16. Global Throughput Control
  17. Serialization
  18. Diagnostics & Thresholds
  19. Telemetry & Metrics (CosmosClientTelemetryConfig)
  20. Micrometer Metrics (CosmosMicrometerMetricsOptions)
  21. Per-Meter Options (CosmosMicrometerMeterOptions)
  22. Dedicated Gateway Cache
  23. Proactive Connection Initialization
  24. Operation Policies
  25. Container Properties
  26. Indexing Policy
  27. Vector Embedding & Index
  28. Full-Text Search
  29. Partition Key Configuration
  30. Unique Key Policy
  31. Change Feed Policy
  32. Conflict Resolution Policy
  33. Client Encryption Policy
  34. Computed Properties
  35. Request-Level Options — Point Operations (CosmosItemRequestOptions)
  36. Request-Level Options — Patch (CosmosPatchItemRequestOptions)
  37. Request-Level Options — Query (CosmosQueryRequestOptions)
  38. Request-Level Options — ReadMany (CosmosReadManyRequestOptions)
  39. Request-Level Options — Change Feed (CosmosChangeFeedRequestOptions)
  40. Request-Level Options — Batch (CosmosBatchRequestOptions)
  41. Request-Level Options — Batch Item (CosmosBatchItemRequestOptions)
  42. Request-Level Options — Batch Patch Item (CosmosBatchPatchItemRequestOptions)
  43. Request-Level Options — Bulk Execution (CosmosBulkExecutionOptions)
  44. Request-Level Options — Bulk Item (CosmosBulkItemRequestOptions)
  45. Request-Level Options — Bulk Patch Item (CosmosBulkPatchItemRequestOptions)
  46. Request-Level Options — Container (CosmosContainerRequestOptions)
  47. Request-Level Options — Database (CosmosDatabaseRequestOptions)
  48. Request-Level Options — Stored Procedures (CosmosStoredProcedureRequestOptions)
  49. Request-Level Options — Permissions (CosmosPermissionRequestOptions)
  50. Request-Level Options — Conflicts (CosmosConflictRequestOptions)
  51. Request-Level Options — Generic (CosmosRequestOptions)
  52. Change Feed Processor
  53. Change Feed Processor Options (ChangeFeedProcessorOptions)
  54. Enums & Constants Reference
  55. Cascading / Layering Behavior

1. Authentication

Set on CosmosClientBuilder. Exactly one authentication mechanism must be chosen.

Option Type Description Default
key(String) String Master or read-only account key
resourceToken(String) String Resource token scoped to a resource
credential(TokenCredential) TokenCredential Azure AD / Entra ID token credential
credential(AzureKeyCredential) AzureKeyCredential Rotatable key credential wrapper
permissions(List<CosmosPermissionProperties>) List<CosmosPermissionProperties> Permission list with resource tokens
authorizationTokenResolver(CosmosAuthorizationTokenResolver) CosmosAuthorizationTokenResolver Custom per-request token resolver

2. Connection — General

Set on CosmosClientBuilder.

Option Type Description Default
endpoint(String) String Account URI (e.g. https://<account>.documents.azure.com:443/) Required
directMode() Use Direct (TCP) connection mode with default config
directMode(DirectConnectionConfig) DirectConnectionConfig Direct mode with custom connection settings
directMode(DirectConnectionConfig, GatewayConnectionConfig) Both Direct mode + custom gateway config for metadata operations
gatewayMode() Use Gateway (HTTPS) connection mode with default config
gatewayMode(GatewayConnectionConfig) GatewayConnectionConfig Gateway mode with custom connection settings
userAgentSuffix(String) String Appended to the SDK User-Agent header ""
connectionSharingAcrossClientsEnabled(boolean) boolean Share TCP connections across multiple CosmosClient instances (first client's config wins) false
contentResponseOnWriteEnabled(boolean) boolean Return item body in write-operation responses false
sessionCapturingOverrideEnabled(boolean) boolean Capture session tokens even when not using SESSION consistency false

3. Connection — Direct Mode (DirectConnectionConfig)

Passed to CosmosClientBuilder.directMode(DirectConnectionConfig).

Option Type Description Default
setConnectTimeout(Duration) Duration Timeout for establishing a TCP connection 5 s
setIdleConnectionTimeout(Duration) Duration Idle timeout for individual connections (Duration.ZERO = disabled) Duration.ZERO
setIdleEndpointTimeout(Duration) Duration All connections to an endpoint closed after this idle duration 1 h
setMaxConnectionsPerEndpoint(int) int Connection pool size per endpoint 130
setMaxRequestsPerConnection(int) int Queued requests per connection 30
setNetworkRequestTimeout(Duration) Duration Timeout waiting for a response (range: 5–10 s) 5 s
setConnectionEndpointRediscoveryEnabled(boolean) boolean Rediscover endpoints to spread latency spikes during maintenance true

4. Connection — Gateway Mode (GatewayConnectionConfig)

Passed to CosmosClientBuilder.gatewayMode(GatewayConnectionConfig).

Option Type Description Default
setNetworkRequestTimeout(Duration) Duration Timeout waiting for an HTTP response (min 60 s) 60 s
setMaxConnectionPoolSize(int) int Maximum HTTP connection pool size 1000
setIdleConnectionTimeout(Duration) Duration Idle connection close timeout 60 s
setProxy(ProxyOptions) ProxyOptions HTTP proxy configuration (HTTP type only) null
setHttp2ConnectionConfig(Http2ConnectionConfig) Http2ConnectionConfig HTTP/2 connection config (Beta) default instance

5. Connection — HTTP/2 (Http2ConnectionConfig)

Nested inside GatewayConnectionConfig. Beta feature.

Option Type Description Default
setEnabled(Boolean) Boolean Enable HTTP/2 for gateway connections false
setMaxConnectionPoolSize(Integer) Integer Max live HTTP/2 connections 1000
setMinConnectionPoolSize(Integer) Integer Min live HTTP/2 connections (best-effort) 1
setMaxConcurrentStreams(Integer) Integer Max concurrent streams per connection 30

6. Region & Endpoint Configuration

Set on CosmosClientBuilder.

Option Type Description Default
preferredRegions(List<String>) List<String> Ordered list of preferred regions (e.g. "East US") null (use account default)
endpointDiscoveryEnabled(boolean) boolean Auto-discover read/write regions from the account true
multipleWriteRegionsEnabled(boolean) boolean Allow writes to any region (multi-master accounts) true
readRequestsFallbackEnabled(boolean) boolean Reads can fall back to other regions on failure true (false for Bounded Staleness)
excludedRegionsSupplier(Supplier<CosmosExcludedRegions>) Supplier<CosmosExcludedRegions> Dynamic supplier of regions to exclude from routing null

CosmosExcludedRegions

Constructor Parameter Type Description
excludedRegions Set<String> Immutable set of region names to exclude (normalized: lowercase, spaces removed)

7. Consistency

Option Type Level Description Default
consistencyLevel(ConsistencyLevel) ConsistencyLevel Client (builder) Override account-level consistency Account default
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Request Per-request consistency (can only weaken, not strengthen relative to account) null (inherit)
readConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Client (builder) Read-specific consistency strategy (Beta) null
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Request Per-request read consistency strategy (Beta); overrides setConsistencyLevel null (inherit)

ConsistencyLevel enum values

Value Description
STRONG Linearizable reads
BOUNDED_STALENESS Reads lag behind writes by at most K versions or T time
SESSION Monotonic reads/writes within a session
CONSISTENT_PREFIX Reads never see out-of-order writes
EVENTUAL No ordering guarantee

ReadConsistencyStrategy enum values (Beta)

Value Description
DEFAULT Defer to consistencyLevel / account setting
EVENTUAL Eventual consistency for reads
SESSION Session consistency for reads
LATEST_COMMITTED Reads the latest committed version
GLOBAL_STRONG Globally strong consistency for reads

8. Retry & Timeout Policies

Set on CosmosClientBuilder.

Option Type Description Default
throttlingRetryOptions(ThrottlingRetryOptions) ThrottlingRetryOptions Retry policy for 429 (throttled) responses default instance
endToEndOperationLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig End-to-end timeout + availability strategy null
sessionRetryOptions(SessionRetryOptions) SessionRetryOptions Retry behavior for 404/1002 (session not found) null
nonIdempotentWriteRetryOptions(NonIdempotentWriteRetryOptions) NonIdempotentWriteRetryOptions Enable retries for non-idempotent writes disabled

9. Throttling Retry (ThrottlingRetryOptions)

Option Type Description Default
setMaxRetryAttemptsOnThrottledRequests(int) int Max retry attempts on HTTP 429 (total attempts = value + 1) 9
setMaxRetryWaitTime(Duration) Duration Max cumulative retry wait time 30 s

10. End-to-End Latency Policy

Built via CosmosEndToEndOperationLatencyPolicyConfigBuilder.

Option Type Description Default
enable(boolean) boolean Enable/disable the policy true
constructor: endToEndOperationTimeout Duration Total allowed time for the operation including retries Required
availabilityStrategy(AvailabilityStrategy) AvailabilityStrategy Strategy for cross-region hedging null

11. Availability Strategy

ThresholdBasedAvailabilityStrategy (extends AvailabilityStrategy).

Option Type Description Default
constructor: threshold Duration Time to wait before sending hedged request to next region 500 ms
constructor: thresholdStep Duration Additional delay for each subsequent hedged region 100 ms

12. Session Retry (SessionRetryOptions)

Built via SessionRetryOptionsBuilder.

Option Type Description Default
regionSwitchHint(CosmosRegionSwitchHint) CosmosRegionSwitchHint LOCAL_REGION_PREFERRED or REMOTE_REGION_PREFERRED Required
minTimeoutPerRegion(Duration) Duration Minimum retry time within each region for 404/1002 500 ms
maxRetriesPerRegion(int) int Max retry count within each region 1

13. Non-Idempotent Write Retry

NonIdempotentWriteRetryOptions — set on builder or per-request.

Option Type Description Default
setEnabled(boolean) boolean Enable automatic retries for create/replace/upsert/delete false
setTrackingIdUsed(boolean) boolean Use /_trackingId system property to de-duplicate retries (avoids 409/412) false

Not supported for Batch, Bulk, or Stored Procedure operations.


14. Throughput / RU Configuration

ThroughputProperties — passed when creating/replacing databases or containers.

Factory Method Parameters Description
createManualThroughput(int) throughput (RU/s) Fixed provisioned throughput
createAutoscaledThroughput(int) autoScaleMaxThroughput (RU/s) Autoscale with specified max RU/s

15. Throughput Control Groups

Built via ThroughputControlGroupConfigBuilder.

Option Type Description Default
groupName(String) String Control group name Required
targetThroughput(int) int Target RU/s for the group (must be > 0) null
targetThroughputThreshold(double) double Throughput as percentage of provisioned (0, 1] null
priorityLevel(PriorityLevel) PriorityLevel HIGH or LOW priority for throttling null
defaultControlGroup(boolean) boolean Default group for requests without explicit assignment false
throughputBucket(int) int Throughput bucket ID (≥ 0) (Beta) null
continueOnInitError(boolean) boolean Fall back gracefully if controller init fails false

At least one of targetThroughput, targetThroughputThreshold, priorityLevel, or throughputBucket must be set.


16. Global Throughput Control

Built via GlobalThroughputControlConfigBuilder.

Option Type Description Default
setControlItemRenewInterval(Duration) Duration How often usage is reported and share rebalanced (min 5 s) 5 s
setControlItemExpireInterval(Duration) Duration Time to detect offline clients (min: 2 × renewInterval + 1 s) 11 s

17. Serialization

Option Type Level Description Default
customItemSerializer(CosmosItemSerializer) CosmosItemSerializer Client (builder) Custom POJO ↔ JSON serializer for all operations CosmosItemSerializer.DEFAULT_SERIALIZER
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Request Per-request serializer override null (inherit client)

CosmosItemSerializer is abstract; implement serialize(T)Map<String,Object> and deserialize(Map, Class<T>)T.


18. Diagnostics & Thresholds

CosmosDiagnosticsThresholds — set on client telemetry config or per-request.

Option Type Description Default
setPointOperationLatencyThreshold(Duration) Duration Latency threshold for point operations (CRUD) 1 s
setNonPointOperationLatencyThreshold(Duration) Duration Latency threshold for queries/feed operations 3 s
setRequestChargeThreshold(float) float RU threshold for emitting diagnostics 1000 RU
setPayloadSizeThreshold(int) int Response payload size threshold (bytes) Integer.MAX_VALUE
setFailureHandler(BiPredicate<Integer,Integer>) BiPredicate<Integer,Integer> Custom (statusCode, subStatusCode) → isFailure predicate Built-in (≥ 400 except 404/0, 409/0, 412/0, 429/3200)

19. Telemetry & Metrics (CosmosClientTelemetryConfig)

Set on CosmosClientBuilder.clientTelemetryConfig(…).

Option Type Description Default
metricsOptions(MetricsOptions) MetricsOptions / CosmosMicrometerMetricsOptions Metrics configuration Enabled if configured
clientCorrelationId(String) String Identifier to distinguish client instances in metrics Auto-incrementing number
diagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Client-wide diagnostic thresholds Default thresholds
tracingOptions(TracingOptions) TracingOptions OpenTelemetry distributed tracing options null
diagnosticsHandler(CosmosDiagnosticsHandler) CosmosDiagnosticsHandler Custom handler for diagnostics events null
enableTransportLevelTracing() Enable transport-level (TCP/HTTP) tracing false
showQueryMode(ShowQueryMode) ShowQueryMode Query text exposure in diagnostics: NONE, PARAMETERIZED, ALL NONE
sampleDiagnostics(double) double Sampling rate (0.0–1.0) for diagnostics Config-dependent

20. Micrometer Metrics (CosmosMicrometerMetricsOptions)

Option Type Description Default
meterRegistry(MeterRegistry) MeterRegistry Micrometer registry for publishing metrics Metrics.globalRegistry
configureDefaultTagNames(CosmosMetricTagName…) CosmosMetricTagName[] Default tags attached to all meters All applicable tags
configureDefaultPercentiles(double…) double[] Histogram percentiles to publish 0.95, 0.99
enableHistogramsByDefault(boolean) boolean Publish histograms for all meters true
applyDiagnosticThresholdsForTransportLevelMeters(boolean) boolean Filter transport-level meters by diagnostic thresholds false
setEnabled(boolean) boolean Enable/disable metrics collection Config-dependent
setMetricCategories(CosmosMetricCategory…) CosmosMetricCategory[] Set which metric categories to emit DEFAULT categories
addMetricCategories(CosmosMetricCategory…) CosmosMetricCategory[] Add additional categories
removeMetricCategories(CosmosMetricCategory…) CosmosMetricCategory[] Remove specific categories
configureMeter(CosmosMetricName, CosmosMicrometerMeterOptions) name + options Override options for a specific meter

21. Per-Meter Options (CosmosMicrometerMeterOptions)

Option Type Description Default
suppressTagNames(CosmosMetricTagName…) CosmosMetricTagName[] Tags to suppress for this meter null
enableHistograms(boolean) boolean Publish histogram for this meter Inherit parent
configurePercentiles(double…) double[] Percentiles for this meter Inherit parent
setEnabled(boolean) boolean Enable/disable this specific meter null (inherit)
applyDiagnosticThresholds(boolean) boolean Apply diagnostic thresholds to this meter Inherit parent

22. Dedicated Gateway Cache

DedicatedGatewayRequestOptions — set per-request.

Option Type Description Default
setMaxIntegratedCacheStaleness(Duration) Duration Max staleness for the integrated cache response null
setIntegratedCacheBypassed(boolean) boolean Bypass the integrated cache entirely false
setShardKey(String) String Shard key for dedicated gateway routing null

23. Proactive Connection Initialization

Built via CosmosContainerProactiveInitConfigBuilder.

Option Type Description Default
constructor: containerIdentities List<CosmosContainerIdentity> Containers to warm up Required
setProactiveConnectionRegionsCount(int) int Number of preferred regions to proactively connect to (max 5) 1
setAggressiveWarmupDuration(Duration) Duration Duration for aggressive (blocking) warmup before switching to defensive null

Set via CosmosClientBuilder.openConnectionsAndInitCaches(CosmosContainerProactiveInitConfig). Requires preferredRegions to be configured.


24. Operation Policies

Option Type Level Description
addOperationPolicy(CosmosOperationPolicy) CosmosOperationPolicy Client (builder) Functional interface (CosmosOperationDetails) → void invoked before each request; enables dynamic request modification

25. Container Properties

CosmosContainerProperties — set when creating/replacing a container.

Option Type Description Default
setId(String) String Container name Set in constructor
setPartitionKeyDefinition(PartitionKeyDefinition) PartitionKeyDefinition Partition key configuration Set in constructor
setIndexingPolicy(IndexingPolicy) IndexingPolicy Index configuration null
setUniqueKeyPolicy(UniqueKeyPolicy) UniqueKeyPolicy Unique key constraints null
setConflictResolutionPolicy(ConflictResolutionPolicy) ConflictResolutionPolicy How conflicts are resolved null
setChangeFeedPolicy(ChangeFeedPolicy) ChangeFeedPolicy Change feed behavior null
setDefaultTimeToLiveInSeconds(Integer) Integer Default TTL: null = disabled, -1 = never expire, > 0 = seconds null
setAnalyticalStoreTimeToLiveInSeconds(Integer) Integer Analytical store TTL: 0 = off, -1 = never expire 0
setComputedProperties(Collection<ComputedProperty>) Collection<ComputedProperty> Computed properties for queries null
setClientEncryptionPolicy(ClientEncryptionPolicy) ClientEncryptionPolicy Client-side encryption config null
setVectorEmbeddingPolicy(CosmosVectorEmbeddingPolicy) CosmosVectorEmbeddingPolicy Vector embedding configuration null
setFullTextPolicy(CosmosFullTextPolicy) CosmosFullTextPolicy Full-text search configuration null

26. Indexing Policy

IndexingPolicy — set on CosmosContainerProperties.

Option Type Description Default
setAutomatic(boolean) boolean Automatically index all documents true
setIndexingMode(IndexingMode) IndexingMode CONSISTENT, LAZY, or NONE CONSISTENT
setIncludedPaths(List<IncludedPath>) List<IncludedPath> Paths to include in indexing []
setExcludedPaths(List<ExcludedPath>) List<ExcludedPath> Paths to exclude from indexing []
setCompositeIndexes(List<List<CompositePath>>) List<List<CompositePath>> Composite indexes for multi-field ORDER BY []
setSpatialIndexes(List<SpatialSpec>) List<SpatialSpec> Spatial indexes for geo queries []
setVectorIndexes(List<CosmosVectorIndexSpec>) List<CosmosVectorIndexSpec> Vector similarity search indexes []
setCosmosFullTextIndexes(List<CosmosFullTextIndex>) List<CosmosFullTextIndex> Full-text search indexes []

CompositePath

Option Type Description Default
setPath(String) String JSON path null
setOrder(CompositePathSortOrder) CompositePathSortOrder ASCENDING or DESCENDING ASCENDING

27. Vector Embedding & Index

CosmosVectorEmbeddingPolicy

Option Type Description
setCosmosVectorEmbeddings(List<CosmosVectorEmbedding>) List<CosmosVectorEmbedding> Vector embedding definitions

CosmosVectorEmbedding

Option Type Description Default
setPath(String) String JSON path to embedding (e.g. "/vector") null
setDataType(CosmosVectorDataType) CosmosVectorDataType Data type (UINT8, INT8, FLOAT16, FLOAT32) null
setEmbeddingDimensions(Integer) Integer Number of dimensions (> 0) null
setDistanceFunction(CosmosVectorDistanceFunction) CosmosVectorDistanceFunction COSINE, EUCLIDEAN, or DOT_PRODUCT null

CosmosVectorIndexSpec

Option Type Description Default
setPath(String) String Index path null
setType(String) String "flat", "quantizedFlat", or "diskANN" null
setQuantizerType(QuantizerType) QuantizerType Quantizer for compression null
setQuantizationSizeInBytes(Integer) Integer Quantization byte size (1–512) 64
setIndexingSearchListSize(Integer) Integer DiskANN candidate list size (25–500) null
setVectorIndexShardKeys(List<String>) List<String> Shard keys for partitioning null

28. Full-Text Search

CosmosFullTextPolicy

Option Type Description Default
setDefaultLanguage(String) String Default language for full-text analysis null
setPaths(List<CosmosFullTextPath>) List<CosmosFullTextPath> Paths enabled for full-text search null

CosmosFullTextPath

Option Type Description Default
setPath(String) String JSON path (must start with '/') null
setLanguage(String) String Language override for this path null

CosmosFullTextIndex

Option Type Description Default
setPath(String) String Index path null

29. Partition Key Configuration

PartitionKeyDefinition

Option Type Description Default
setPaths(List<String>) List<String> Property paths forming the partition key []
setKind(PartitionKind) PartitionKind Partition algorithm (HASH) HASH
setVersion(PartitionKeyDefinitionVersion) PartitionKeyDefinitionVersion Key definition version null

30. Unique Key Policy

Option Type Description Default
setUniqueKeys(List<UniqueKey>) List<UniqueKey> List of unique key constraints []

Each UniqueKey has setPaths(List<String>) for the paths that must be unique together.


31. Change Feed Policy

Option Type Description Default
setRetentionDurationForAllVersionsAndDeletesPolicyInMinutes(Integer) Integer Retention window (minutes) for AllVersionsAndDeletes mode; null/0/negative = disabled null

32. Conflict Resolution Policy

Created via factory methods:

Factory Method Parameters Description
ConflictResolutionPolicy.createLastWriterWinsPolicy(String) conflictResolutionPath (e.g. "/_ts") Last-writer-wins using a given path
ConflictResolutionPolicy.createCustomPolicy(String) storedProcedurePath Custom conflict resolution via stored procedure
ConflictResolutionPolicy.createCustomPolicy() Custom policy with no stored procedure

33. Client Encryption Policy

Constructor Parameters Description Default
ClientEncryptionPolicy(List<ClientEncryptionIncludedPath>) paths Paths requiring encryption (format version 1)
ClientEncryptionPolicy(List<ClientEncryptionIncludedPath>, int) paths, policyFormatVersion Paths + version (1 or 2) version 1

ClientEncryptionIncludedPath

Option Type Description
setPath(String) String JSON path to encrypt
setClientEncryptionKeyId(String) String Encryption key ID
setEncryptionType(String) String "Deterministic" or "Randomized"
setEncryptionAlgorithm(String) String Algorithm (e.g. "AEAD_AES_256_CBC_HMAC_SHA256")

34. Computed Properties

ComputedProperty — immutable after construction.

Constructor Parameter Type Description
name String Property name
query String SQL expression defining the computation

35. Request-Level Options — Point Operations (CosmosItemRequestOptions)

Option Type Description Default
setIfMatchETag(String) String Optimistic concurrency ETag for replace/upsert/delete null
setIfNoneMatchETag(String) String Conditional read: 304 if match, "*" matches any null
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Per-request consistency override null (inherit)
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Per-request read consistency strategy (Beta) null
setIndexingDirective(IndexingDirective) IndexingDirective DEFAULT, INCLUDE, or EXCLUDE null
setPreTriggerInclude(List<String>) List<String> Pre-operation trigger IDs null
setPostTriggerInclude(List<String>) List<String> Post-operation trigger IDs null
setSessionToken(String) String Session token for session consistency null
setPartitionKey(PartitionKey) PartitionKey Target partition key null
setContentResponseOnWriteEnabled(Boolean) Boolean Return body in write responses (overrides client setting) null (inherit)
setNonIdempotentWriteRetryPolicy(boolean, boolean) two boolean Enable non-idempotent retries + tracking ID usage false, false
setDedicatedGatewayRequestOptions(DedicatedGatewayRequestOptions) DedicatedGatewayRequestOptions Integrated cache options null
setCosmosEndToEndOperationLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig Per-request E2E latency policy override null (inherit)
setExcludedRegions(List<String>) List<String> Regions to exclude for this request null
setThroughputControlGroupName(String) String Throughput control group null
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Per-request diagnostics threshold override null (inherit)
setThresholdForDiagnosticsOnTracer(Duration) Duration Latency threshold for OTel diagnostics export 100 ms
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-request serializer null (inherit)
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers {}

36. Request-Level Options — Patch (CosmosPatchItemRequestOptions)

Extends CosmosItemRequestOptions (inherits all options above) and adds:

Option Type Description Default
setFilterPredicate(String) String SQL WHERE clause for conditional patch (e.g. "from c where c.taskNum = 3") null

37. Request-Level Options — Query (CosmosQueryRequestOptions)

Option Type Description Default
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Per-query consistency null (inherit)
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Read consistency strategy (Beta) null
setSessionToken(String) String Session token null
setScanInQueryEnabled(Boolean) Boolean Allow scans when indexing is opted out null
setMaxDegreeOfParallelism(int) int Concurrent cross-partition query threads Implementation-specific
setMaxBufferedItemCount(int) int Max items buffered client-side during parallel query Implementation-specific
setResponseContinuationTokenLimitInKb(int) int Max continuation token size in KB (≥ 1) 0 (not set)
setCosmosEndToEndOperationLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig Per-query E2E latency policy null (inherit)
setExcludedRegions(List<String>) List<String> Excluded regions null
setPartitionKey(PartitionKey) PartitionKey Target partition (single-partition query) null
setQueryMetricsEnabled(boolean) boolean Include query execution metrics true
setIndexMetricsEnabled(boolean) boolean Include index utilization metrics false
setFeedRange(FeedRange) FeedRange Restrict query to a feed range null
setThroughputControlGroupName(String) String Throughput control group null
setDedicatedGatewayRequestOptions(DedicatedGatewayRequestOptions) DedicatedGatewayRequestOptions Integrated cache options null
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Per-query diagnostics thresholds null (inherit)
setThresholdForDiagnosticsOnTracer(Duration) Duration OTel latency threshold for diagnostics 500 ms
setQueryName(String) String Logical name for metrics/telemetry (keep cardinality < 100) null
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-query serializer null (inherit)
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers null

38. Request-Level Options — ReadMany (CosmosReadManyRequestOptions)

Option Type Description Default
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Per-request consistency null
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Read consistency strategy (Beta) null
setSessionToken(String) String Session token null
setResponseContinuationTokenLimitInKb(int) int Continuation token size limit (≥ 1 KB) 0
setCosmosEndToEndOperationLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig E2E latency policy null
setExcludedRegions(List<String>) List<String> Excluded regions null
setQueryMetricsEnabled(boolean) boolean Query execution metrics true
setIndexMetricsEnabled(boolean) boolean Index utilization metrics false
setThroughputControlGroupName(String) String Throughput control group null
setDedicatedGatewayRequestOptions(DedicatedGatewayRequestOptions) DedicatedGatewayRequestOptions Integrated cache options null
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Diagnostics thresholds null
setThresholdForDiagnosticsOnTracer(Duration) Duration OTel diagnostics latency threshold 500 ms
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-request serializer null
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers null

39. Request-Level Options — Change Feed (CosmosChangeFeedRequestOptions)

Created via factory methods:

Factory Method Parameters Description
createForProcessingFromBeginning(FeedRange) FeedRange Start from container beginning
createForProcessingFromNow(FeedRange) FeedRange Start from current point in time
createForProcessingFromContinuation(String) continuation token Resume from continuation
createForProcessingFromPointInTime(Instant, FeedRange) time + range Start from specific point in time
Option Type Description Default
setMaxItemCount(int) int Max items per page Implementation-specific
setMaxPrefetchPageCount(int) int Max pages prefetched asynchronously Implementation-specific
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Read consistency strategy (Beta) null
setQuotaInfoEnabled(boolean) boolean Include quota-related stats false
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Per-request diagnostics thresholds null
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-request serializer null
setCompleteAfterAllCurrentChangesRetrieved(boolean) boolean Complete feed after all current changes retrieved false
setThroughputControlGroupName(String) String Throughput control group null
setExcludedRegions(List<String>) List<String> Excluded regions null
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers {}

40. Request-Level Options — Batch (CosmosBatchRequestOptions)

Option Type Description Default
setSessionToken(String) String Session token null
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Consistency level null
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Diagnostics thresholds default instance
setExcludedRegions(List<String>) List<String> Excluded regions null
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-batch serializer null
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers {}

41. Request-Level Options — Batch Item (CosmosBatchItemRequestOptions)

Option Type Description Default
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null
setThroughputControlGroupName(String) String Throughput control group null

42. Request-Level Options — Batch Patch Item (CosmosBatchPatchItemRequestOptions)

Option Type Description Default
setFilterPredicate(String) String SQL WHERE clause for conditional patch null
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null

43. Request-Level Options — Bulk Execution (CosmosBulkExecutionOptions)

Option Type Description Default
setInitialMicroBatchSize(int) int Initial micro-batch size per flush 100
setMaxMicroBatchSize(int) int Max micro-batch size before flush Implementation-specific
setMaxMicroBatchConcurrency(int) int Max concurrency per partition key range (1–5) 1
setThroughputControlGroupName(String) String Throughput control group null
setExcludedRegions(List<String>) List<String> Excluded regions null
setCustomItemSerializer(CosmosItemSerializer) CosmosItemSerializer Per-bulk serializer null
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers {}
setEndToEndOperationLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig E2E latency policy null

44. Request-Level Options — Bulk Item (CosmosBulkItemRequestOptions)

Option Type Description Default
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null
setContentResponseOnWriteEnabled(Boolean) Boolean Return body in write responses null

45. Request-Level Options — Bulk Patch Item (CosmosBulkPatchItemRequestOptions)

Option Type Description Default
setFilterPredicate(String) String SQL WHERE clause for conditional patch null
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null
setContentResponseOnWriteEnabled(Boolean) Boolean Return body in write responses null

46. Request-Level Options — Container (CosmosContainerRequestOptions)

Option Type Description Default
setQuotaInfoEnabled(boolean) boolean Include quota stats in response false
setSessionToken(String) String Session token null
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null

47. Request-Level Options — Database (CosmosDatabaseRequestOptions)

Option Type Description Default
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null

48. Request-Level Options — Stored Procedures (CosmosStoredProcedureRequestOptions)

Option Type Description Default
setPartitionKey(PartitionKey) PartitionKey Target partition null
setSessionToken(String) String Session token null
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null
setScriptLoggingEnabled(boolean) boolean Enable JavaScript stored procedure logging false

49. Request-Level Options — Permissions (CosmosPermissionRequestOptions)

Option Type Description Default
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null

50. Request-Level Options — Conflicts (CosmosConflictRequestOptions)

Option Type Description Default
setPartitionKey(PartitionKey) PartitionKey Target partition null
setIfMatchETag(String) String Optimistic concurrency ETag null
setIfNoneMatchETag(String) String Conditional read ETag null

51. Request-Level Options — Generic (CosmosRequestOptions)

CosmosRequestOptions is a unified options bag usable across operation types (Beta).

Option Type Description Default
setCosmosEndToEndLatencyPolicyConfig(…) CosmosEndToEndOperationLatencyPolicyConfig E2E latency policy null
setConsistencyLevel(ConsistencyLevel) ConsistencyLevel Consistency override null
setReadConsistencyStrategy(ReadConsistencyStrategy) ReadConsistencyStrategy Read consistency strategy (Beta) null
setContentResponseOnWriteEnabled(Boolean) Boolean Return body in write responses null
setNonIdempotentWriteRetriesEnabled(Boolean) Boolean Non-idempotent write retries null
setDedicatedGatewayRequestOptions(DedicatedGatewayRequestOptions) DedicatedGatewayRequestOptions Integrated cache options null
setExcludeRegions(List<String>) List<String> Excluded regions null
setThroughputControlGroupName(String) String Throughput control group null
setDiagnosticsThresholds(CosmosDiagnosticsThresholds) CosmosDiagnosticsThresholds Diagnostics thresholds null
setScanInQueryEnabled(Boolean) Boolean Allow scans when indexing opted out null
setMaxDegreeOfParallelism(Integer) Integer Parallel query threads null
setMaxBufferedItemCount(Integer) Integer Max buffered items in parallel query null
setResponseContinuationTokenLimitInKb(Integer) Integer Continuation token size limit null
setMaxItemCount(Integer) Integer Max items per page null
setQueryMetricsEnabled(Boolean) Boolean Query execution metrics null
setIndexMetricsEnabled(Boolean) Boolean Index utilization metrics null
setMaxPrefetchPageCount(Integer) Integer Max prefetch pages null
setQueryName(String) String Logical query name for telemetry null
setKeywordIdentifiers(Set<String>) Set<String> Custom keyword identifiers {}

52. Change Feed Processor

ChangeFeedProcessorBuilder — builds a ChangeFeedProcessor.

Option Type Description
hostName(String) String Unique host name for multi-host coordination
feedContainer(CosmosAsyncContainer) CosmosAsyncContainer Monitored container
leaseContainer(CosmosAsyncContainer) CosmosAsyncContainer Lease container for coordination
handleChanges(Consumer<List<JsonNode>>) Consumer<List<JsonNode>> LatestVersion handler (legacy PK-based leases)
handleLatestVersionChanges(Consumer<List<ChangeFeedProcessorItem>>) Consumer<…> LatestVersion handler (EPK-based leases)
handleAllVersionsAndDeletesChanges(Consumer<…>) Consumer<…> AllVersionsAndDeletes handler
handleAllVersionsAndDeletesChanges(BiConsumer<…>) BiConsumer<…> AllVersionsAndDeletes with context
options(ChangeFeedProcessorOptions) ChangeFeedProcessorOptions Processing options (see below)

53. Change Feed Processor Options (ChangeFeedProcessorOptions)

Option Type Description Default
setLeaseRenewInterval(Duration) Duration How often held leases are renewed 17 s
setLeaseAcquireInterval(Duration) Duration How often partition distribution is checked 13 s
setLeaseExpirationInterval(Duration) Duration Lease expiry timeout (must be > renew interval) 60 s
setFeedPollDelay(Duration) Duration Delay between polls when no changes are available 5 s
setLeasePrefix(String) String Prefix for lease document IDs null
setMaxItemCount(int) int Max items per change feed page 100
setStartContinuation(String) String Resume from continuation token (overrides startTime) null
setStartTime(Instant) Instant Start reading changes from this time (exclusive) null
setStartFromBeginning(boolean) boolean Start from the beginning of the container false
setMinScaleCount(int) int Minimum parallel workers per host 0
setMaxScaleCount(int) int Maximum parallel workers per host (0 = unlimited) 0
setMaxLeasesToAcquirePerCycle(int) int Max leases acquired per load-balancing cycle (0 = legacy) 0
setScheduler(Scheduler) Scheduler Reactor scheduler for the executor pool Schedulers.boundedElastic()
setFeedPollThroughputControlConfig(ThroughputControlGroupConfig) ThroughputControlGroupConfig Throughput control for feed polling null
setLeaseVerificationEnabledOnRestart(boolean) boolean Check for missing leases on restart false

54. Enums & Constants Reference

ConnectionMode

Value Description
DIRECT TCP-based direct connectivity to replicas
GATEWAY HTTPS through the Cosmos DB gateway

ConsistencyLevel

STRONG, BOUNDED_STALENESS, SESSION, CONSISTENT_PREFIX, EVENTUAL

ReadConsistencyStrategy (Beta)

DEFAULT, EVENTUAL, SESSION, LATEST_COMMITTED, GLOBAL_STRONG

IndexingMode

Value Description
CONSISTENT Indexes updated synchronously with writes
LAZY Indexes updated asynchronously (deprecated)
NONE No indexing

IndexingDirective

DEFAULT, INCLUDE, EXCLUDE

PriorityLevel

HIGH, LOW

CosmosRegionSwitchHint

LOCAL_REGION_PREFERRED, REMOTE_REGION_PREFERRED

ShowQueryMode

NONE, PARAMETERIZED, ALL

CosmosMetricCategory

ALL, DEFAULT, MINIMUM, OPERATION_SUMMARY, OPERATION_DETAILS, REQUEST_SUMMARY, REQUEST_DETAILS, DIRECT_ADDRESS_RESOLUTIONS, DIRECT_CHANNELS, DIRECT_ENDPOINTS, DIRECT_REQUESTS, SYSTEM, LEGACY

CosmosMetricTagName

ALL, DEFAULT, MINIMUM, CONSISTENCY_LEVEL, CONTAINER, SERVICE_ENDPOINT, SERVICE_ADDRESS, PARTITION_ID, REPLICA_ID, REGION_NAME, OPERATION_STATUS_CODE, OPERATION_SUB_STATUS_CODE, OPERATION, REQUEST_STATUS_CODE, REQUEST_OPERATION_TYPE, CLIENT_CORRELATION_ID, ADDRESS_RESOLUTION_FORCED_REFRESH, ADDRESS_RESOLUTION_COLLECTION_MAP_REFRESH, PARTITION_KEY_RANGE_ID

CompositePathSortOrder

ASCENDING, DESCENDING

PartitionKind

HASH

ConflictResolutionMode

LAST_WRITER_WINS, CUSTOM, INVALID

CosmosVectorDataType

UINT8, INT8, FLOAT16, FLOAT32

CosmosVectorDistanceFunction

COSINE, EUCLIDEAN, DOT_PRODUCT

CosmosVectorIndexType

FLAT, QUANTIZED_FLAT, DISK_ANN

QuantizerType

Used in CosmosVectorIndexSpec for vector quantization compression.


55. Cascading / Layering Behavior

The Cosmos DB Java SDK uses a multi-level configuration model where settings at a more specific level override broader settings. The cascade order from broadest to most specific is:

Account Default → Client (Builder) → Request Options

Options that cascade (client → request)

Setting Client-Level API Request-Level Override
Consistency Level CosmosClientBuilder.consistencyLevel() setConsistencyLevel() on item/query/batch/readMany request options
Read Consistency Strategy CosmosClientBuilder.readConsistencyStrategy() setReadConsistencyStrategy() on item/query/changeFeed/readMany request options
Content Response on Write CosmosClientBuilder.contentResponseOnWriteEnabled() setContentResponseOnWriteEnabled() on item/bulk request options
End-to-End Latency Policy CosmosClientBuilder.endToEndOperationLatencyPolicyConfig() setCosmosEndToEndOperationLatencyPolicyConfig() on item/query/readMany/bulk request options
Non-Idempotent Write Retry CosmosClientBuilder.nonIdempotentWriteRetryOptions() setNonIdempotentWriteRetryPolicy() on CosmosItemRequestOptions
Excluded Regions CosmosClientBuilder.excludedRegionsSupplier() setExcludedRegions() on item/query/changeFeed/batch/bulk/readMany request options
Diagnostics Thresholds CosmosClientTelemetryConfig.diagnosticsThresholds() setDiagnosticsThresholds() on item/query/changeFeed/batch/readMany request options
Custom Item Serializer CosmosClientBuilder.customItemSerializer() setCustomItemSerializer() on item/query/changeFeed/batch/bulk/readMany request options

Precedence rules

  1. Request-level options always win when explicitly set (non-null).
  2. Client-level options act as defaults when request-level options are null.
  3. Account defaults apply when neither client nor request level specifies a value (e.g., consistency level defaults to the account-level setting).
  4. Consistency level can only be weakened at the request level (e.g., account = Strong, request = Eventual is allowed; account = Eventual, request = Strong is not allowed). The ReadConsistencyStrategy (Beta) relaxes this restriction.
  5. ReadConsistencyStrategy overrides ConsistencyLevel unless the strategy is DEFAULT.
  6. Connection configuration (DirectConnectionConfig, GatewayConnectionConfig) is set once at client creation and cannot be overridden per-request.
  7. Region preferences are set at the client level; per-request only allows excluding regions from the preferred list.
  8. Throughput control group can be set at the client level as a default group and overridden per-request via setThroughputControlGroupName().
  9. When connectionSharingAcrossClientsEnabled is true, the first client's connection configuration applies to all subsequent clients sharing that connection pool.

Container-level vs. request-level properties

Container-level properties (indexing policy, TTL, partition key, unique keys, conflict resolution, change feed policy, encryption policy, vector/full-text policies) are set when creating or replacing a container and apply to all operations on that container. They cannot be overridden per-request, with the exception of:

  • IndexingDirective on CosmosItemRequestOptions — overrides whether a specific document write is indexed.
  • ThroughputProperties — throughput can be changed at the database or container level independently.

Generated from source analysis of com.azure:azure-cosmos in azure-sdk-for-java.

Azure Cosmos DB Python SDK — Comprehensive Configuration Options Report

This document catalogs every configurable option/setting available in the azure-cosmos Python SDK. Options are grouped by purpose and annotated with the level(s) at which they can be set, their types, defaults, and descriptions.

Levels:

  • Client – Set on CosmosClient.__init__ (applies to all requests made by that client).
  • Database – Set on DatabaseProxy operations.
  • Container-Def – Set when creating/replacing a container definition (schema-level settings).
  • Operation – Set per-request via keyword arguments on individual methods (e.g., read_item, query_items).

1. Authentication

Option Type Default Level Description
credential (positional) str | dict | TokenCredential | Iterable[Mapping] (required) Client The master key (string), resource token dict, permission feed, or an AAD TokenCredential.
url (positional) str (required) Client The Cosmos DB account endpoint URL.
conn_str str Client (from_connection_string) Connection string containing AccountEndpoint and AccountKey.

Credential sub-types resolved internally

Auth dict key Meaning
masterKey Account master key (string credential).
resourceTokens Dictionary mapping resource IDs to tokens.
permissionFeed Iterable of permission dicts (each containing resource and _token).
clientSecretCredential Any azure.core.credentials.TokenCredential instance (AAD).

2. Consistency

Option Type Default Level Description
consistency_level str (one of ConsistencyLevel values) None (account default) Client, Operation (read_items) The consistency level for operations. Must be equal to or weaker than the account-level setting. Values: "Strong", "BoundedStaleness", "Session", "ConsistentPrefix", "Eventual".
session_token str None Operation A session token for use with Session consistency. Accepted on item-level operations (read_item, create_item, replace_item, upsert_item, patch_item, delete_item, read_items, read_all_items, query_items, execute_item_batch, delete_all_items_by_partition_key).

3. Connection & Network

Option Type Default Level Description
connection_timeout int (seconds) 5 Client HTTP request timeout (connection phase). Replaces deprecated request_timeout.
request_timeout (deprecated) int (ms) Client Legacy connection timeout in milliseconds; converted to seconds internally.
timeout int (seconds) Operation Absolute timeout for the combined HTTP request + response processing. Passed through **kwargs on any operation.
read_timeout int (seconds) 65 Client (via ConnectionPolicy.ReadTimeout) Socket read timeout for data operations.
connection_mode str (e.g., "Gateway") ConnectionMode.Gateway (0) Client Connection mode. Currently only Gateway is supported.
proxy_config ProxyConfiguration None Client Proxy host/port configuration. ProxyConfiguration.Host and .Port.
proxies dict {} Client Raw proxy dict passed to the HTTP transport.
ssl_config SSLConfiguration None Client SSL key file, cert file, and CA bundle paths.
connection_verify bool True Client Whether to verify SSL certificates. False disables verification (emulator only).
connection_cert str None Client Alternative certificate file path for SSL verification.
connection_policy ConnectionPolicy ConnectionPolicy() Client A pre-built ConnectionPolicy object. If supplied, individual connection kwargs override its fields.
enable_endpoint_discovery bool True Client Enables automatic discovery of read/write endpoints for geo-replicated accounts.
transport HTTP transport None Client Custom HTTP transport passed to PipelineClient.

ConnectionPolicy fields (set via ConnectionPolicy object or extracted from kwargs)

Field Type Default Description
RequestTimeout int (seconds) 5 Connection timeout for all operations except database account reads.
DBAConnectionTimeout int (seconds) 3 Connection timeout for database account reads.
ReadTimeout int (seconds) 65 Socket read timeout.
RecoveryReadTimeout int (seconds) 6 Read timeout when recovering an unavailable partition (circuit breaker only).
DBAReadTimeout int (seconds) 3 Read timeout for database account reads.
MaxBackoff int (seconds) 1 Maximum backoff time.
ConnectionMode int 0 (Gateway) Connection mode.
SSLConfiguration SSLConfiguration None SSL settings.
ProxyConfiguration ProxyConfiguration None Proxy settings.
EnableEndpointDiscovery bool True Auto-discover endpoints.
PreferredLocations list[str] [] Preferred regions list.
ExcludedLocations list[str] None Excluded regions list.
RetryOptions RetryOptions RetryOptions() Throttling retry options.
DisableSSLVerification bool False Disable SSL verification.
UseMultipleWriteLocations bool False Enable multi-region writes.
ConnectionRetryConfiguration ConnectionRetryPolicy | int None Connection-level retry policy or total retry count.
ResponsePayloadOnWriteDisabled bool False Skip response payloads on write operations.
RetryNonIdempotentWrites int 0 Number of times to retry non-idempotent writes.

SSLConfiguration fields

Field Type Default Description
SSLKeyFile str None Path to SSL key file.
SSLCertFile str None Path to SSL cert file.
SSLCaCerts str | bool None Path to CA bundle or True/False.

ProxyConfiguration fields

Field Type Default Description
Host str None Proxy host address.
Port int None Proxy port number.

4. Geo-Distribution & Availability

Option Type Default Level Description
preferred_locations list[str] [] Client Ordered list of preferred Azure regions (e.g., ["West US", "East US"]).
excluded_locations list[str] None Client, Operation Regions to exclude from routing. Operation-level overrides client-level.
multiple_write_locations bool False Client Enable writes to any region in a multi-write account.
availability_strategy_config dict[str, Any] None Client, Operation Cross-region hedging strategy configuration. Keys: threshold_ms (default 500), threshold_steps_ms (default 100). Operation-level overrides client-level. Setting None at operation-level disables the strategy for that request.
availability_strategy_executor ThreadPoolExecutor None Client Thread pool used for hedging concurrent operations.

5. Retry & Throttling

Client-level retry kwargs

Option Type Default Level Description
retry_total int 9 (from RetryOptions) Client Maximum total retry attempts (applies to both connection and throttle retries if specific overrides not set).
retry_throttle_total int (falls back to retry_total) Client Maximum throttle (429) retry attempts specifically.
retry_backoff_max int (seconds) 30 Client Maximum wait time between retries.
retry_throttle_backoff_max int (seconds) (falls back to retry_backoff_max) Client Maximum wait time between throttle retries specifically.
retry_fixed_interval int (ms) None Client Fixed retry interval in milliseconds; ignores server retryAfter header when set.
retry_connect int None Client Maximum connection-error retry attempts.
retry_read int None Client Maximum socket-read retry attempts.
retry_status int None Client Maximum retry attempts on error status codes.
retry_on_status_codes list[int] [] Client Specific HTTP status codes to retry on.
retry_backoff_factor float 1 Client Factor to calculate wait time between retries.
retry_mode RetryMode RetryMode.Fixed Client Retry mode (Fixed or Exponential).
retry_options (deprecated) RetryOptions Client Deprecated. A pre-built RetryOptions object.
connection_retry_policy (deprecated) ConnectionRetryPolicy Client Deprecated. A pre-built connection retry policy.

RetryOptions fields

Field Type Default Description
MaxRetryAttemptCount int 9 Max number of throttle retries.
FixedRetryIntervalInMilliseconds int None Fixed retry interval; if set, ignores retryAfter.
MaxWaitTimeInSeconds int 30 Max total wait time for throttle retries.

Operation-level write retry

Option Type Default Level Description
retry_write int 0 / False Client, Operation Number of times to retry non-idempotent write operations. Operation-level overrides client-level. Accepted on: create_item, replace_item, upsert_item, patch_item, delete_item, execute_item_batch.

6. Performance & Throughput

Option Type Default Level Description
offer_throughput int | ThroughputProperties None Database, Container-Def Provisioned throughput (RU/s) for a database or container.
throughput_bucket int None Client, Operation Desired throughput bucket. Client-level sets a default header; operation-level overrides per-request.
no_response_on_write bool False Client Instructs service to skip response payloads on write operations (client-level default).
no_response bool None Operation Per-request override: skip sending response payloads on writes. Falls back to client-level no_response_on_write. Accepted on: create_item, replace_item, upsert_item, patch_item.
priority Literal["High", "Low"] None Client, Operation Priority-based execution. Low-priority requests are throttled first when throughput limits are reached. Must be enabled at account level.

ThroughputProperties

Field Type Default Description
offer_throughput int None Manual provisioned throughput in RU/s.
auto_scale_max_throughput int None Max autoscale throughput (1000–1000000, increments of 1000).
auto_scale_increment_percent int None Percentage increment from selected RU base (≥ 0).

7. Query Options

Option Type Default Level Description
query str Operation The SQL query string.
parameters list[dict[str, object]] None Operation Parameterized query parameters (list of {"name": "@p", "value": v}).
partition_key PartitionKeyType None Operation Scopes query to a single logical partition. None → cross-partition. NonePartitionKeyValue → null partition key.
feed_range dict[str, Any] None Operation Scopes query to a specific feed range (mutually exclusive with partition_key).
enable_cross_partition_query bool None Operation Allow fan-out queries across partitions.
max_item_count int None Operation Maximum items per page/enumeration.
enable_scan_in_query bool None Operation Allow table scans when indexing is opted out.
populate_query_metrics bool None (deprecated on most methods) Operation Enable query metrics in response headers.
populate_index_metrics bool None Operation Return index metrics showing how indexes were used and potential improvements. Incurs overhead.
continuation_token_limit int None (no limit) Operation Max size (KB) of the continuation token in query responses. 0 = no limit.
max_integrated_cache_staleness_in_ms int None Operation Max cache staleness for the integrated cache (Session/Eventual consistency). Accepted on: read_item, read_all_items, query_items.

8. Change Feed Options

Option Type Default Level Description
partition_key PartitionKeyType None Operation Scope change feed to a logical partition.
feed_range dict[str, Any] None Operation Scope change feed to a specific feed range.
continuation str None Operation Continuation token from a previous change feed response. Contains mode information.
start_time datetime | Literal["Now", "Beginning"] "Now" Operation Start point for change feed processing. "Beginning" = from the start, "Now" = from current time, or a specific datetime (converted to UTC).
max_item_count int None Operation Maximum items per page.
mode Literal["LatestVersion", "AllVersionsAndDeletes"] None Operation Change feed mode. LatestVersion returns latest item versions; AllVersionsAndDeletes returns all versions including deletes (requires start_time="Now" or continuation).
priority Literal["High", "Low"] None Operation Priority-based execution for change feed requests.
is_start_from_beginning (legacy) bool False Operation Legacy flag; if True, maps to start_time="Beginning".
partition_key_range_id (legacy) str None Operation Legacy partition key range ID filter.

9. Item CRUD Options

These kwargs are accepted on item-level methods (create_item, read_item, replace_item, upsert_item, patch_item, delete_item).

Option Type Default Level Description
partition_key PartitionKeyType (required for most) Operation The partition key value for the item.
pre_trigger_include str None Operation Server-side trigger ID to execute before the operation.
post_trigger_include str None Operation Server-side trigger ID to execute after the operation.
session_token str None Operation Session token for Session consistency.
initial_headers dict[str, str] None Operation Additional HTTP headers to send with the request.
etag str None Operation ETag value for optimistic concurrency (must be paired with match_condition).
match_condition MatchConditions None Operation Concurrency condition: IfNotModified, IfPresent, IfModified, IfMissing.
indexing_directive int None Operation (create_item) Whether to index this document. Values: 0 (Default), 1 (Exclude), 2 (Include).
enable_automatic_id_generation bool False Operation (create_item) Auto-generate id if not present in the document body.
filter_predicate str None Operation (patch_item) Conditional filter predicate for patch operations.
response_hook Callable None Operation Callback invoked with response headers/metadata.
priority Literal["High", "Low"] None Operation Request priority.
no_response bool None Operation Skip response payloads on write.
retry_write int None Operation Per-request override for non-idempotent write retries.
throughput_bucket int None Operation Per-request throughput bucket.
excluded_locations list[str] None Operation Per-request excluded regions (overrides client-level).
availability_strategy_config dict[str, Any] (client default) Operation Per-request hedging strategy (overrides client-level).

Batch Operation (execute_item_batch)

Same as above, except:

  • partition_key is required (all operations in batch share a single partition key).
  • etag / match_condition are not applicable (ignored with deprecation warning).
  • no_response is not applicable.

Read-Many (read_items)

Option Type Default Level Description
items list[Tuple[str, PartitionKeyType]] (required) Operation List of (id, partition_key) tuples to read.
executor ThreadPoolExecutor None Operation Thread pool for concurrent reads.
max_concurrency int None Operation Max concurrent threads (ignored if executor is provided).
consistency_level str None Operation Per-request consistency override.

10. Container Definition Options

These are set when calling DatabaseProxy.create_container or replace_container.

Option Type Default Level Description
id str (required) Container-Def Container name/ID.
partition_key PartitionKey (required) Container-Def Partition key definition (PartitionKey(path=..., kind=...)).
indexing_policy dict[str, Any] None Container-Def Indexing policy: indexing mode, included/excluded paths, composite indexes, spatial indexes, etc.
default_ttl int None (no expiry) Container-Def Default time-to-live in seconds for items. -1 = on with no default expiry; positive int = seconds.
unique_key_policy dict[str, Any] None Container-Def Unique key constraints.
conflict_resolution_policy dict[str, Any] None Container-Def Conflict resolution policy for multi-region writes.
offer_throughput int | ThroughputProperties None Container-Def Provisioned throughput for the container.
analytical_storage_ttl int None Container-Def Analytical store TTL. None = off, -1 = on with no TTL. Requires Synapse Link.
computed_properties list[dict[str, str]] None Container-Def Computed properties definitions.
vector_embedding_policy dict[str, Any] None Container-Def Vector embedding policy (dimensions, data type, distance function).
change_feed_policy dict[str, Any] None Container-Def Change feed policy (e.g., retentionDuration).
full_text_policy dict[str, Any] None Container-Def Provisional. Full text search policy (default language, per-path language).
return_properties bool False Container-Def, Database If True, returns a tuple of (Proxy, properties_dict) instead of just the proxy.

11. Database-Level Options

Option Type Default Level Description
id str (required) Database Database name/ID.
offer_throughput int | ThroughputProperties None Database Provisioned throughput for the database (shared across containers).
initial_headers dict[str, str] None Database, Operation Additional HTTP headers.
response_hook Callable None Database, Operation Callback for response metadata.
throughput_bucket int None Operation Throughput bucket for list/query/delete database operations.
return_properties bool False Database Return properties alongside proxy on create.

12. Stored Procedure / Script Options

Option Type Default Level Description
partition_key PartitionKeyType None Operation Partition key for stored procedure execution scope.
params list[dict[str, Any]] None Operation Parameters to pass to the stored procedure.
enable_script_logging bool None Operation Enables script logging for the stored procedure execution.
max_item_count int None Operation Max items for list/query of scripts, triggers, UDFs.

13. Semantic Reranking Options (Provisional)

Called via ContainerProxy.semantic_rerank(). Requires AAD credentials.

Option Type Default Level Description
context str (required) Operation The reranking query/context string.
documents list[str] (required) Operation Documents to rerank.
options dict[str, Any] None Operation Additional reranking options (see below).

Reranking options dict keys

Key Type Default Description
return_documents bool True Include document text in response.
top_k int all Max documents to return.
batch_size int Documents per processing batch.
sort bool True Sort results by relevance score descending.
document_type str "string" or "json".
target_paths str Comma-separated JSON paths for "json" document type.

14. Diagnostics & Logging

Option Type Default Level Description
enable_diagnostics_logging bool False Client Enable the CosmosHttpLoggingPolicy. Must be paired with a logger.
logger logging.Logger None Client, Operation Logger for request diagnostics. Requests are logged at INFO level.
user_agent_suffix str None Client Custom suffix appended to the SDK user-agent string.
response_hook Callable None Operation Callback invoked with response metadata on any operation.

15. Feed Range & Partition Key Utilities

These are methods on ContainerProxy, not kwargs, but they affect how operations are scoped:

Method Description
read_feed_ranges(force_refresh=False) Get list of feed ranges for the container. force_refresh bypasses the cache.
feed_range_from_partition_key(partition_key) Convert a partition key value to a feed range dict.
is_feed_range_subset(parent, child) Check if child feed range is a subset of parent.
get_latest_session_token(feed_ranges_to_session_tokens, target_feed_range) Get the most up-to-date session token for a given feed range.

16. Common Internal Options (via build_options)

The build_options function in _base.py maps user-facing kwargs to internal request option keys. This table shows the mapping:

User kwarg Internal option key Description
initial_headers initialHeaders Extra HTTP headers.
pre_trigger_include preTriggerInclude Pre-operation trigger.
post_trigger_include postTriggerInclude Post-operation trigger.
access_condition accessCondition ETag-based access condition.
session_token sessionToken Session token.
resource_token_expiry_seconds resourceTokenExpirySeconds Resource token expiry.
offer_enable_ru_per_minute_throughput offerEnableRUPerMinuteThroughput Enable RU/min throughput.
disable_ru_per_minute_usage disableRUPerMinuteUsage Disable RU/min metering.
continuation continuation Continuation token.
content_type contentType Request content type.
is_query_plan_request isQueryPlanRequest Internal: query plan request flag.
supported_query_features supportedQueryFeatures Internal: supported query features.
query_version queryVersion Internal: query version.
priority priorityLevel Request priority ("High" / "Low").
no_response responsePayloadOnWriteDisabled Skip write response payload.
retry_write retry_write Non-idempotent write retry count.
max_item_count maxItemCount Page size.
throughput_bucket throughputBucket Throughput bucket.
excluded_locations excludedLocations Excluded regions.
availability_strategy_config availabilityStrategyConfig Hedging strategy config.
timeout timeout Operation timeout (passed through).
read_timeout read_timeout Read timeout (passed through).

17. Environment Variables

These environment variables modify SDK behavior at runtime:

Variable Default Description
AZURE_COSMOS_HYBRID_SEARCH_MAX_ITEMS 1000 Max items for hybrid search.
AZURE_COSMOS_MAX_ITEM_BUFFER_VECTOR_SEARCH 50000 Max item buffer for vector search.
AZURE_COSMOS_SESSION_TOKEN_FALSE_PROGRESS_MERGE "True" Enable session token false-progress merge.
AZURE_COSMOS_ENABLE_CIRCUIT_BREAKER "False" Enable circuit breaker for partition-level failover.
AZURE_COSMOS_AAD_SCOPE_OVERRIDE "" (uses default) Override AAD scope (default: https://cosmos.azure.com/.default).
AZURE_COSMOS_SEMANTIC_RERANKER_INFERENCE_ENDPOINT Custom endpoint for the semantic reranker inference service.
AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES 3 Max health check retry attempts.
AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS 500 Health check retry interval in ms.
AZURE_COSMOS_CONSECUTIVE_ERROR_COUNT_TOLERATED_FOR_READ 10 Circuit breaker: consecutive read errors tolerated.
AZURE_COSMOS_CONSECUTIVE_ERROR_COUNT_TOLERATED_FOR_WRITE 5 Circuit breaker: consecutive write errors tolerated.
AZURE_COSMOS_FAILURE_PERCENTAGE_TOLERATED 90 Circuit breaker: failure percentage threshold.
AZURE_COSMOS_TIMEOUT_ERROR_THRESHOLD_FOR_PPAF 10 Per-partition automatic failover: timeout error threshold.

18. Cascading / Layering Behavior

The Cosmos DB Python SDK supports a layered configuration model where options set at a broader scope act as defaults and can be overridden at a narrower scope:

Client → Operation cascading

Option Client-level Operation-level Behavior
consistency_level Set on CosmosClient(consistency_level=...) Passed via consistencyLevel kwarg on read_items Operation overrides client.
priority Set on CosmosClient(priority=...) → stored as default header Passed per-request on any item operation Operation-level value takes precedence.
throughput_bucket Set on CosmosClient(throughput_bucket=...) → stored as default header Passed per-request Operation value overrides client default header.
excluded_locations Set on CosmosClient(excluded_locations=...) → stored in ConnectionPolicy Passed per-request on item operations Operation-level replaces client-level list entirely.
availability_strategy_config Set on CosmosClient(availability_strategy_config=...) Passed per-request; None explicitly disables Operation-level overrides; None disables hedging for that request.
no_response_on_write / no_response Client: no_response_on_write=True sets ConnectionPolicy.ResponsePayloadOnWriteDisabled Operation: no_response=True on individual writes When no_response is not specified at operation level, falls back to client-level no_response_on_write.
retry_write Client: retry_write=N sets ConnectionPolicy.RetryNonIdempotentWrites Operation: retry_write=N on individual writes Operation value takes precedence.
session_token Managed automatically by the SDK (internal Session object) Can be explicitly passed per-request Explicit token overrides SDK-managed session.

ConnectionPolicy → kwargs override

When constructing the client, individual kwargs (e.g., connection_timeout, preferred_locations) override fields on a user-supplied ConnectionPolicy object. The precedence is:

kwargs > ConnectionPolicy fields > ConnectionPolicy defaults

Container-level settings vs. operation-level

Container definition options (default_ttl, indexing_policy, etc.) are schema-level settings stored on the server. They are not overridable per-request. The indexing_directive parameter on create_item is the one exception that allows per-document override of indexing behavior.

Session management

  • If consistency_level is set to "Session" (either explicitly or from account default), the SDK creates an internal Session object that automatically tracks and sends session tokens.
  • Users can override with explicit session_token kwargs per-request.
  • The get_latest_session_token() method on ContainerProxy enables manual session token management for advanced scenarios.

Azure Cosmos DB Rust SDK — Configuration Options Reference

This document provides a comprehensive catalog of every configurable option available in the Azure Cosmos DB Rust SDK (azure_data_cosmos). Options are grouped by purpose and annotated with their type, default value, and the level at which they can be set.

Level key:

Abbreviation Meaning
Client Set once on CosmosClientOptions when constructing CosmosClient
Request Set per-operation via an options struct (e.g., ItemOptions, QueryOptions)
Container Set on ContainerProperties when creating/replacing a container
Database Set on CreateDatabaseOptions when creating a database
Model Set on a model struct (e.g., ThroughputProperties, PatchDocument)

1. Authentication

Authentication method is chosen by which CosmosClient constructor you use. All three accept Option<CosmosClientOptions>.

Constructor Auth Mechanism Feature Gate Key Parameters
CosmosClient::new() Entra ID / TokenCredential (always available) endpoint: &str, credential: Arc<dyn TokenCredential>
CosmosClient::with_key() Account key (shared key) key_auth endpoint: &str, key: Secret
CosmosClient::with_connection_string() Connection string (key-based) key_auth connection_string: Secret

The connection string format is AccountEndpoint=<url>;AccountKey=<key>.


2. Client-Level Options (CosmosClientOptions)

Set when constructing CosmosClient. These are the broadest options and apply as defaults to every request made through the client.

2.1 Core Azure SDK Options

CosmosClientOptions embeds azure_core::http::ClientOptions (via the client_options field), which provides transport-level configuration.

Note: The Cosmos SDK overrides client_options.retry to RetryOptions::none() internally (it uses its own retry logic) and sets client_options.logging to include Cosmos-specific allowed headers.

Option Type Default Description
client_options azure_core::http::ClientOptions Default::default() Container for pipeline policies, retry, transport, user-agent, instrumentation, logging, and cloud configuration. See Section 2.1.1 below.

2.1.1 ClientOptions Sub-Fields

These are fields of azure_core::http::ClientOptions (which is the Azure wrapper around typespec_client_core::http::ClientOptions):

Field Type Default Description
per_call_policies Vec<Arc<dyn Policy>> [] Custom pipeline policies invoked once per API call (before retry).
per_try_policies Vec<Arc<dyn Policy>> [] Custom pipeline policies invoked on every retry attempt.
retry RetryOptions Exponential (see below) Retry strategy. Overridden to RetryOptions::none() by the Cosmos client — Cosmos handles its own retries.
transport Option<Transport> None (uses default HTTP client) Custom HTTP transport implementation.
user_agent UserAgentOptions Default::default() Controls the User-Agent header (application ID, etc.).
instrumentation InstrumentationOptions Default::default() Distributed tracing / OpenTelemetry configuration.
logging LoggingOptions Default::default() Controls which headers/query params are logged vs. redacted. Overridden by Cosmos to allow Cosmos-specific headers.
cloud Option<Arc<CloudConfiguration>> None (Azure Public Cloud) Cloud configuration (sovereign clouds, etc.).
RetryOptions Variants (not used by Cosmos transport layer, but included for reference)
Variant Description
RetryOptions::exponential(ExponentialRetryOptions) Exponential back-off (default outside Cosmos).
RetryOptions::fixed(FixedRetryOptions) Fixed interval retries.
RetryOptions::custom(Arc<dyn RetryPolicy>) User-supplied retry policy.
RetryOptions::none() No retries. This is what Cosmos sets.
ExponentialRetryOptions (reference)
Field Type Default Description
initial_delay Duration 200 ms Initial delay before first retry.
max_retries u32 8 Maximum retry attempts.
max_total_elapsed Duration 60 s Maximum total time spent retrying.
max_delay Duration 30 s Maximum delay between any two retries.
FixedRetryOptions (reference)
Field Type Default Description
delay Duration 200 ms Fixed delay between retries.
max_retries u32 8 Maximum retry attempts.
max_total_elapsed Duration 60 s Maximum total time spent retrying.

2.2 Cosmos-Specific Client Options

Option Type Default Level Description
application_name Option<String> None Client Application identifier, used for telemetry/User-Agent.
application_region Option<RegionName> None Client The Azure region in which the application is running. Used for optimizing regional routing.
application_preferred_regions Vec<RegionName> [] (empty) Client Ordered list of preferred regions for routing requests. Regions are tried in order.
excluded_regions Vec<RegionName> [] (empty) Client Regions to exclude from routing. If all are excluded, the primary/hub region is used.
account_initialization_custom_endpoints Option<HashSet<String>> None Client Custom endpoints to use during account initialization (e.g., for private endpoints).
consistency_level Option<ConsistencyLevel> None (account default) Client Default consistency level for all operations. Sent as x-ms-consistency-level header.
request_timeout Option<Duration> None Client Timeout for individual HTTP requests.
throughput_bucket Option<usize> None Client Throughput bucket for throughput control. Sent as x-ms-cosmos-throughput-bucket header.
priority Option<PriorityLevel> None Client Default request priority (High or Low). Low-priority requests are throttled first. Sent as x-ms-cosmos-priority-level header.
custom_headers HashMap<HeaderName, HeaderValue> {} (empty) Client Arbitrary custom headers added to every request. Will not override SDK-set headers. Useful for dedicated gateway cache control headers.
enable_remote_region_preferred_for_session_retry bool false Client Hint to the session retry policy to prefer remote regions earlier when retrying 404/1002 errors.
enable_partition_level_circuit_breaker bool false Client Enables the partition-level circuit breaker, which can mark individual partitions as unavailable.
disable_partition_level_failover bool false Client Disables partition-level failover behavior.
enable_upgrade_consistency_to_local_quorum bool false Client When enabled, upgrades certain consistency levels to local quorum reads for better availability.
session_retry_options SessionRetryOptions See below Client Configuration for session-consistency retry behavior.
fault_injection_enabled bool false Client (Feature: fault_injection) Enables fault injection for testing.

2.3 Session Retry Options (SessionRetryOptions)

Nested within CosmosClientOptions. Controls retry behavior for session-consistency 404/1002 errors.

Field Type Default Description
min_in_region_retry_time Duration 500 ms (minimum: 100 ms) Minimum time spent retrying within a single region before giving up on that region.
max_in_region_retry_count usize 0 (default usize) Maximum number of retries within a single region. Minimum is 1.
remote_region_preferred bool false If true, retries all replicas once then switches to a different region with minimum delay. If false, retries in the local region up to 5 seconds.

3. Consistency Levels (ConsistencyLevel)

Used in CosmosClientOptions, ItemOptions, and QueryOptions.

Variant Description
ConsistencyLevel::Strong Linearizable reads; strongest guarantee.
ConsistencyLevel::BoundedStaleness Reads lag behind writes by at most K versions or T time.
ConsistencyLevel::Session Monotonic reads/writes within a session. Default for most accounts.
ConsistencyLevel::ConsistentPrefix Reads never see out-of-order writes.
ConsistencyLevel::Eventual No ordering guarantee; lowest latency.

4. Priority Levels (PriorityLevel)

Used in CosmosClientOptions, ItemOptions, and QueryOptions.

Variant Description
PriorityLevel::High High priority — throttled last when RU budget is exhausted.
PriorityLevel::Low Low priority — throttled first when RU budget is exhausted.

5. Per-Operation Options

5.1 Item Operations (ItemOptions)

Used for: create_item, replace_item, upsert_item, read_item, delete_item, patch_item.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context (for tracing, cancellation, etc.).
pre_triggers Option<Vec<String>> None Server-side triggers to execute before the operation. Sent as x-ms-documentdb-pre-trigger-include.
post_triggers Option<Vec<String>> None Server-side triggers to execute after the operation. Sent as x-ms-documentdb-post-trigger-include.
session_token Option<SessionToken> None Session token for session consistency. Sent as x-ms-session-token.
consistency_level Option<ConsistencyLevel> None (falls through to client/account default) Per-request consistency level override. Sent as x-ms-consistency-level.
indexing_directive Option<IndexingDirective> None Controls indexing behavior for this item. Sent as x-ms-indexing-directive.
if_match_etag Option<Etag> None Optimistic concurrency control — operation only proceeds if the item's ETag matches. Sent as If-Match.
content_response_on_write_enabled bool false When true, write operations return the full item body. When false, sends Prefer: return=minimal.
throughput_bucket Option<usize> None Per-request throughput bucket override.
priority Option<PriorityLevel> None Per-request priority override.
custom_headers HashMap<HeaderName, HeaderValue> {} (empty) Custom headers for this request. Will not override SDK-set headers.
excluded_regions Option<Vec<RegionName>> None (uses client-level) Regions to skip for this specific request. None = use client defaults; empty Vec = exclude no regions.

IndexingDirective Variants

Variant Description
IndexingDirective::Default Use the container's default indexing behavior.
IndexingDirective::Include Force this item to be indexed.
IndexingDirective::Exclude Force this item to be excluded from the index.

5.2 Query Operations (QueryOptions)

Used for: ContainerClient::query_items.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.
session_token Option<SessionToken> None Session token for session consistency.
consistency_level Option<ConsistencyLevel> None Per-query consistency level override.
throughput_bucket Option<usize> None Per-query throughput bucket override.
priority Option<PriorityLevel> None Per-query priority override.
custom_headers HashMap<HeaderName, HeaderValue> {} (empty) Custom headers for query requests.

5.3 Query Databases Options (QueryDatabasesOptions)

Used for: CosmosClient::query_databases.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.4 Query Containers Options (QueryContainersOptions)

Used for: DatabaseClient::query_containers.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.5 Create Database Options (CreateDatabaseOptions)

Used for: CosmosClient::create_database.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.
throughput Option<ThroughputProperties> None Provisioned throughput for the new database. See Section 7.

5.6 Delete Database Options (DeleteDatabaseOptions)

Used for: DatabaseClient::delete.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.7 Create Container Options (CreateContainerOptions)

Used for: DatabaseClient::create_container.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.
throughput Option<ThroughputProperties> None Provisioned throughput for the new container.

5.8 Replace Container Options (ReplaceContainerOptions)

Used for: ContainerClient::replace.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.9 Read Container Options (ReadContainerOptions)

Used for: ContainerClient::read.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.10 Delete Container Options (DeleteContainerOptions)

Used for: ContainerClient::delete.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.11 Read Database Options (ReadDatabaseOptions)

Used for: DatabaseClient::read.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

5.12 Throughput Options (ThroughputOptions)

Used for: DatabaseClient::read_throughput, DatabaseClient::replace_throughput, ContainerClient::read_throughput, ContainerClient::replace_throughput.

Option Type Default Description
method_options ClientMethodOptions<'a> Default::default() Carries the operation Context.

6. Container Configuration (ContainerProperties)

These are properties set when creating or replacing a container, not per-request options.

Property Type Default Description
id Cow<'static, str> (required) Container name/ID.
partition_key PartitionKeyDefinition (required) Partition key definition. See Section 8.
indexing_policy Option<IndexingPolicy> None Indexing configuration. See Section 9.
unique_key_policy Option<UniqueKeyPolicy> None Unique key constraints.
conflict_resolution_policy Option<ConflictResolutionPolicy> None Multi-region write conflict resolution strategy.
vector_embedding_policy Option<VectorEmbeddingPolicy> None Vector embedding configuration for vector search.
default_ttl Option<Duration> None Default time-to-live for items (in seconds).
analytical_storage_ttl Option<Duration> None TTL for the analytical store.

6.1 Conflict Resolution Policy

Field Type Description
mode ConflictResolutionMode LastWriterWins or Custom.
resolution_path String JSON path for last-writer-wins resolution (e.g., /_ts).
resolution_procedure String Stored procedure path for custom resolution.

6.2 Unique Key Policy

Field Type Description
unique_keys Vec<UniqueKey> List of unique key definitions. Each UniqueKey has paths: Vec<String>.

6.3 Vector Embedding Policy

Field Type Description
embeddings Vec<VectorEmbedding> List of vector embedding definitions.

Each VectorEmbedding contains:

Field Type Description
path String JSON path to the vector property.
data_type VectorDataType Float16, Float32, Uint8, or Int8.
dimensions u32 Number of dimensions in the vector.
distance_function VectorDistanceFunction Euclidean, Cosine, or DotProduct.

7. Throughput Configuration (ThroughputProperties)

Used in CreateDatabaseOptions, CreateContainerOptions, and replace_throughput() methods.

Factory Methods

Method Parameters Description
ThroughputProperties::manual(throughput) throughput: usize Fixed manual throughput in RU/s. Sent as x-ms-offer-throughput header.
ThroughputProperties::autoscale(max, increment) starting_maximum_throughput: usize, increment_percent: Option<usize> Autoscale throughput with a maximum RU/s. Optional auto-upgrade increment percentage. Sent as x-ms-cosmos-offer-autopilot-settings header.

Read Accessors

Method Returns Description
throughput() Option<usize> The manual throughput value, if set.
autoscale_maximum() Option<usize> The autoscale maximum throughput, if configured.
autoscale_increment() Option<usize> The autoscale increment percentage, if configured.

8. Partition Key Configuration

8.1 PartitionKeyDefinition (Container-level)

Set on ContainerProperties when creating a container.

Field Type Default Description
paths Vec<String> (required) JSON paths that make up the partition key (e.g., ["/tenantId"]).
kind PartitionKeyKind Auto-detected "Hash" for single-path, "MultiHash" for hierarchical (multi-path).
version Option<i32> Some(2) Hash version. Version 2 is the modern default.

Convenience constructors:

  • PartitionKeyDefinition::from("/path") — single-path Hash
  • PartitionKeyDefinition::from(("/path1", "/path2")) — two-level MultiHash
  • PartitionKeyDefinition::from(("/path1", "/path2", "/path3")) — three-level MultiHash

8.2 PartitionKey (Request-level)

Specifies the partition key value for a request. Supports:

Form Example Description
Single value "my_key", 42, 4.2f64 Converted via Into<PartitionKey>.
Hierarchical tuple ("parent", "child"), ("a", "b", 42) Up to 3 levels.
Vec<PartitionKeyValue> vec![PartitionKeyValue::from("a"), ...] Runtime-constructed, max 3 elements.
PartitionKey::NULL Explicit JSON null partition key.
PartitionKey::UNDEFINED Targets items where the PK property is absent (serialized as {}).
PartitionKey::EMPTY / () Empty partition key — signals a cross-partition query.
Option<T>None Serialized as null.

9. Indexing Policy (IndexingPolicy)

Set on ContainerProperties.

Field Type Default Description
automatic bool false Whether indexing is automatic for new items.
indexing_mode Option<IndexingMode> None Consistent or None.
included_paths Vec<PropertyPath> [] Paths to include in the index (e.g., /*).
excluded_paths Vec<PropertyPath> [] Paths to exclude from the index.
spatial_indexes Vec<SpatialIndex> [] Spatial index definitions (with SpatialType: Point, Polygon, LineString, MultiPolygon).
composite_indexes Vec<CompositeIndex> [] Composite index definitions (each with ordered CompositeIndexProperty entries: path + Ascending/Descending).
vector_indexes Vec<VectorIndex> [] Vector index definitions (path + VectorIndexType: Flat, QuantizedFlat, DiskANN).

10. Patch Document (PatchDocument)

Used with ContainerClient::patch_item.

Field Type Default Description
condition Option<Cow<'static, str>> None SQL-like filter predicate; patch is only applied if condition is met.
operations Vec<PatchOperation> [] List of patch operations to apply.

Patch Operations

Operation Fields Description
Add path, value Add a property.
Remove path Remove a property.
Replace path, value Replace a property's value.
Set path, value Set a property (creates if absent).
Increment path, value (Number) Increment a numeric property.
Move from, to Move a property from one path to another.

11. Region Names (RegionName / regions module)

The regions module provides pre-defined constants for all Azure regions (e.g., regions::WEST_US, regions::EAST_US, regions::WEST_EUROPE). Over 80 region constants are defined.

RegionName supports case-insensitive, whitespace-insensitive comparison. "West US", "westus", and "WEST US" are all equivalent.

Used in: application_region, application_preferred_regions, excluded_regions (client-level and request-level).


12. Cascading / Layering Behavior

Several options can be set at the client level and overridden at the request level. The SDK applies a clear priority order:

12.1 Header Priority

Request-level headers always take priority over client-level headers. The mechanism:

  1. Request-level options (e.g., ItemOptions, QueryOptions) are applied to the request first via CosmosRequestBuilder::request_headers().
  2. Client-level options (CosmosClientOptions) are applied second via CosmosRequest::client_headers().
  3. The client_headers() method only inserts a header if it is not already present on the request. This ensures request-level values are never overridden by client-level defaults.

Custom headers follow the same pattern: custom headers are added first, but SDK-set headers (from consistency level, priority, etc.) overwrite any custom header with the same name.

12.2 Options That Support Cascading

Option Client-Level Request-Level Behavior
consistency_level CosmosClientOptions ItemOptions, QueryOptions Request overrides client; client overrides account default.
throughput_bucket CosmosClientOptions ItemOptions, QueryOptions Request overrides client.
priority CosmosClientOptions ItemOptions, QueryOptions Request overrides client.
custom_headers CosmosClientOptions ItemOptions, QueryOptions Request headers take priority; client headers fill in gaps.
excluded_regions CosmosClientOptions ItemOptions If ItemOptions::excluded_regions is None, client-level excluded_regions are used. If set to an empty Vec, no regions are excluded for that request.

12.3 Options That Do NOT Cascade

These are set at only one level:

Option Level Notes
application_preferred_regions Client only Determines regional routing order for all requests.
application_region Client only Identifies where the application is running.
request_timeout Client only Applies to all requests from this client.
session_retry_options Client only Governs retry behavior for all session-consistency retries.
enable_partition_level_circuit_breaker Client only Global circuit breaker toggle.
pre_triggers, post_triggers Request only (ItemOptions) Triggers are specific to individual item operations.
session_token Request only (ItemOptions, QueryOptions) Session tokens are tied to specific read/write sequences.
indexing_directive Request only (ItemOptions) Per-item indexing override.
if_match_etag Request only (ItemOptions) Optimistic concurrency is per-item.
content_response_on_write_enabled Request only (ItemOptions) Controls response body for a specific write.
throughput CreateDatabaseOptions / CreateContainerOptions Set at resource creation time only.

12.4 Visual Cascade Diagram

Account Default (server-side)
  └─ CosmosClientOptions (client-level)
       ├─ consistency_level
       ├─ priority
       ├─ throughput_bucket
       ├─ custom_headers
       └─ excluded_regions
            └─ ItemOptions / QueryOptions (request-level overrides)
                 ├─ consistency_level    ← wins if set
                 ├─ priority             ← wins if set
                 ├─ throughput_bucket    ← wins if set
                 ├─ custom_headers       ← wins if set (per header name)
                 └─ excluded_regions     ← wins if Some(...)

13. Summary of All Options Structs

Struct Level Used By
CosmosClientOptions Client CosmosClient::new(), with_key(), with_connection_string()
SessionRetryOptions Client (nested) CosmosClientOptions::session_retry_options
ItemOptions Request create_item, replace_item, upsert_item, read_item, delete_item, patch_item
QueryOptions Request query_items
QueryDatabasesOptions Request query_databases
QueryContainersOptions Request query_containers
CreateDatabaseOptions Request create_database
DeleteDatabaseOptions Request delete (database)
CreateContainerOptions Request create_container
ReplaceContainerOptions Request replace (container)
ReadContainerOptions Request read (container)
DeleteContainerOptions Request delete (container)
ReadDatabaseOptions Request read (database)
ThroughputOptions Request read_throughput, replace_throughput
ContainerProperties Container create_container, replace
ThroughputProperties Model create_database, create_container, replace_throughput
PatchDocument Model patch_item
IndexingPolicy Container (nested) ContainerProperties::indexing_policy
PartitionKeyDefinition Container (nested) ContainerProperties::partition_key

14. Feature Flags

Feature Effect
key_auth Enables CosmosClient::with_key() and CosmosClient::with_connection_string() constructors.
fault_injection Enables the fault_injection_enabled option on CosmosClientOptions and the fault_injection module for testing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment