Search code examples
c#mongodb.net-core

How set timeout to find operation to Mongo in C#


I use nuget MongoDB.Driver Version=2.17.1.

Sometimes find operation is freezed while making request to mongo database. And this freeze can last upto 2 hours or more.

Here how I call find:

Set<EntityDto>().Find(x => x.Id == id).FirstOrDefaultAsync(cancellationToken);

I tried to find any options to set timeout and found:

  1. class MongoClientSettings with many properies like ConnectTimeout, MaxConnectionIdleTime, MaxConnectionLifeTime, ServerSelectionTimeout, SocketTimeout
  2. class FindOptions with properties MaxAwaitTime, MaxTime.

But I can't find any documentations what each property serve to. And can't find any default values equals to 2 hours.

Also I found here the solution with cancelationToken.

But anyway I'd like to find out with all these settings in mongo library. Anyone knows where to find explanation or documentation?


Solution

  • You can find this details here. Options in other drivers and shells are the same as in c# driver (slight naming difference related to language standards are possible too though).

    maxTimeMS is the same as MaxTime, so configure it in FindOptions. See also same details here

    UPDATE:

    • maxtime is responsible for a time where command is being executed on the server it doesn't include the round trip time or the time needed for the driver for serialization, server selecting and so on. So do not expect too precise calculation from client perspective
    • ConnectTimeout - The time in milliseconds to attempt a connection before timing out. See here
    • socketTimeout - timeout on response from socket during sending/receiving commands. See here
    • ServerSelectionTimeout - timeout on finding available server to work with. See here
    • WaitQueueTimeout - The maximum time that a thread can wait for a connection to become available.See here
    • MaxConnectionIdleTime - The maximum time that a connection can remain idle in the pool before being removed and closed. See here
    • MaxConnectionLifeTime - as I recall, it's time when connection is considered alive after creating in the pool.

    So, as you can see, each timeout option is responsible for particular step in communication with a server. As I understand, you need a client side timeout with high precise. Then, cancellationtoken is the best option. However pay attention that server is not aware about it, so it might be the situation when operation will be done on the server, but cancellationToken on the client will fail remaining inner driver's steps and as the result the full operation.

    Also as a note, you should remember, that when you call let's say Find operation, it may be that more steps are actually taken by driver than just sending your command, at the very least driver should ensure that there is a connection in the pool, the server is healthy, serialization steps... So, I would not rely on 100ms client side timeout in your case