socket.reconnectStrategy
In the modern node‑redis client (v4 and later), you don’t use the old retry_strategy
option. Instead, you configure reconnection using the socket.reconnectStrategy
option when creating a client:
js
CopyEdit
import{ createClient } from 'redis'; const client = createClient({ socket: { reconnectStrategy: (retries, cause) => { if (retries >= MAX_ATTEMPTS) { return new Error('Too many reconnect attempts'); } // Return a delay in ms before next retry return calculateDelay(retries); } } }); client.on('error', err => console.error('Redis error', err)); await client.connect();
retries
is the count of attempts so far, starting at 0.
cause
is the Error that triggered this reconnect attempt.
If the function returns:
false
or new Error(…)
→ stop retrying.
a number (ms) → that’s the delay before the next attempt.
This gives full control—you can stop after a fixed number or vary delay. npm+12Redis+12Stack Overflow+12Stack OverflowUNPKG+4Redis Documentation+4Snyk+4
node-redis-retry-strategy
packageIf you're using legacy clients expecting retry_strategy
, or you need a drop‑in function:
The node-redis-retry-strategy
package provides a strategy where you can configure:
number_of_retry_attempts
(default 5)
delay_of_retry_attempts
(default 500 ms)
wait_time
(how long before quitting retries, default 300 000 ms) npm+2UNPKG+2Snyk+2
Example:
js
CopyEdit
constredis = require('redis'); const retryStrategy = require('node-redis-retry-strategy'); const client = redis.createClient({ host: '127.0.0.1', port: 6379, retry_strategy: retryStrategy({ number_of_retry_attempts: 7, delay_of_retry_attempts: 1000, wait_time: 600000 }) });
This is helpful if you’re migrating older code or using compatibility layers. UNPKGSnyk
In node‑redis v4+, retry_strategy
, max_attempts
, retry_max_delay
, and connect_timeout
are deprecated.
Instead, custom reconnect logic is done via socket.reconnectStrategy
. By default, reconnection is disabled unless you specify a strategy. Redis+8Stack Overflow+8Snyk+8
Default behavior without configuration is: no reconnection, so if you don’t provide reconnectStrategy
, the client won’t retry.
ScenarioHow to set retry countExample
behaviorNew node‑redis (v4+)Use socket.reconnectStrategyYour custom function handles limits and delayLegacy code expecting retry_strategyUse node-redis-retry-strategy packageConfigure with number_of_retry_attempts etc.
Imagine Redis connection drops. You want it to try reconnecting a few times—say 5 attempts—with increasing wait times. In modern node‑redis, you hand it a little function:
js
CopyEdit
reconnectStrategy: (retries, err) => { if (retries >= 5) return new Error('Reached retry limit'); return retries * 500 + Math.random() * 100; }
That way, if Redis goes offline, your app will give it up after the 5th try. Before then, it’s patiently trying again with a touch of randomness (jitter).