node-redis icon indicating copy to clipboard operation
node-redis copied to clipboard

Socket Closed Unexpectedly after 1 minute

Open niall-nai opened this issue 9 months ago • 8 comments

Description

Exactly 1 minute after a connection has successfully been established to Redis, the client is failing with a "Socket Closed Unexpectedly" error. Following other issues raised on this, have tried changing the tcp-keepalive and timeout values in Redis to match with the defaults for this library (5000ms), with no improvement. This has only started happening following a recent update to Redis 5.1.0 from the previous version of 3.1.2. We are also using RedisStore from the connect-redis library alongside this one

Minimal code example:

import session from 'express-session';
import { RedisStore } from 'connect-redis';
import { createClient } from 'redis';
import { logger } from './logger';
import { getConfig } from './config/ValidateConfig';
import { BaseHttpsConfig, RedisConfig } from './config';

export const configureSession = (): session.SessionOptions => {
  let isConnected = false;
  const redisConfig = getConfig(RedisConfig);
  const httpsConfig = getConfig(BaseHttpsConfig);

  const redisClient = createClient({
    url: `redis://${redisConfig.REDIS_USERNAME}:${redisConfig.REDIS_PASSWORD}@${redisConfig.REDIS_HOSTNAME}:${redisConfig.REDIS_PORT}`,
  });

  redisClient.on('connect', () => {
    // This ensure that the log message is only called once
    // Connect event can happen many times due to timeouts on the redis instance being configured to a small value
    if (!isConnected) {
      logger.info(
        `Successfully connected to Redis on host: ${redisConfig.REDIS_HOSTNAME}:${redisConfig.REDIS_PORT}`
      );
    }
    isConnected = true;
  });

  redisClient.on('reconnecting', () => {
    logger.warn('Lost connection Redis, attempting reconnect...');
    if (isConnected) {
      isConnected = false;
    }
  });

  redisClient.on('error', (err) => {
    logger.error(`Error on Redis Connection: ${err.message}`);
    logger.error('Process will now exit.');
    throw err;
  });

  redisClient.on('end', () => {
    logger.warn('Redis Client Connection terminated');
    if (isConnected) {
      isConnected = false;
    }
  });

  redisClient.connect();

  return {
    store: new RedisStore({ client: redisClient }),
    name: redisConfig.REDIS_COOKIE_NAME,
    secret: redisConfig.REDIS_SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    cookie: {
      secure: httpsConfig.HTTPS_ENABLED,
      httpOnly: true,
      maxAge: redisConfig.REDIS_SESSION_EXPIRY_MILLIS,
    },
  };
};

Node.js Version

20.10.0

Redis Server Version

6.2.1

Node Redis Version

5.1.0

Platform

Linux

Logs

13:58:50 info: Successfully connected to Redis on host: [redacted]
...
13:59:50 error: Error on Redis Connection: Socket closed unexpectedly
13:59:50 error: Process will now exit
SocketClosedUnexpectedlyError: Socket closed unexpectedly
    at Socket.<anonymous> (/node_module/@redis/client/dist/lib/client/socket.js:232:33)
    at Object.onceWrapper (node:events:639:26)
    at Socket.emit (node:events:524:28)
    at TCP.<anonymous> (node:net:343:12)

niall-nai avatar Feb 24 '26 10:02 niall-nai

Should also note that this issue only manifests when running on an environment where Redis is on a different host to the client - in single-host environments this has not occurred.

niall-nai avatar Feb 24 '26 10:02 niall-nai

@niall-nai latest version is 5.11.0. I believe there were some fixes regarding socket timeout. Can you upgrade to the latest version and try again?

nkaradzhov avatar Feb 24 '26 16:02 nkaradzhov

@nkaradzhov ok thanks, we've upgraded to that and also exposed some more of the environment variables to see if we can get those to work - will update if anything changes

niall-nai avatar Feb 25 '26 15:02 niall-nai

@nkaradzhov apologies for the delay- looks like that's not resolved the issue according to the customer. Have updated to include:

const redisClient = createClient({
    url: `redis://${redisConfig.REDIS_USERNAME}:${redisConfig.REDIS_PASSWORD}@${redisConfig.REDIS_HOSTNAME}:${redisConfig.REDIS_PORT}`,
    socket: {
      keepAlive: true,
      keepAliveInitialDelay: redisConfig.REDIS_KEEPALIVE_DELAY_MILLIS,
      timeout: redisConfig.REDIS_CONNECTION_TIMEOUT_MILLIS,
    },
  });

And the reports we're getting are that the issue persists. I've suggested setting values to 0 (ie disabling?) but other than that it looks like we're out of ideas

niall-nai avatar Mar 10 '26 14:03 niall-nai

We've also attempted a downgrade to v4.x on this and seeing similar behaviour- for now we're going to have to revert to v3.x unless there's a better solution

niall-nai avatar Mar 17 '26 14:03 niall-nai

This looks to have been an undocumented change between 3.x and 4.x where a socket disconnect is no longer considered a "reconnecting" event, but instead an "error" event.

niall-nai avatar Apr 09 '26 07:04 niall-nai

I'm seeing this error in one of our apps too. I'll share some details here, perhaps we can separate enough signal from noise to find a root cause.

  • Error started occurring after a dual upgrade
    • GCP MemoryStore Redis from 6.x to 7.2
    • This library from 4.7.0 to 5.11.0
  • It only occurs in only 1 of 3 applications, all NestJS, sharing a service using a Redis client. Each is talking to the same Redis instance, using the same library version.
  • Just letting the application idle, no incoming traffic or background tasks, and the socket will be disrupted in 10-15 minutes.

I haven't found the root cause yet, but ensuring that there's a proper on('error' and reconnectStrategy configured will restore the connection and prevent the application crashing with an uncaughtException

If I find some time, I'll try and run a profiler on it.

rickdgeerling avatar Apr 22 '26 07:04 rickdgeerling

Thanks both for the detailed reports — there's enough signal here to close this out.

What you're seeing is almost certainly a network middlebox (load balancer, NAT, cloud proxy/firewall) reaping the idle TCP connection. It fits the symptoms exactly: it only happens cross-host, at a fixed interval, while the connection is idle. @rickdgeerling's GCP MemoryStore case is the same pattern. node-redis sends nothing at the application layer while idle, so an intermediary that enforces an idle timeout will drop the socket.

This is expected and there are supported ways to handle it:

  1. Set pingInterval (ms) so the client sends periodic PINGs and keeps the connection alive through the idle timeout. This is the recommended fix for idle-timeout environments — see the note in docs/client-configuration.md. Set it below your infrastructure's idle timeout (e.g. pingInterval: 30000 for a ~60s reaper).

  2. Do not throw inside your on('error') handler. Re-throwing turns a recoverable disconnect into an uncaughtException and kills the process before the client can reconnect. Log it instead.

  3. Rely on the default reconnectStrategy (or configure your own). On an unexpected close the client emits error and then reconnects automatically — so with a non-throwing error handler the connection recovers on its own.

On the 3.x→4.x difference you noted: from v4 onward an unexpected socket close surfaces as an error event and the client reconnects via reconnectStrategy, rather than a bare reconnecting event. This is documented in the reconnect-strategy section. The client does still reconnect by default; the crash you saw came from the re-thrown error, not from the disconnect itself.

Recommended config:

const client = createClient({
  url,
  pingInterval: 30000,
  socket: { reconnectStrategy: (retries) => Math.min(retries * 50, 2000) }
});
client.on('error', (err) => logger.error(`Redis error: ${err.message}`)); // no throw

Closing as resolved by existing configuration. Happy to reopen if pingInterval set below your infrastructure's idle timeout, plus a non-throwing error handler, still drops the connection — in that case please share the value used and confirm whether reconnect is firing.

nkaradzhov avatar Jul 01 '26 08:07 nkaradzhov