Search code examples
mongodbmongodb-.net-driver

MongoDB C# Driver connection pooling


I'm using the current stable version of the MongoDB C# Driver. I have a long-running service essentially reads data from an external source and writes it all to a MongoDB database.

At the moment, I handle this by connecting to MongoDB on startup...

void Connect()
{
    var client = new MongoClient("(url)");
    var server = client.GetServer();
    var db = server.GetDatabase("(db-name)");
    this.coll = db.GetCollection("(collection-name)");
}

and then whenever I get some data, I simply do:

void Insert(object data)
{
    this.coll.Save(data);
}

This all works fine, except for the odd occasion where the connection to MongoDB fails. I then an IOException on the Save call.

So I want to add some resilience to this, and the natural thing to do is to catch the IOException, try to re-connect, and then retry the Save. However, I'm wondering if I can make use of the connection pool to automatically handle lost connections for me. If so, what would my code need to look like for connection pooling to work?


Solution

  • There is already a connection pooling going on. The problem with sockets is that you don't know if they work until you use them. You have to send data to see if the connection is broken. The driver heartbeats occasionally, so there is a good chance we'll find that the connections were broken and start them over. But, there is a good chance you'll attempt to do an operation prior to the heartbeat running and the discovery of the broken connection. In this case, you'll check out a connection we didn't know was bad and you'll get an exception. The only thing you can do is catch and retry.