Reconnecting to MongoDB when Mongoose connect fails at startup
We recently experienced a short outage when a deploy to Heroku came up during a brief period when network connectivity to MongoHQ was down.
Our app came up but failed to connect to mongo. To our surprise, it did not attempt to reconnect, so even though MongoHQ came back quickly, our app continued to report errors due to no mongo connection.
This was especially surprising since we use mongoose.js to map to mongo, and mongoose passes the auto_reconnect=true
flag to node-mongodb-native. It turns out auto_reconnect
(aka autoReconnect
in some contexts) only comes in to play if the driver has already successfully established a connection to mongo.
According to the driver maintainers, this is by design.
by design, autoReconnect is after a successful connection. If you need to handle the case where your app is started before the server I recommend using setTimeout and doing your own connection logic for the db.open function.
Seems like a bit of a cop out to me. You’ll try to reconnect on an interval if you loose the connection but not if you can’t connect initially? Doesn’t everyone need this functionality?
Well, we clearly do so we implemented it and are sharing it here for you.
Good Eggs connects people who love food, directly with people who make it. We deliver the most incredible food, straight to Bay Area homes. If you are inspired by our mission is to grow and sustain local food systems worldwide, find out how you can help.