Tomasz Rakowski
Tomasz Rakowski

Reputation: 1062

Good way of handling MongoError: server instance pool was destroyed

I'm running a daemon with a mongo connection pool. It runs fine for days but eventually it crashes and every subsequent request gets this error:

MongoError: server instance pool was destroyed

The code is similar to this:

var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();

MongoClient.connect(config.mongo.url, function(err, db) {

    app.use('/', function(req, res, next) {
        db.collection('somecollection').find({}).toArray(function(err, result) {
            console.log(result);
        });
    })

    var server = require('http').Server(app);
    server.listen(config.worker.port, function() {
        var address = server.address();
        logger.info({
            address: address.address,
            port: address.port
        }, 'New Worker created');
    });
});

Restarting the process fixes the issue, but I would like the application to somehow elegantly reconnect and reset the "db" object there.

Upvotes: 4

Views: 6062

Answers (1)

libik
libik

Reputation: 23049

This is what we are using - if connection fails, it tries to reconnect after 5 seconds. It is written for mongoose, but we are just re-running connection when detecting error, which should be done for any framework.

// Connect to mongodb
    const connect = function () {
        const options = {server: {socketOptions: {keepAlive: 1}}};
        mongoose.connect(config.db, options);
    };
    connect();

    mongoose.connection.on('error', err => {
        let stack;
        if (err) {
            stack = err.stack;
        }
        winston.error('Mongo crashed with error', {err, stack});
    }); // eslint-disable-line no-console
    mongoose.connection.on('disconnected', () => {
        setTimeout(connect, 5000);
    });

Upvotes: 5

Related Questions