Graceful Mongoose, Redis, && Express in Node.js

Phillip Whisenhunt
The Startup
Published in
2 min readMay 25, 2020

I’ve recently been hacking away on a Node.js side project that uses Mongo(mongoose), Redis, and Express. As I was polishing my application for production I realized I needed to gracefully handle Mongoose, Redis, and Express throughout my application’s life cycle. For example, how do I wait for Mongoose and Redis to connect before allowing Express to accept HTTP connections? Or, when I deploy my code how do I wait for Mongoose, Redis, and Express to finish their current work before killing the process?

You can checkout a working example of all of the code from this article here. I’m using npm packages mongoose@5.9.10, express@4.17.1, and redis@3.0.2 in the following code snippets.

First, let’s setup our express server.

Environment Variables

Now that we have our express server let’s grab our configuration from environment variables.

Configuring Mongoose Client

Next, let’s log all Mongoose related events that could happen. I highly recommend sending error events to your error tracker.

After we have all Mongoose events being logged let’s connect to Mongoose. According to Mongoose’s docs if Mongoose fails to initially connect to Mongo it will not automatically attempt to reconnect. So, let’s build our own reconnect logic with a simple exponential backoff algorithm.

Note that Mongoose will handle reconnecting after you’ve initially established a connection to Mongo.

Configuring Redis Client

Redis thankfully handles initial reconnection logic so all we need to do is log events that our Redis client emits.

Application Startup

When our process starts up we don’t want to start accepting HTTP requests in Express until we’ve successfully connected to Redis and Mongo. So, let’s add that logic in as well.

Application Termination

When our application’s process receives a termination signal we don’t want to just kill the process because we could have inflight calls to Mongo, Redis, or Express. Instead, we want to first close Express and then close Mongo and Redis. Lastly, if for some reason we haven’t cleanly closed Mongo, Redis, and Express within a given amount of time we’ll tell the process to go ahead and exit.

And that’s it! Lastly, you can find a working example of the code in this github repo.

--

--

Phillip Whisenhunt
The Startup

Staff Software Engineer @Procore. Previously @InVisionApp, @Olark and @HomeAway. @Virginia_Tech Alumni. pwhisenhunt.github.io