How to Resolve Timeout Error Connecting C# (.NET 9) Application to Azure Cosmos DB for MongoDB?

Oscar Chavarria 0 Reputation points
2025-05-10T20:54:09.3066667+00:00

I've tried in the past connect C# code (.NET 9) to my Azure Cosmos DB for MongoDB (vCore).

Till today and using the latest MongoDB.Driver package version (3.4.0) I'm still unable to get the proper connection to work either by using the exact same connection string provided by Azure or versions of it.

  • I've escapped special characters in my password.
  • Allowed all IPs access to the resource.
  • Ping/nslookup getting:
    Servidor: UnKnown Address: fe80::1

But none of this seems to work, I though the issue will get solved eventually but have been 2 months since then.

Repro steps:
Client setup:

MongoClient client = new($"mongodb+srv://MYUSER:{PASSWORD}@HOSTNAME.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000");

IMongoDatabase database = client.GetDatabase("my-db-source");

IMongoCollection<Products> collection = database.GetCollection<Products>("collection1");

IAsyncCursor<Products> documents = await collection.FindAsync<Products>(
    d => d.id == "123"
);

Result:

Unhandled exception. System.TimeoutException: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [] }.
   at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask)
   at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Clusters.Cluster.SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Clusters.IClusterExtensions.SelectServerAndPinIfNeededAsync(IClusterInternal cluster, ICoreSessionHandle session, IServerSelector selector, IReadOnlyCollection`1 deprioritizedServers, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Bindings.ReadPreferenceBinding.GetReadChannelSourceAsync(IReadOnlyCollection`1 deprioritizedServers, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.RetryableReadContext.InitializeAsync(CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.RetryableReadContext.CreateAsync(IReadBinding binding, Boolean retryRequested, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
   at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
   at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in D:\net\repos\MongoTest\Program.cs:line 14
   at Program.<Main>(String[] args)

Note: Searching seems to be related with a DNS stuff but same connection string works in Python with pymongo but no in systems las mongodb compass

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,851 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Suwarna S Kale 2,591 Reputation points
    2025-05-11T02:01:58.7066667+00:00

    Hello Oscar Chavarria,

    Thank you for posting your question in the Microsoft Q&A forum. 

    The connection issues between your .NET 9 application and Azure Cosmos DB for MongoDB (vCore) likely stem from DNS resolution or driver-specific handling of the connection string, despite working in Python with PyMongo. The timeout error suggests the MongoDB .NET driver fails to discover cluster nodes, possibly due to: 

    • DNS Propagation Delays: The mongodb+srv protocol relies on SRV records, which may not resolve consistently across environments. 
    • Driver Configuration: The .NET driver might interpret timeout settings differently—try explicitly increasing connectTimeoutMS and serverSelectionTimeoutMS in the connection string. 
    • TLS/SSL Handshake: Ensure the system running .NET trusts Azure’s TLS certificates (unlike Python, which may bypass stricter checks). 
    • Connection String Format: While escaping special characters helps, verify the full URI adheres to Azure’s vCore requirements (e.g., retrywrites=false is critical). 

    For troubleshooting: 

    • Replace mongodb+srv with a standard connection string (list explicit host/port) to bypass SRV issues. 
    • Test with MongoDB.Driver 2.19+ (some users report better compatibility). 
    • Capture network traces (dotnet-trace or Wireshark) to confirm DNS/TLS failures. 
    • If using Azure Private Link, validate DNS resolution aligns with private endpoints. 

    Since Compass also fails, this points to a platform/network-level inconsistency rather than code. Engage Azure Support with correlation IDs and network traces for deeper diagnosis. 

     

    If the above answer helped, please do not forget to "Accept Answer" as this may help other community members to refer the info if facing a similar issue. Your contribution to the Microsoft Q&A community is highly appreciated. 


  2. Sina Salam 20,106 Reputation points Moderator
    2025-05-11T23:50:37.3533333+00:00

    Hello Oscar Chavarria,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    I understand that you would like to know how you can resolve timeout error connecting C# (.NET 9) Application to Azure Cosmos DB for MongoDB?

    In assumption based on your explanation and what you have done so far, that no other environmental or network-related complications. The five steps below will permanently resolve the MongoDB connection issue:

    1. Replace the driver with MongoDB.Driver 2.21 because the older drivers are not fully supporting newer SRV-based DNS resolution. MongoDB.Driver v3.4.0 is obsolete and not compatible with Cosmos DB vCore (which uses MongoDB Wire Protocol v4.0 using bash command:

    dotnet add package MongoDB.Driver --version 2.21.0 To downgrade to the supported latest version. Version 2.21 includes bug fixes and improvements for DNS handling. - https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/vcore/reference-protocols

    1. Run the Docker container with your custom DNS server IP. But importantly, if the container's default DNS can't resolve the mongodb+srv:// hostname, using a reliable public DNS like Google’s (8.8.8.8) will help resolve it correctly. For an example, you can in your Dockerfile or runtime command, override the DNS to use a public resolver:
    docker run --dns=8.8.8.8 --dns=1.1.1.1 your-image
    

    Or in Docker Compose:

    services:
      app:
        image: your-image
        dns:
          - 8.8.8.8
          - 1.1.1.1
    
    1. Use a direct mongodb:// URI instead of mongodb+srv:// Because, the +srv URI relies on DNS SRV record lookups. Using mongodb:// avoids this dependency entirely and is often more reliable in restricted environments. Use this format instead:
    var client = new MongoClient("mongodb://USERNAME:******@HOSTNAME.mongocluster.cosmos.azure.com:10255/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false");
    
    1. It is also, critical to ensure port 10255 is reachable, MongoDB Atlas often uses port 10255 for TLS/SSL connections. If this port is blocked, connection attempts will fail. You can enforce TLS 1.2 in your code using C# line of code: System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;-https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls
    2. Test DNS resolution from inside the container to confirms that the container’s internal networking can resolve the required domains, catching issues before runtime. You achieve this by using a network tool inside Docker to verify DNS and port connectivity:
    apt-get update && apt-get install -y dnsutils netcat
    nslookup your-cluster.mongocluster.cosmos.azure.com
    nc -vz your-cluster.mongocluster.cosmos.azure.com 10255
    

    Use the links to read more details, the above steps should resolve the issue permanently, unless there are external factors like:

    • Changing network firewall rules
    • MongoDB cluster settings (e.g., IP whitelist)
    • Container DNS config reset on redeployment

    I hope this is helpful! Do not hesitate to let me know if you have any other questions or clarifications.


    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.