0

I'm tinkering my API on node.js with caching, supporting graceful degradation. While testing app with redis container being disabled, node-redis is trying to reconnect every five seconds. The problem is that reconnection attempts can not be set. It seems like it can be set only in ioredis library. So, every five seconds I see these amount of exception on my terminal. Of course I can just skip logging part, but my app still processing those errors, and filtering this type of exception will only add tasks number. I want just one-three attempts, not a hundreds.

And also "ready" event is not what I personally expect, why would it be emitted while not opened connection?

static async init() {
    if (!process.env.REDIS_HOST || !process.env.REDIS_PORT || !process.env.REDIS_TTL) {
        Logger.error('Redis configuration missing - running without cache');
        return;
    }

    try {
        this.#client = await createClient({
            socket: {
                host: process.env.REDIS_HOST,
                port: Number(process.env.REDIS_PORT),
                connectTimeout: 1000,
                reconnectStrategy: 5000
            },
            disableOfflineQueue: false,
        });

        this.#attachHandlers();
        await this.#client.connect();
    } catch (err) {
        Logger.warn(`Redis init failed: ${err}. Cache disabled`);
    }
}

static #attachHandlers() {
    this.#client.on("error", (err) => {
        console.log(performance.now());
        Logger.warn(`Redis error: ${err.message}`)
    });
    this.#client.on("end", () => Logger.info(`Redis connection has been closed`));
    this.#client.on("connection", () => Logger.info(`Initiating a connection to the Redis`));
    this.#client.on("reconnecting", () => Logger.info(`Reconnecting to the Redis`));
    this.#client.on("ready", () => Logger.info(`Redis connection established`));
}
  • Tried to set connectTimeout but even with 100 milliseconds window, tens of exceptions were emitted
  • Property reconnectStrategy is only used for setting timeout for particular window, idk how to use any how
  • Checked official docs, useless at that point

2 Answers 2

0

The reconnectStrategy is defined as
reconnectStrategy?: false | number | ReconnectStrategyFunction;
Setting it to false will disable the reconnects, another option would be to write your own ReconnectStrategyFunction.

There's a whole section about it in the client-configuration.md

Sign up to request clarification or add additional context in comments.

4 Comments

My question was about setting number of reconnection attempts, not disabling it. Documentation is not helping with it.
The first argument that ReconnectStrategyFunction accepts is the number of retries, based on it you can return false if you wan't to stop the reconnection attempts
Settings false will prevent all future attempts of reconnection, so return false is very bad idea. I want to set number of reconnection attempts in one reconnectStrategy tick.
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

Just check the number of retries as in the following example:

createClient({
  socket: {
    reconnectStrategy: (retries, cause) => {
        // By default, do not reconnect on socket timeout.
        console.log("RETRIES", retries);
          if (retries > 10) {
            console.log("Canceling Connection");
            return false;
          }

        // Generate a random jitter between 0 – 200 ms:
        const jitter = Math.floor(Math.random() * 200);
        // Delay is an exponential back off, (times^2) * 50 ms, with a maximum value of 2000 ms:
        const delay = Math.min(Math.pow(2, retries) * 50, 2000);

        return delay + jitter;
    }
  }
});

link to an example

On a side note, be careful to add exception handling or the process will terminate.

2 Comments

Retries variable is always - 0, and returning false will prevent all future connection attempts. This is not a solution
@Stas as you can see in my sandbox, retries is not always zero. if that happens in your use case, then something else is happening. please provide more details on how is the static method init called, so that i can debug further. Also provide your version of node-redis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.