IORedis Reconnect Strategy and Sentinel Failover

Harden ioredis connections with retry backoff, command timeouts, and sentinel failover so cache clients survive restarts and primary swaps.

JavascriptNodeResilience

Code

javascriptsnippet
21 lines
import Redis from 'ioredis';

const client = new Redis({
  sentinels: [
    { host: '10.0.0.11', port: 26379 },
    { host: '10.0.0.12', port: 26379 },
  ],
  name: 'mymaster',
  password: process.env.REDIS_PASSWORD,
  sentinelRetryStrategy: (times) => Math.min(times * 200, 5000),
  retryStrategy: (times) => Math.min(times * 100, 3000),
  maxRetriesPerRequest: 2,
  commandTimeout: 1500,
  enableOfflineQueue: false,
});

client.on('error', (err) => console.error('redis error:', err.message));
client.on('reconnecting', (delay) => console.log('reconnecting in', delay, 'ms'));

await client.set('session:42', 'active', 'EX', 900);
const state = await client.get('session:42');

What the code does

The asynchronous flow is linearized with await, keeping failure handling local.

The demo data lives in module-level bindings: client, state.

Configuration comes from the environment — it reads REDIS_PASSWORD, so the same code switches behavior between environments without edits.

Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.

Points of care

  • Plan for an install step: ioredis is a real dependency, resolved by the package manager.

Using it

Running the file prints labeled results such as redis error:, reconnecting in — each operation’s effect is visible in the output.

Key statements

await client.set('session:42', 'active', 'EX', 900);
const state = await client.get('session:42');

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `ioredis`. Without it the snippet will not load.