node-redis: Socket closed unexpectedly

 this.redisClient = redis.createClient({
			url: `redis://${redisHost}:${redisPort}`,
			socket: {
				connectTimeout: 60000,
				keepAlive: 60000,
				reconnectStrategy: (attempts) => {
					logger.log(`Redis reconnecting attempt ${attempts}`);
					if (attempts == 1) {
						console.log(`${this.constructor.name} failed to connect to ${redisHost}:${redisPort}. Reconnecting...`);
					}
					return 500;
				},
			},
			password: ******
		});
		this.redisClient.on('error', err => logger.error(err, "Redis v4 client error"));
		this.redisClient.on('connect', () => logger.log('Redis v4 is connect'));
		this.redisClient.on('reconnecting', () => logger.log('Redis v4 is reconnecting'));
		this.redisClient.on('ready', () => logger.log('Redis v4 is ready'));
		this.redisClient.connect(); 

between my app service and redis service, there is an aws NLB-network load balancer. I have four redis client created, and every 2 minutes will get this error: “error: Socket closed unexpectedly”

Environment:

  • Node.js Version: “16.16”
  • Redis Server Version: “6.2”
  • Node Redis Version: “4.3.1”
  • Platform: aws Ecs

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 26

Commits related to this issue

Most upvoted comments

Switched to ioredis for now… this library is not suitable for production use until the issue is fixed.

@thorep if the solutions discussed above don’t work, just use ioredis. Setting connection timeout to 0 didn’t work for me, so I migrated to ioredis and it just works.

@richardsun2021 in the meantime you can use this code to do (almost) the exact thing:

setInterval(client => {
  client.ping((err) => {
    if (err) console.error('Redis keepalive error', err);
  });
}, 9*1000*60);
// azure is closing the socket after 10m of idle time, pinging every 9m seems like a reasonable choice

@josh803316 it should reconnect after this error, do you have a listener to error (see #2302)? AFAIK AWS honors TCP keep-alive, I don’t think pingInteval will help in your case…