leotron
leotron

Reputation: 99

How can I prevent redis from crashing the entire application on connection error?

I'm using the redis npm package in a TypeScript Node.js app. If redis fails to connect, it takes my app down with it regardless of how many try-catch blocks I use. Modifying the client.on("error"... hook doesn't have an effect.

The following code (from 2016) is supposed to solve the issue:

const client = redis.createClient({
  retry_strategy: function (options) {
    if (options.error.code === "ECONNREFUSED") {
      // This will suppress the ECONNREFUSED unhandled exception
      // that results in app crash
      return;
    }
  }
});

However I get a TypeScript error:

Argument of type '{ retry_strategy: (options: any) => void; }' is not assignable to parameter of type 'RedisClientOptions<RedisModules, RedisFunctions, RedisScripts>'.

Even if I add @ts-ignore, the solution above has no effect.

Another way to solve this is to use ioredis, but I want to use the redis package. Any ideas how to solve this?

Upvotes: 0

Views: 2108

Answers (2)

Leibale Eidelman
Leibale Eidelman

Reputation: 3194

In case of an error (such as a network error), the client will emit an error event (which you'll have to handle, otherwise the process will crash. see here) -> call reconnectStrategy (which in most cases you shouldn't override, the default one will retry with a backoff between 0-500ms, depends of the number of retries) to decide if it needs to reconnect, and the backoff strategy -> reconnect to the server -> keep processing the commands in the queue. You can read more about this here and here.

Upvotes: 1

leotron
leotron

Reputation: 99

So far the only working solution (that doesn't rely on other libraries) seems to be to disconnect when encountering an error:

client.on("error", (e) => {
  // handle error
  client.disconnect();
});

Upvotes: 0

Related Questions