Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 851
Yash Dixit Avatar asked Jan 23 '26 13:01

Yash Dixit


2 Answers

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. 
});
like image 128
Yash Dixit Avatar answered Jan 26 '26 06:01

Yash Dixit


I had similar issue of socket close unexpectedly. The issue started while I upgraded node-redis from 3.x to 4.x. The issue was gone after I upgraded my redis-server from 5.x to 6.x.

like image 38
Jack Lin Avatar answered Jan 26 '26 05:01

Jack Lin