Azure Cache for Redis failover reconnect

Someone 20 Reputation points
2024-08-02T06:28:20.9666667+00:00

I'm using Azure Cache for Redis.

When using the node-redis package to connect to Redis in Node.js, there's an issue with automatically reconnecting when Redis doing an upgrade. In .NET, you can use ForceReconnect, but how can this be implemented in Node.js?

Here are the settings:

const redisConfig = {
    url: `redis://${REDIS_HOST}:${REDIS_PORT}`,
    socket: {
        host: REDIS_HOST,
        port: Number(REDIS_PORT),
        reconnectStrategy: (retries) => (retries < 5 ? 100 : 5000),
    },
    password: REDIS_PWD,
    database: Number(REDIS_DB_NUMBER),
    // Azure Redis has a 10-minute timeout for idle connections
    pingInterval: 4 * 60 * 1000,
};
Azure Cache for Redis
Azure Cache for Redis
An Azure service that provides access to a secure, dedicated Redis cache, managed by Microsoft.
260 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Someone 20 Reputation points
    2024-10-18T08:12:46.2733333+00:00

    @Oury Ba-MSFT
    The support ticket indicates that during an update at either the Redis or OS level, as well as during a manual reboot (https://zcusa.951200.xyz/en-us/azure/azure-cache-for-redis/cache-failover#explanation-of-a-failover), the Redis server will send a FIN network packet to notify the client. If the client's logic can correctly identify the FIN packet, disconnect, and then re-establish the connection, the client can quickly reconnect.

    Here's my solution:

    const client = redis.createClient(redisConfig);
    
    // REAL CASE should wrapped in async function
    client.connect();
    
    client.on('error', async (err) => {
        switch (err.message) {
            // SOLUTION
            case 'Socket closed unexpectedly':
                console.log('Closing Redis connection...');
                await client.disconnect();
                await utils.sleep(3000);
                console.log('Trying reconnecting Redis...');
                await client.connect();
                break;
            default:
                break;
        }
    });
    

    I am unable to verify it now, and will have to wait until the next update to confirm if it's effective.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.