Search code examples
node.jssocketsredisnode-redis

Reusing Redis Connection: Socket Closed Unexpectedly - node-redis


First, let me tell you how I'm using Redis connection in my NodeJS application:

  • I'm re-using one connection throughout the app using a singleton class.
class RDB {

    static async getClient() {
        if (this.client) {
            return this.client
        }

        let startTime = Date.now();

        this.client = createClient({
            url: config.redis.uri
        });

        await this.client.connect();

        return this.client;
    }

}

For some reason - that I don't know - time to time my application crashes giving an error without any reason - this happens about once or twice a week:

Error: Socket closed unexpectedly

Now, my questions:

  1. Is using Redis connections like this alright? Is there something wrong with my approach?
  2. Why does this happen? Why is my socket closing unexpectedly?
  3. Is there a way to catch this error (using my approach) or any other good practice for implementing Redis connections?

Solution

  • I solved this using the 'error' listener. Just listening to it - saves the node application from crashing.

    client.on("error", function(error) {
       console.error(error);
       // I report it onto a logging service like Sentry. 
    });