DEV Community

Tim Nguyen
Tim Nguyen

Posted on

Node.js + ioredis + elasticache

For who is struggling with ioredis connection to elasticache (cluster enable)

const REDIS_COMMAND_TIMEOUT = 10000;
const MAX_REDIS_ATTEMPS = 3;
const REDIS_BACKOFF_RETRY = 2000;

const REDIS_HOST = process.env.REDIS_HOST || '127.0.0.1';
const REDIS_PORT = Number(process.env.REDIS_PORT) || 6379;

// https://github.com/redis/lettuce/wiki/Redis-URI-and-connection-details
const REDIS_SCHEME = REDIS_CLUSTER_ENABLED ? `rediss` : `redis`;

const redis = new Redis(`${REDIS_SCHEME}://${REDIS_HOST}:${REDIS_PORT}`, {
  commandTimeout: REDIS_COMMAND_TIMEOUT,
  retryStrategy: (times: number): number | null => {
    if (times > MAX_REDIS_ATTEMPS) {
      return null; // Stop retrying
    }
    return REDIS_BACKOFF_RETRY; // Retry after some time
  },
  tls: REDIS_CLUSTER_ENABLED ? {} : undefined,
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay